Skip to content

A platform for community discussion. Free, open, simple.

DEV: Convert admin user, API key, log and web hook models to TypeScript (#45205)

Sérgio Saquetim3c9c7ba641cb
diff --git a/frontend/discourse/admin/models/admin-user.js b/frontend/discourse/admin/models/admin-user.js
deleted file mode 100644
index 03ebbd07d19..00000000000
--- a/frontend/discourse/admin/models/admin-user.js
+++ /dev/null
@@ -1,460 +0,0 @@
-import { computed } from "@ember/object";
-import { ajax } from "discourse/lib/ajax";
-import { popupAjaxError } from "discourse/lib/ajax-error";
-import getURL from "discourse/lib/get-url";
-import { deepEqual } from "discourse/lib/object";
-import { autoTrackedArray } from "discourse/lib/tracked-tools";
-import { applyBehaviorTransformer } from "discourse/lib/transformer";
-import { userPath } from "discourse/lib/url";
-import User from "discourse/models/user";
-import { i18n } from "discourse-i18n";
-
-export default class AdminUser extends User {
- /**
- * Retrieves user details for the specified user ID and formats the result based on the provided options.
- *
- * @param {string|number} user_id - The ID of the user to be retrieved.
- * @param {Object} [opts] - Options to customize the result format.
- * @param {boolean} [opts.raw=false] - If true, returns the raw response instead of formatting it using AdminUser.create.
- * @return {Promise<Record<string, unknown>|AdminUser>} A promise that resolves with either the raw response object or an instance of AdminUser.
- */
- static async find(user_id, opts = { raw: false }) {
- const result = await ajax(`/admin/users/${user_id}.json`);
- result.loadedDetails = true;
-
- if (Object.hasOwn(result, "groups")) {
- result.visibleGroups = result.groups;
- delete result.groups;
- }
-
- return opts?.raw ? result : AdminUser.create(result);
- }
-
- static findAll(query, userFilter) {
- return ajax(`/admin/users/list/${query}.json`, {
- data: userFilter,
- }).then((users) => users.map((u) => AdminUser.create(u)));
- }
-
- adminUserView = true;
-
- @autoTrackedArray visibleGroups;
-
- @computed("active", "staged")
- get canViewProfile() {
- return this.active || this.staged;
- }
-
- @computed("bounce_score")
- get canResetBounceScore() {
- return this.bounce_score > 0;
- }
-
- @computed("originalTrustLevel", "trust_level")
- get dirty() {
- return !deepEqual(this.originalTrustLevel, this.trust_level);
- }
-
- @computed("trust_level")
- get canLockTrustLevel() {
- return this.trust_level < 4;
- }
-
- @computed("staff")
- get canSuspend() {
- return !this.staff;
- }
-
- @computed("staff")
- get canSilence() {
- return !this.staff;
- }
-
- get customGroups() {
- return this.visibleGroups?.filter((g) => !g.automatic) ?? [];
- }
-
- get automaticGroups() {
- return this.visibleGroups?.filter((g) => g.automatic) ?? [];
- }
-
- @computed("bounce_score", "reset_bounce_score_after")
- get bounceScore() {
- if (this.bounce_score > 0) {
- return `${this.bounce_score} - ${moment(
- this.reset_bounce_score_after
- ).format("LL")}`;
- } else {
- return this.bounce_score;
- }
- }
-
- @computed("bounce_score")
- get bounceScoreExplanation() {
- if (this.bounce_score === 0) {
- return i18n("admin.user.bounce_score_explanation.none");
- } else if (this.bounce_score < this.siteSettings.bounce_score_threshold) {
- return i18n("admin.user.bounce_score_explanation.some");
- } else {
- return i18n("admin.user.bounce_score_explanation.threshold_reached");
- }
- }
-
- @computed
- get bounceLink() {
- return getURL("/admin/email-logs/bounced");
- }
-
- @computed("suspended_till", "suspended_at")
- get suspendDuration() {
- const suspendedAt = moment(this.suspended_at);
- const suspendedTill = moment(this.suspended_till);
- return suspendedAt.format("L") + " - " + suspendedTill.format("L");
- }
-
- @computed("tl3_requirements")
- get tl3Requirements() {
- if (this.tl3_requirements) {
- return this.store.createRecord("tl3Requirements", this.tl3_requirements);
- }
- }
-
- @computed("suspended_by")
- get suspendedBy() {
- return this.suspended_by ? AdminUser.create(this.suspended_by) : null;
- }
-
- @computed("silenced_by")
- get silencedBy() {
- return this.silenced_by ? AdminUser.create(this.silenced_by) : null;
- }
-
- @computed("approved_by")
- get approvedBy() {
- return this.approved_by ? AdminUser.create(this.approved_by) : null;
- }
-
- resetBounceScore() {
- return ajax(`/admin/users/${this.id}/reset-bounce-score`, {
- type: "POST",
- }).then(() =>
- this.setProperties({
- bounce_score: 0,
- reset_bounce_score_after: null,
- })
- );
- }
-
- async groupAdded(added) {
- await ajax(`/admin/users/${this.id}/groups`, {
- type: "POST",
- data: { group_id: added.id },
- });
-
- this.visibleGroups.push(added);
- }
-
- groupRemoved(groupId) {
- return ajax(`/admin/users/${this.id}/groups/${groupId}`, {
- type: "DELETE",
- }).then(() => {
- this.visibleGroups = this.visibleGroups.filter(
- (group) => group.id !== groupId
- );
- if (this.primary_group_id === groupId) {
- this.set("primary_group_id", null);
- }
- });
- }
-
- deleteAllPosts() {
- return ajax(`/admin/users/${this.get("id")}/delete_posts_batch`, {
- type: "PUT",
- });
- }
-
- deleteAllPostsDecider() {
- return ajax(`/admin/users/${this.get("id")}/delete_posts_decider`, {
- type: "POST",
- });
- }
-
- revokeAdmin() {
- return ajax(`/admin/users/${this.id}/revoke_admin`, {
- type: "PUT",
- }).then((resp) => {
- this.setProperties({
- admin: false,
- can_grant_admin: true,
- can_revoke_admin: false,
- can_be_merged: resp.can_be_merged,
- can_be_anonymized: resp.can_be_anonymized,
- can_be_deleted: resp.can_be_deleted,
- can_delete_all_posts: resp.can_delete_all_posts,
- });
- });
- }
-
- grantAdmin(data) {
- return ajax(`/admin/users/${this.id}/grant_admin`, {
- type: "PUT",
- data,
- }).then((resp) => {
- if (resp.success && !resp.email_confirmation_required) {
- this.setProperties({
- admin: true,
- can_grant_admin: false,
- can_revoke_admin: true,
- });
- }
-
- return resp;
- });
- }
-
- revokeModeration() {
- return ajax(`/admin/users/${this.id}/revoke_moderation`, {
- type: "PUT",
- })
- .then((resp) => {
- this.setProperties({
- moderator: false,
- can_grant_moderation: true,
- can_revoke_moderation: false,
- can_be_merged: resp.can_be_merged,
- can_be_anonymized: resp.can_be_anonymized,
- });
- })
- .catch(popupAjaxError);
- }
-
- grantModeration() {
- return ajax(`/admin/users/${this.id}/grant_moderation`, {
- type: "PUT",
- })
- .then((resp) => {
- this.setProperties({
- moderator: true,
- can_grant_moderation: false,
- can_revoke_moderation: true,
- can_be_merged: resp.can_be_merged,
- can_be_anonymized: resp.can_be_anonymized,
- });
- })
- .catch(popupAjaxError);
- }
-
- disableSecondFactor() {
- return ajax(`/admin/users/${this.id}/disable_second_factor`, {
- type: "PUT",
- })
- .then(() => {
- this.set("second_factor_enabled", false);
- })
- .catch(popupAjaxError);
- }
-
- approve(approvedBy) {
- return ajax(`/admin/users/${this.id}/approve`, {
- type: "PUT",
- }).then(() => {
- this.setProperties({
- can_approve: false,
- approved: true,
- approved_by: approvedBy,
- });
- });
- }
-
- setOriginalTrustLevel() {
- this.set("originalTrustLevel", this.trust_level);
- }
-
- saveTrustLevel() {
- return ajax(`/admin/users/${this.id}/trust_level`, {
- type: "PUT",
- data: { level: this.trust_level },
- });
- }
-
- restoreTrustLevel() {
- this.set("trust_level", this.originalTrustLevel);
- }
-
- lockTrustLevel(locked) {
- return ajax(`/admin/users/${this.id}/trust_level_lock`, {
- type: "PUT",
- data: { locked: !!locked },
- });
- }
-
- suspend(data) {
- return ajax(`/admin/users/${this.id}/suspend`, {
- type: "PUT",
- data,
- }).then((result) => this.setProperties(result.suspension));
- }
-
- unsuspend() {
- return applyBehaviorTransformer(
- "admin-user-unsuspend",
- () =>
- ajax(`/admin/users/${this.id}/unsuspend`, {
- type: "PUT",
- }).then((result) => this.setProperties(result.suspension)),
- { user: this }
- );
- }
-
- logOut() {
- return ajax("/admin/users/" + this.id + "/log_out", {
- type: "POST",
- data: { username_or_email: this.username },
- });
- }
-
- impersonate() {
- return ajax("/admin/impersonate", {
- type: "POST",
- data: { username_or_email: this.username },
- });
- }
-
- activate() {
- return ajax(`/admin/users/${this.id}/activate`, {
- type: "PUT",
- });
- }
-
- deactivate() {
- return ajax(`/admin/users/${this.id}/deactivate`, {
- type: "PUT",
- data: { context: document.location.pathname },
- });
- }
-
- unsilence() {
- return applyBehaviorTransformer(
- "admin-user-unsilence",
- () => {
- this.set("silencingUser", true);
-
- return ajax(`/admin/users/${this.id}/unsilence`, {
- type: "PUT",
- })
- .then((result) => {
- this.setProperties({
- silence_reason: result.unsilence.silence_reason,
- full_silence_reason: result.unsilence.full_silence_reason,
- silenced_at: result.unsilence.silence_at,
- silenced_till: result.unsilence.silence_till,
- });
- })
- .finally(() => this.set("silencingUser", false));
- },
- { user: this }
- );
- }
-
- silence(data) {
- this.set("silencingUser", true);
-
- return ajax(`/admin/users/${this.id}/silence`, {
- type: "PUT",
- data,
- })
- .then((result) => {
- this.setProperties({
- silence_reason: result.silence.silence_reason,
- full_silence_reason: result.silence.full_silence_reason,
- silenced_at: result.silence.silenced_at,
- silenced_by: result.silence.silenced_by,
- silenced_till: result.silence.silenced_till,
- });
- })
- .finally(() => this.set("silencingUser", false));
- }
-
- sendActivationEmail() {
- return ajax(userPath("action/send_activation_email"), {
- type: "POST",
- data: { username: this.username },
- });
- }
-
- anonymize() {
- return ajax(`/admin/users/${this.id}/anonymize.json`, {
- type: "PUT",
- });
- }
-
- deleteAssociatedAccounts() {
- return ajax(`/admin/users/${this.id}/delete_associated_accounts`, {
- type: "PUT",
- data: {
- context: window.location.pathname,
- },
- }).then(() => {
- this.set("associated_accounts", []);
- });
- }
-
- /**
- * The unreachable overload preserves the inherited framework destruction contract.
- *
- * @overload
- * @param {never} this
- * @returns {never}
- */
- /**
- * @overload
- * @param {Record<string, unknown>} formData
- * @returns {Promise<unknown>}
- */
- destroy(formData) {
- return ajax(`/admin/users/${this.id}.json`, {
- type: "DELETE",
- data: formData,
- })
- .then((data) => {
- if (!data.deleted && data.user) {
- this.setProperties(data.user);
- }
-
- return data;
- })
- .catch(() => {
- this.find(this.id).then((u) => this.setProperties(u));
- });
- }
-
- merge(formData) {
- return ajax(`/admin/users/${this.id}/merge.json`, {
- type: "POST",
- data: formData,
- });
- }
-
- async loadDetails() {
- if (this.loadedDetails) {
- return this;
- }
-
- // we need to ask find to provide a raw object instead of AdminUser model because we're using
- // setProperties to update the values. Otherwise we would miss tracked properties which are not enumerable.
- const userProperties = await AdminUser.find(this.id, { raw: true });
- this.setProperties(userProperties);
-
- return this;
- }
-
- deleteSSORecord() {
- return ajax(`/admin/users/${this.id}/sso_record.json`, {
- type: "DELETE",
- })
- .then(() => {
- this.set("single_sign_on_record", null);
- })
- .catch(popupAjaxError);
- }
-}
diff --git a/frontend/discourse/admin/models/admin-user.ts b/frontend/discourse/admin/models/admin-user.ts
new file mode 100644
index 00000000000..75237c6a0c3
--- /dev/null
+++ b/frontend/discourse/admin/models/admin-user.ts
@@ -0,0 +1,680 @@
+import { computed } from "@ember/object";
+import type { Tl3RequirementsFields } from "discourse/admin/models/tl3-requirements";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import getURL from "discourse/lib/get-url";
+import { deepEqual } from "discourse/lib/object";
+import { autoTrackedArray } from "discourse/lib/tracked-tools";
+import { applyBehaviorTransformer } from "discourse/lib/transformer";
+import { userPath } from "discourse/lib/url";
+import type { GroupFields } from "discourse/models/group";
+import User, { type UserFields, type UserGroup } from "discourse/models/user";
+import { i18n } from "discourse-i18n";
+
+/** Embedded basic users are data records, not hydrated User instances. */
+export type BasicAdminUser = Pick<
+ UserFields,
+ "id" | "username" | "avatar_template" | "name"
+> & { status?: User["status"] };
+
+/** BasicGroup serializer data; the inherited UserGroup identity contract stays required. */
+export type AdminUserGroup = UserGroup & GroupFields & { user_count?: number };
+
+/** Export serialization can omit the envelope when there is no upload. */
+export interface AdminUserExport {
+ id: number;
+ filename: string;
+ uri: string;
+ filesize: number;
+ extension: string;
+ retain_hours: number;
+ human_filesize: string;
+}
+
+/** Core admin serializer additions; plugins augment this interface. All admin additions can be absent on basic users. */
+export interface AdminUserFields extends UserFields {
+ active?: boolean;
+ approved?: boolean;
+ last_emailed_at?: string | null;
+ last_seen_age?: number | null;
+ last_emailed_age?: number | null;
+ created_at_age?: number;
+ manual_locked_trust_level?: number | null;
+ can_be_suspended?: boolean;
+ can_send_activation_email?: boolean;
+ can_activate?: boolean;
+ can_deactivate?: boolean;
+ can_approve?: boolean;
+ can_change_trust_level?: boolean;
+ ip_address?: string | null;
+ registration_ip_address?: string | null;
+ include_ip?: boolean | null;
+ can_grant_admin?: boolean;
+ can_revoke_admin?: boolean;
+ can_grant_moderation?: boolean;
+ can_revoke_moderation?: boolean;
+ can_impersonate?: boolean;
+ can_be_anonymized?: boolean;
+ can_be_merged?: boolean;
+ like_count?: number;
+ like_given_count?: number;
+ post_edits_count?: number | null;
+ flags_given_count?: number;
+ flags_received_count?: number;
+ private_topics_count?: number;
+ warnings_received_count?: number;
+ full_suspend_reason?: string | null;
+ suspended_at?: string | null;
+ full_silence_reason?: string | null;
+ silenced_at?: string | null;
+ /** The detail serializer emits no total, unlike the embedded TL3 serializer. */
+ penalty_counts?: { silenced: number; suspended: number };
+ next_penalty?: string | null;
+ bounce_score?: number;
+ reset_bounce_score_after?: string | null;
+ can_view_action_logs?: boolean;
+ can_disable_second_factor?: boolean;
+ can_delete_sso_record?: boolean;
+ api_key_count?: number;
+ external_ids?: Record<string, string>;
+ similar_users_count?: number;
+ /** Captures contain only null; accept wrapped, unwrapped and empty export serialization conservatively. */
+ latest_export?:
+ | (Partial<AdminUserExport> & { user_export?: Partial<AdminUserExport> })
+ | null;
+ upcoming_changes_stats?: {
+ name: string;
+ humanized_name: string;
+ description: string;
+ enabled: boolean;
+ specific_groups: string[];
+ reason:
+ | "enabled_for_everyone"
+ | "enabled_for_no_one"
+ | "in_specific_groups"
+ | "not_in_specific_groups";
+ }[];
+ single_sign_on_record?: {
+ user_id: number;
+ external_id: string;
+ created_at: string;
+ updated_at: string;
+ external_username: string | null;
+ external_name: string | null;
+ external_avatar_url: string | null;
+ external_profile_background_url: string | null;
+ external_card_background_url: string | null;
+ } | null;
+ approved_by?: BasicAdminUser | null;
+ suspended_by?: BasicAdminUser | null;
+ silenced_by?: BasicAdminUser | null;
+ tl3_requirements?: Tl3RequirementsFields;
+ loadedDetails?: boolean;
+ originalTrustLevel?: number;
+ selected?: boolean;
+ silencingUser?: boolean;
+}
+
+/** Raw serializer data also includes fields User declares separately as tracked members. */
+export interface AdminUserWireFields extends AdminUserFields {
+ groups?: AdminUserGroup[];
+ visibleGroups?: AdminUserGroup[];
+ secondary_emails?: User["secondary_emails"];
+ associated_accounts?: User["associated_accounts"];
+ status?: User["status"];
+}
+
+/** Detail response after find marks it loaded and moves groups to visibleGroups. */
+export interface AdminUserDetails extends AdminUserWireFields {
+ loadedDetails: boolean;
+}
+
+/** List endpoint filters; query selects the list name separately. */
+export interface AdminUserFilter {
+ filter?: string;
+ show_emails?: boolean;
+ page?: number;
+ [key: string]: string | number | boolean | undefined;
+}
+
+/** Shared penalty form inputs; suspend and silence use different expiry keys. */
+export interface AdminUserPenaltyParams {
+ reason?: string;
+ message?: string;
+ post_id?: number;
+ reviewable_id?: number;
+ post_action?: string;
+ post_edit?: string;
+ other_user_ids?: number[];
+ [key: string]: unknown;
+}
+
+type Suspension = Pick<
+ AdminUserFields,
+ | "suspend_reason"
+ | "full_suspend_reason"
+ | "suspended_till"
+ | "suspended_at"
+ | "suspended_by"
+>;
+type Silencing = Pick<
+ AdminUserFields,
+ | "silence_reason"
+ | "full_silence_reason"
+ | "silenced_till"
+ | "silenced_at"
+ | "silenced_by"
+>;
+type SuccessResponse = { success: string | boolean };
+
+/** A failed deletion can return refreshed user data; the catch resolves without a value. */
+export interface AdminUserDestroyResult {
+ deleted: boolean;
+ user?: AdminUserWireFields;
+ message?: string;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface AdminUser extends AdminUserFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class AdminUser extends User {
+ /** Raw lookups return enumerable response data for setProperties rather than an instance. */
+ static find(
+ user_id: string | number,
+ opts: { raw: true }
+ ): Promise<AdminUserDetails>;
+
+ static find(
+ user_id: string | number,
+ opts?: { raw?: false } | null
+ ): Promise<AdminUser>;
+
+ static find(
+ user_id: string | number,
+ opts: { raw?: boolean } | null
+ ): Promise<AdminUserDetails | AdminUser>;
+
+ static async find(
+ user_id: string | number,
+ opts: { raw?: boolean } | null = { raw: false }
+ ): Promise<AdminUserDetails | AdminUser> {
+ // TODO(typescript-pending): ajax has no endpoint contracts; remove when admin user responses are typed.
+ const result = (await ajax(
+ `/admin/users/${user_id}.json`
+ )) as AdminUserDetails;
+ result.loadedDetails = true;
+
+ if (Object.hasOwn(result, "groups")) {
+ result.visibleGroups = result.groups;
+ delete result.groups;
+ }
+
+ return opts?.raw ? result : AdminUser.create(result);
+ }
+
+ static findAll(
+ query: string,
+ userFilter?: AdminUserFilter
+ ): Promise<AdminUser[]> {
+ return ajax(`/admin/users/list/${query}.json`, {
+ data: userFilter,
+ }).then((users: AdminUserWireFields[]) =>
+ users.map((u) => AdminUser.create(u))
+ );
+ }
+
+ adminUserView = true;
+
+ @autoTrackedArray visibleGroups: AdminUserGroup[] | undefined;
+
+ @computed("active", "staged")
+ get canViewProfile() {
+ return this.active || this.staged;
+ }
+
+ @computed("bounce_score")
+ get canResetBounceScore() {
+ // Missing scores retain JavaScript comparison semantics on partial instances.
+ return this.bounce_score! > 0;
+ }
+
+ @computed("originalTrustLevel", "trust_level")
+ get dirty() {
+ return !deepEqual(this.originalTrustLevel, this.trust_level);
+ }
+
+ @computed("trust_level")
+ get canLockTrustLevel() {
+ return this.trust_level! < 4;
+ }
+
+ @computed("staff")
+ get canSuspend() {
+ return !this.staff;
+ }
+
+ @computed("staff")
+ get canSilence() {
+ return !this.staff;
+ }
+
+ get customGroups() {
+ return this.visibleGroups?.filter((g) => !g.automatic) ?? [];
+ }
+
+ get automaticGroups() {
+ return this.visibleGroups?.filter((g) => g.automatic) ?? [];
+ }
+
+ @computed("bounce_score", "reset_bounce_score_after")
+ get bounceScore() {
+ if (this.bounce_score! > 0) {
+ return `${this.bounce_score} - ${moment(
+ this.reset_bounce_score_after
+ ).format("LL")}`;
+ } else {
+ return this.bounce_score;
+ }
+ }
+
+ @computed("bounce_score")
+ get bounceScoreExplanation(): string {
+ // TODO(typescript-pending): site settings expose unknown values; remove the assertion when bounce_score_threshold is typed.
+ if (this.bounce_score === 0) {
+ return i18n("admin.user.bounce_score_explanation.none");
+ } else if (
+ this.bounce_score! < (this.siteSettings.bounce_score_threshold as number)
+ ) {
+ return i18n("admin.user.bounce_score_explanation.some");
+ } else {
+ return i18n("admin.user.bounce_score_explanation.threshold_reached");
+ }
+ }
+
+ @computed
+ get bounceLink(): string {
+ return getURL("/admin/email-logs/bounced");
+ }
+
+ @computed("suspended_till", "suspended_at")
+ get suspendDuration() {
+ const suspendedAt = moment(this.suspended_at);
+ const suspendedTill = moment(this.suspended_till);
+ return suspendedAt.format("L") + " - " + suspendedTill.format("L");
+ }
+
+ @computed("tl3_requirements")
+ get tl3Requirements() {
+ if (this.tl3_requirements) {
+ return this.store.createRecord("tl3Requirements", this.tl3_requirements);
+ }
+ }
+
+ @computed("suspended_by")
+ get suspendedBy(): AdminUser | null {
+ return this.suspended_by ? AdminUser.create(this.suspended_by) : null;
+ }
+
+ @computed("silenced_by")
+ get silencedBy(): AdminUser | null {
+ return this.silenced_by ? AdminUser.create(this.silenced_by) : null;
+ }
+
+ @computed("approved_by")
+ get approvedBy(): AdminUser | null {
+ return this.approved_by ? AdminUser.create(this.approved_by) : null;
+ }
+
+ resetBounceScore() {
+ return ajax(`/admin/users/${this.id}/reset-bounce-score`, {
+ type: "POST",
+ }).then(() =>
+ this.setProperties({
+ bounce_score: 0,
+ reset_bounce_score_after: null,
+ })
+ );
+ }
+
+ async groupAdded(added: AdminUserGroup) {
+ await ajax(`/admin/users/${this.id}/groups`, {
+ type: "POST",
+ data: { group_id: added.id },
+ });
+
+ this.visibleGroups!.push(added);
+ }
+
+ groupRemoved(groupId: number) {
+ return ajax(`/admin/users/${this.id}/groups/${groupId}`, {
+ type: "DELETE",
+ }).then(() => {
+ this.visibleGroups = this.visibleGroups!.filter(
+ (group) => group.id !== groupId
+ );
+ if (this.primary_group_id === groupId) {
+ this.set("primary_group_id", null);
+ }
+ });
+ }
+
+ deleteAllPosts(): Promise<{ posts_deleted: number }> {
+ return ajax(`/admin/users/${this.get("id")}/delete_posts_batch`, {
+ type: "PUT",
+ });
+ }
+
+ deleteAllPostsDecider(): Promise<{
+ job_enqueued: boolean;
+ post_count: number;
+ }> {
+ return ajax(`/admin/users/${this.get("id")}/delete_posts_decider`, {
+ type: "POST",
+ });
+ }
+
+ revokeAdmin() {
+ return ajax(`/admin/users/${this.id}/revoke_admin`, {
+ type: "PUT",
+ }).then((resp: AdminUserWireFields) => {
+ this.setProperties({
+ admin: false,
+ can_grant_admin: true,
+ can_revoke_admin: false,
+ can_be_merged: resp.can_be_merged,
+ can_be_anonymized: resp.can_be_anonymized,
+ can_be_deleted: resp.can_be_deleted,
+ can_delete_all_posts: resp.can_delete_all_posts,
+ });
+ });
+ }
+
+ grantAdmin(data?: {
+ email_confirmation_token?: string;
+ [key: string]: unknown;
+ }) {
+ return ajax(`/admin/users/${this.id}/grant_admin`, {
+ type: "PUT",
+ data,
+ }).then(
+ (resp: SuccessResponse & { email_confirmation_required?: boolean }) => {
+ if (resp.success && !resp.email_confirmation_required) {
+ this.setProperties({
+ admin: true,
+ can_grant_admin: false,
+ can_revoke_admin: true,
+ });
+ }
+
+ return resp;
+ }
+ );
+ }
+
+ revokeModeration() {
+ return ajax(`/admin/users/${this.id}/revoke_moderation`, {
+ type: "PUT",
+ })
+ .then((resp: AdminUserWireFields) => {
+ this.setProperties({
+ moderator: false,
+ can_grant_moderation: true,
+ can_revoke_moderation: false,
+ can_be_merged: resp.can_be_merged,
+ can_be_anonymized: resp.can_be_anonymized,
+ });
+ })
+ .catch(popupAjaxError);
+ }
+
+ grantModeration() {
+ return ajax(`/admin/users/${this.id}/grant_moderation`, {
+ type: "PUT",
+ })
+ .then((resp: AdminUserWireFields) => {
+ this.setProperties({
+ moderator: true,
+ can_grant_moderation: false,
+ can_revoke_moderation: true,
+ can_be_merged: resp.can_be_merged,
+ can_be_anonymized: resp.can_be_anonymized,
+ });
+ })
+ .catch(popupAjaxError);
+ }
+
+ disableSecondFactor() {
+ return ajax(`/admin/users/${this.id}/disable_second_factor`, {
+ type: "PUT",
+ })
+ .then(() => {
+ this.set("second_factor_enabled", false);
+ })
+ .catch(popupAjaxError);
+ }
+
+ approve(approvedBy: BasicAdminUser) {
+ return ajax(`/admin/users/${this.id}/approve`, {
+ type: "PUT",
+ }).then(() => {
+ this.setProperties({
+ can_approve: false,
+ approved: true,
+ approved_by: approvedBy,
+ });
+ });
+ }
+
+ setOriginalTrustLevel() {
+ this.set("originalTrustLevel", this.trust_level);
+ }
+
+ saveTrustLevel(): Promise<{ admin_user: AdminUserWireFields }> {
+ return ajax(`/admin/users/${this.id}/trust_level`, {
+ type: "PUT",
+ data: { level: this.trust_level },
+ });
+ }
+
+ restoreTrustLevel() {
+ this.set("trust_level", this.originalTrustLevel);
+ }
+
+ lockTrustLevel(locked: boolean): Promise<unknown> {
+ return ajax(`/admin/users/${this.id}/trust_level_lock`, {
+ type: "PUT",
+ data: { locked: !!locked },
+ });
+ }
+
+ suspend(data: AdminUserPenaltyParams & { suspend_until: string }) {
+ return ajax(`/admin/users/${this.id}/suspend`, {
+ type: "PUT",
+ data,
+ }).then((result: { suspension: Suspension }) =>
+ this.setProperties(result.suspension)
+ );
+ }
+
+ unsuspend() {
+ return applyBehaviorTransformer(
+ "admin-user-unsuspend",
+ () =>
+ ajax(`/admin/users/${this.id}/unsuspend`, {
+ type: "PUT",
+ }).then((result: { suspension: Suspension }) =>
+ this.setProperties(result.suspension)
+ ),
+ { user: this }
+ );
+ }
+
+ logOut(): Promise<SuccessResponse> {
+ return ajax("/admin/users/" + this.id + "/log_out", {
+ type: "POST",
+ data: { username_or_email: this.username },
+ });
+ }
+
+ impersonate(): Promise<unknown> {
+ return ajax("/admin/impersonate", {
+ type: "POST",
+ data: { username_or_email: this.username },
+ });
+ }
+
+ activate(): Promise<SuccessResponse> {
+ return ajax(`/admin/users/${this.id}/activate`, {
+ type: "PUT",
+ });
+ }
+
+ deactivate(): Promise<SuccessResponse> {
+ return ajax(`/admin/users/${this.id}/deactivate`, {
+ type: "PUT",
+ data: { context: document.location.pathname },
+ });
+ }
+
+ unsilence() {
+ return applyBehaviorTransformer(
+ "admin-user-unsilence",
+ () => {
+ this.set("silencingUser", true);
+
+ return ajax(`/admin/users/${this.id}/unsilence`, {
+ type: "PUT",
+ })
+ .then(
+ (result: {
+ unsilence: Silencing & {
+ silence_at?: undefined;
+ silence_till?: undefined;
+ };
+ }) => {
+ this.setProperties({
+ silence_reason: result.unsilence.silence_reason,
+ full_silence_reason: result.unsilence.full_silence_reason,
+ silenced_at: result.unsilence.silence_at,
+ silenced_till: result.unsilence.silence_till,
+ });
+ }
+ )
+ .finally(() => this.set("silencingUser", false));
+ },
+ { user: this }
+ );
+ }
+
+ silence(data: AdminUserPenaltyParams & { silenced_till: string }) {
+ this.set("silencingUser", true);
+
+ return ajax(`/admin/users/${this.id}/silence`, {
+ type: "PUT",
+ data,
+ })
+ .then((result: { silence: Silencing }) => {
+ this.setProperties({
+ silence_reason: result.silence.silence_reason,
+ full_silence_reason: result.silence.full_silence_reason,
+ silenced_at: result.silence.silenced_at,
+ silenced_by: result.silence.silenced_by,
+ silenced_till: result.silence.silenced_till,
+ });
+ })
+ .finally(() => this.set("silencingUser", false));
+ }
+
+ sendActivationEmail(): Promise<unknown> {
+ return ajax(userPath("action/send_activation_email"), {
+ type: "POST",
+ data: { username: this.username },
+ });
+ }
+
+ anonymize(): Promise<
+ | (SuccessResponse & { username: string })
+ | { failed: string; user: AdminUserWireFields | null }
+ > {
+ return ajax(`/admin/users/${this.id}/anonymize.json`, {
+ type: "PUT",
+ });
+ }
+
+ deleteAssociatedAccounts() {
+ return ajax(`/admin/users/${this.id}/delete_associated_accounts`, {
+ type: "PUT",
+ data: {
+ context: window.location.pathname,
+ },
+ }).then(() => {
+ this.set("associated_accounts", []);
+ });
+ }
+
+ /** The unreachable overload preserves the inherited framework destruction contract. */
+ destroy(this: never): never;
+ destroy(
+ formData: Record<string, unknown>
+ ): Promise<AdminUserDestroyResult | void>;
+
+ destroy(
+ formData?: Record<string, unknown>
+ ): Promise<AdminUserDestroyResult | void> {
+ return ajax(`/admin/users/${this.id}.json`, {
+ type: "DELETE",
+ data: formData,
+ })
+ .then((data: AdminUserDestroyResult) => {
+ if (!data.deleted && data.user) {
+ // TODO(typescript-pending): Ember's setProperties cannot infer subclass keys here; remove when it accepts partial base fields.
+ this.setProperties(data.user as Partial<this>);
+ }
+
+ return data;
+ })
+ .catch(() => {
+ // Instances have no `find`, so this rejects at runtime. TODO(typescript-pending): remove this cast with that runtime fix.
+ (this as unknown as { find: typeof AdminUser.find })
+ .find(this.id)
+ .then((u) => this.setProperties(u as Partial<this>));
+ });
+ }
+
+ merge(formData: {
+ target_username: string;
+ [key: string]: unknown;
+ }): Promise<SuccessResponse> {
+ return ajax(`/admin/users/${this.id}/merge.json`, {
+ type: "POST",
+ data: formData,
+ });
+ }
+
+ async loadDetails(): Promise<AdminUser> {
+ if (this.loadedDetails) {
+ return this;
+ }
+
+ // Raw data preserves tracked values that are not enumerable on an AdminUser instance.
+ const userProperties = await AdminUser.find(this.id, { raw: true });
+ // TODO(typescript-pending): Ember's setProperties cannot infer subclass keys here; remove when it accepts partial base fields.
+ this.setProperties(userProperties as Partial<this>);
+
+ return this;
+ }
+
+ deleteSSORecord() {
+ return ajax(`/admin/users/${this.id}/sso_record.json`, {
+ type: "DELETE",
+ })
+ .then(() => {
+ this.set("single_sign_on_record", null);
+ })
+ .catch(popupAjaxError);
+ }
+}
+
+/** Legacy application global; declaring it preserves the module evaluation order. */
+declare const moment: typeof import("moment");
diff --git a/frontend/discourse/admin/models/api-key.js b/frontend/discourse/admin/models/api-key.js
deleted file mode 100644
index c5b02c0ab30..00000000000
--- a/frontend/discourse/admin/models/api-key.js
+++ /dev/null
@@ -1,73 +0,0 @@
-import { computed } from "@ember/object";
-import AdminUser from "discourse/admin/models/admin-user";
-import { ajax } from "discourse/lib/ajax";
-import RestModel from "discourse/models/rest";
-
-export default class ApiKey extends RestModel {
- @computed("_user")
- get user() {
- return this._user;
- }
-
- set user(value) {
- if (value && !(value instanceof AdminUser)) {
- this.set("_user", AdminUser.create(value));
- } else {
- this.set("_user", value);
- }
- }
-
- @computed("truncated_key")
- get truncatedKey() {
- return `${this.truncated_key} ...`;
- }
-
- @computed("_created_by")
- get createdBy() {
- return this._created_by;
- }
-
- @computed("description")
- get shortDescription() {
- if (!this.description || this.description.length < 40) {
- return this.description;
- }
- return `${this.description.substring(0, 40)}...`;
- }
-
- @computed()
- get basePath() {
- return this.store
- .adapterFor("api-key")
- .pathFor(this.store, "api-key", this.id);
- }
-
- set created_by(value) {
- if (value && !(value instanceof AdminUser)) {
- this.set("_created_by", AdminUser.create(value));
- } else {
- this.set("_created_by", value);
- }
- }
-
- revoke() {
- return ajax(`${this.basePath}/revoke`, {
- type: "POST",
- }).then((result) => this.setProperties(result.api_key));
- }
-
- undoRevoke() {
- return ajax(`${this.basePath}/undo-revoke`, {
- type: "POST",
- }).then((result) => this.setProperties(result.api_key));
- }
-
- createProperties() {
- return this.getProperties(
- "description",
- "username",
- "scopes",
- "scope_mode"
- );
- }
-}
diff --git a/frontend/discourse/admin/models/api-key.ts b/frontend/discourse/admin/models/api-key.ts
new file mode 100644
index 00000000000..c4813c64cec
--- /dev/null
+++ b/frontend/discourse/admin/models/api-key.ts
@@ -0,0 +1,157 @@
+import { computed } from "@ember/object";
+import type RestAdapter from "discourse/adapters/rest";
+import AdminUser, {
+ type BasicAdminUser,
+} from "discourse/admin/models/admin-user";
+import { ajax } from "discourse/lib/ajax";
+import RestModel, {
+ type RestModelClass,
+ type RestModelStoreAttrs,
+ type RestPayload,
+} from "discourse/models/rest";
+
+/** Scopes serialized on detail/create/update responses, absent from index rows. */
+export interface ApiKeyScope {
+ resource: string;
+ action: string;
+ parameters: string[];
+ urls: string[];
+ allowed_parameters: Record<string, string[]> | null;
+ key: string;
+}
+
+/** Scope catalogue selections are request data, separate from serialized key scopes. */
+export type ApiKeyScopeSelection = {
+ scope_id: string;
+ key: string;
+ name: string;
+ params: string[] | null;
+ urls?: string[];
+} & Record<string, string | string[] | boolean | null | undefined>;
+
+/** Index fields plus conditional detail fields and mutable creation inputs. */
+export interface ApiKeyFields {
+ id: number;
+ truncated_key: string;
+ description: string | null;
+ scope_mode: "global" | "read_only" | "granular" | null;
+ last_used_at: string | null;
+ revoked_at: string | null;
+ created_at?: string;
+ updated_at?: string;
+ key?: string;
+ api_key_scopes?: ApiKeyScope[];
+ username?: string | null;
+ scopes?: (ApiKeyScopeSelection | undefined)[] | null;
+ _user?: AdminUser | null;
+ _created_by?: AdminUser | null;
+}
+
+/** Setters accept basic wire users, while getters expose wrapped instances. */
+export type ApiKeyCreateAttrs<M = ApiKey> = Partial<
+ Omit<M, "user" | "created_by">
+> &
+ RestModelStoreAttrs &
+ RestPayload & {
+ user?: BasicAdminUser | AdminUser | null;
+ created_by?: BasicAdminUser | AdminUser | null;
+ };
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface ApiKey extends ApiKeyFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class ApiKey extends RestModel {
+ declare static create: <C extends RestModelClass>(
+ this: C,
+ attrs?: ApiKeyCreateAttrs<InstanceType<C>>
+ ) => InstanceType<C>;
+
+ @computed("_user")
+ get user(): AdminUser | null | undefined {
+ return this._user;
+ }
+
+ set user(value: BasicAdminUser | AdminUser | null | undefined) {
+ if (value && !(value instanceof AdminUser)) {
+ this.set("_user", AdminUser.create(value));
+ } else {
+ this.set("_user", value);
+ }
+ }
+
+ @computed("truncated_key")
+ get truncatedKey() {
+ return `${this.truncated_key} ...`;
+ }
+
+ @computed("_created_by")
+ get createdBy(): AdminUser | null | undefined {
+ return this._created_by;
+ }
+
+ @computed("description")
+ get shortDescription(): string | null {
+ if (!this.description || this.description.length < 40) {
+ return this.description;
+ }
+ return `${this.description.substring(0, 40)}...`;
+ }
+
+ @computed()
+ get basePath(): string {
+ // TODO(typescript-pending): StoreAdapter omits pathFor; remove when its REST adapter surface is typed.
+ return (
+ this.store.adapterFor("api-key") as ReturnType<
+ typeof this.store.adapterFor
+ > &
+ Pick<RestAdapter, "pathFor">
+ ).pathFor(this.store, "api-key", this.id);
+ }
+
+ /** Write-only raw input; read the wrapped user through createdBy. */
+ set created_by(value: BasicAdminUser | AdminUser | null | undefined) {
+ if (value && !(value instanceof AdminUser)) {
+ this.set("_created_by", AdminUser.create(value));
+ } else {
+ this.set("_created_by", value);
+ }
+ }
+
+ revoke() {
+ return ajax(`${this.basePath}/revoke`, {
+ type: "POST",
+ }).then((result: { api_key: ApiKeyCreateAttrs }) =>
+ this.setProperties(result.api_key)
+ );
+ }
+
+ undoRevoke() {
+ return ajax(`${this.basePath}/undo-revoke`, {
+ type: "POST",
+ }).then((result: { api_key: ApiKeyCreateAttrs }) =>
+ this.setProperties(result.api_key)
+ );
+ }
+
+ createProperties(): Pick<
+ ApiKey,
+ "description" | "username" | "scopes" | "scope_mode"
+ > {
+ return this.getProperties(
+ "description",
+ "username",
+ "scopes",
+ "scope_mode"
+ );
+ }
+}
+
+declare module "discourse/services/store" {
+ interface ModelRegistry {
+ "api-key": ApiKey;
+ }
+ interface ModelCreateAttrsRegistry {
+ "api-key": ApiKeyCreateAttrs;
+ }
+}
diff --git a/frontend/discourse/admin/models/email-log.js b/frontend/discourse/admin/models/email-log.js
deleted file mode 100644
index 39ee34090f8..00000000000
--- a/frontend/discourse/admin/models/email-log.js
+++ /dev/null
@@ -1,32 +0,0 @@
-import EmberObject from "@ember/object";
-import AdminUser from "discourse/admin/models/admin-user";
-import { ajax } from "discourse/lib/ajax";
-import getURL from "discourse/lib/get-url";
-
-export default class EmailLog extends EmberObject {
- static create(attrs) {
- attrs = attrs || {};
-
- if (attrs.user) {
- attrs.user = AdminUser.create(attrs.user);
- }
-
- if (attrs.post_url) {
- attrs.post_url = getURL(attrs.post_url);
- }
-
- return super.create(attrs);
- }
-
- static findAll(filter, offset) {
- filter = filter || {};
- offset = offset || 0;
-
- const status = filter.status || "sent";
- delete filter.status;
-
- return ajax(`/admin/email-logs/${status}.json?offset=${offset}`, {
- data: filter,
- }).then((logs) => logs.map((log) => EmailLog.create(log)));
- }
-}
diff --git a/frontend/discourse/admin/models/email-log.ts b/frontend/discourse/admin/models/email-log.ts
new file mode 100644
index 00000000000..4c64159c0d9
--- /dev/null
+++ b/frontend/discourse/admin/models/email-log.ts
@@ -0,0 +1,92 @@
+import EmberObject from "@ember/object";
+import AdminUser, {
+ type BasicAdminUser,
+} from "discourse/admin/models/admin-user";
+import { ajax } from "discourse/lib/ajax";
+import getURL from "discourse/lib/get-url";
+
+/** Common, sent/bounced and skipped serializer fields; variant fields are optional. */
+export interface EmailLogFields {
+ id?: number;
+ created_at?: string;
+ user: AdminUser | null;
+ post_url?: string;
+ to_address?: string;
+ email_type?: string;
+ user_id: number | null;
+ post_description?: string;
+ cc_addresses?: string[] | null;
+ post_id?: number | null;
+ reply_key?: string;
+ bounced?: boolean;
+ has_bounce_key?: boolean;
+ smtp_transaction_response?: string | null;
+ skipped_reason?: string;
+}
+
+/** The factory mutates raw users into AdminUser instances. */
+export type EmailLogCreateAttrs<M = EmailLog> = Partial<Omit<M, "user">> & {
+ user?: BasicAdminUser | AdminUser | null;
+};
+
+/** findAll consumes status by deleting it from this object. */
+export interface EmailLogFilter {
+ status?: string;
+ address?: string;
+ user?: string;
+ type?: string;
+ [key: string]: string | number | boolean | null | undefined;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface EmailLog extends EmailLogFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class EmailLog extends EmberObject {
+ static create<C extends abstract new (...args: never[]) => EmberObject>(
+ this: C,
+ attrs?: EmailLogCreateAttrs<InstanceType<C>> | null
+ ): InstanceType<C>;
+
+ /** Keeps the inherited variadic factory assignable without advertising extra runtime arguments. */
+ static create(this: never, ...args: unknown[]): never;
+ static create(attrs?: EmailLogCreateAttrs | null) {
+ attrs = attrs || {};
+
+ if (attrs.user) {
+ attrs.user = AdminUser.create(attrs.user);
+ }
+
+ if (attrs.post_url) {
+ attrs.post_url = getURL(attrs.post_url);
+ }
+
+ return super.create(attrs);
+ }
+
+ static findAll(
+ filter?: EmailLogFilter | null,
+ offset?: number | null
+ ): Promise<EmailLog[]> {
+ filter = filter || {};
+ offset = offset || 0;
+
+ const status = filter.status || "sent";
+ delete filter.status;
+
+ return ajax(`/admin/email-logs/${status}.json?offset=${offset}`, {
+ data: filter,
+ }).then((logs: EmailLogCreateAttrs[]) =>
+ logs.map((log) => EmailLog.create(log))
+ );
+ }
+}
+
+declare module "discourse/services/store" {
+ interface ModelRegistry {
+ "email-log": EmailLog;
+ }
+ interface ModelCreateAttrsRegistry {
+ "email-log": EmailLogCreateAttrs;
+ }
+}
diff --git a/frontend/discourse/admin/models/incoming-email.js b/frontend/discourse/admin/models/incoming-email.js
deleted file mode 100644
index 99d4b5835d2..00000000000
--- a/frontend/discourse/admin/models/incoming-email.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import EmberObject from "@ember/object";
-import AdminUser from "discourse/admin/models/admin-user";
-import { ajax } from "discourse/lib/ajax";
-
-export default class IncomingEmail extends EmberObject {
- static create(attrs) {
- attrs = attrs || {};
-
- if (attrs.user) {
- attrs.user = AdminUser.create(attrs.user);
- }
-
- return super.create(attrs);
- }
-
- static find(id) {
- return ajax(`/admin/email-logs/incoming/${id}.json`);
- }
-
- static findByBounced(id) {
- return ajax(`/admin/email-logs/incoming_from_bounced/${id}.json`);
- }
-
- static findAll(filter, offset) {
- filter = filter || {};
- offset = offset || 0;
-
- const status = filter.status || "received";
- delete filter.status;
-
- return ajax(`/admin/email-logs/${status}.json?offset=${offset}`, {
- data: filter,
- }).then((incomings) =>
- incomings.map((incoming) => IncomingEmail.create(incoming))
- );
- }
-}
diff --git a/frontend/discourse/admin/models/incoming-email.ts b/frontend/discourse/admin/models/incoming-email.ts
new file mode 100644
index 00000000000..557dd793ee3
--- /dev/null
+++ b/frontend/discourse/admin/models/incoming-email.ts
@@ -0,0 +1,84 @@
+import EmberObject from "@ember/object";
+import AdminUser, {
+ type BasicAdminUser,
+} from "discourse/admin/models/admin-user";
+import type { EmailLogFilter } from "discourse/admin/models/email-log";
+import { ajax } from "discourse/lib/ajax";
+
+/** List rows only; detail lookups return IncomingEmailDetails. */
+export interface IncomingEmailFields {
+ id?: number;
+ created_at?: string;
+ user: AdminUser | null;
+ post_url?: string;
+ from_address?: string | null;
+ to_addresses: string[] | null;
+ cc_addresses?: string[] | null;
+ subject?: string | null;
+ error?: string;
+}
+
+/** The factory mutates raw users into AdminUser instances. */
+export type IncomingEmailCreateAttrs<M = IncomingEmail> = Partial<
+ Omit<M, "user">
+> & {
+ user?: BasicAdminUser | AdminUser | null;
+};
+
+/** Rootless detail response, with no list identity or addresses. */
+export interface IncomingEmailDetails {
+ error?: string;
+ error_description?: string;
+ rejection_message: string | null;
+ headers: string;
+ subject: string;
+ body: string;
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface IncomingEmail extends IncomingEmailFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class IncomingEmail extends EmberObject {
+ static create<C extends abstract new (...args: never[]) => EmberObject>(
+ this: C,
+ attrs?: IncomingEmailCreateAttrs<InstanceType<C>> | null
+ ): InstanceType<C>;
+
+ /** Keeps the inherited variadic factory assignable without advertising extra runtime arguments. */
+ static create(this: never, ...args: unknown[]): never;
+ static create(attrs?: IncomingEmailCreateAttrs | null) {
+ attrs = attrs || {};
+
+ if (attrs.user) {
+ attrs.user = AdminUser.create(attrs.user);
+ }
+
+ return super.create(attrs);
+ }
+
+ static find(id: string | number): Promise<IncomingEmailDetails> {
+ return ajax(`/admin/email-logs/incoming/${id}.json`);
+ }
+
+ static findByBounced(id: string | number): Promise<IncomingEmailDetails> {
+ return ajax(`/admin/email-logs/incoming_from_bounced/${id}.json`);
+ }
+
+ static findAll(
+ filter?: EmailLogFilter | null,
+ offset?: number | null
+ ): Promise<IncomingEmail[]> {
+ filter = filter || {};
+ offset = offset || 0;
+
+ const status = filter.status || "received";
+ delete filter.status;
+
+ return ajax(`/admin/email-logs/${status}.json?offset=${offset}`, {
+ data: filter,
+ }).then((incomings: IncomingEmailCreateAttrs[]) =>
+ incomings.map((incoming) => IncomingEmail.create(incoming))
+ );
+ }
+}
diff --git a/frontend/discourse/admin/models/staff-action-log.js b/frontend/discourse/admin/models/staff-action-log.ts
similarity index 57%
rename from frontend/discourse/admin/models/staff-action-log.js
rename to frontend/discourse/admin/models/staff-action-log.ts
index 748884f63e1..c541a1878f4 100644
--- a/frontend/discourse/admin/models/staff-action-log.js
+++ b/frontend/discourse/admin/models/staff-action-log.ts
@@ -1,13 +1,71 @@
import { computed } from "@ember/object";
-import AdminUser from "discourse/admin/models/admin-user";
+import AdminUser, {
+ type BasicAdminUser,
+} from "discourse/admin/models/admin-user";
import { ajax } from "discourse/lib/ajax";
import { duration, longDate } from "discourse/lib/formatter";
import getURL from "discourse/lib/get-url";
import { escapeExpression } from "discourse/lib/utilities";
-import RestModel from "discourse/models/rest";
+import RestModel, {
+ type RestModelClass,
+ type RestModelStoreAttrs,
+ type RestPayload,
+} from "discourse/models/rest";
import { i18n } from "discourse-i18n";
-function format(label, value, escape = true) {
+/** Parsed theme/tag-group JSON or the text used by other history actions. */
+export type StaffActionValue =
+ | string
+ | number
+ | boolean
+ | null
+ | StaffActionValue[]
+ | { [key: string]: StaffActionValue };
+
+/** Viewer-redacted history rows; reviewable_id is conditionally serialized. */
+export interface StaffActionLogFields {
+ id?: number;
+ action_name: string;
+ action: number;
+ details: string | null;
+ context?: string | null;
+ ip_address?: string | null;
+ email?: string | null;
+ created_at?: string;
+ expires_at: string | null;
+ subject?: string | null;
+ previous_value?: StaffActionValue;
+ new_value?: StaffActionValue;
+ topic_id?: number | null;
+ post_id?: number | null;
+ category_id?: number | null;
+ reviewable_id?: number;
+ custom_type: string | null;
+ acting_user: AdminUser | null;
+ target_user: AdminUser | null;
+}
+
+/** munge hydrates actors on the store and inherited create paths. */
+export type StaffActionLogCreateAttrs<M = StaffActionLog> = Partial<
+ Omit<M, "acting_user" | "target_user">
+> &
+ RestModelStoreAttrs &
+ RestPayload & {
+ acting_user?: BasicAdminUser | AdminUser | null;
+ target_user?: BasicAdminUser | AdminUser | null;
+ };
+
+/** The unused findAll reads this at the top level, although the controller sends it under extras. */
+export interface StaffActionLogListResponse {
+ staff_action_logs: StaffActionLog[];
+ user_history_actions: { id: string; action_id: number }[] | undefined;
+}
+
+function format(
+ label: string,
+ value: StaffActionValue | undefined,
+ escape = true
+) {
const labelBr = value && value.toString().includes("\n") ? "<br/>" : " ";
value = value ? value.toString() : "";
return value
@@ -15,8 +73,19 @@ function format(label, value, escape = true) {
: "";
}
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface StaffActionLog extends StaffActionLogFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export default class StaffActionLog extends RestModel {
- static munge(json) {
+ declare static create: <C extends RestModelClass>(
+ this: C,
+ attrs?: StaffActionLogCreateAttrs<InstanceType<C>>
+ ) => InstanceType<C>;
+
+ static munge(json: StaffActionLogCreateAttrs): RestPayload;
+ static munge(json: RestPayload): RestPayload;
+ static munge(json: StaffActionLogCreateAttrs) {
if (json.acting_user) {
json.acting_user = AdminUser.create(json.acting_user);
}
@@ -26,9 +95,14 @@ export default class StaffActionLog extends RestModel {
return json;
}
- static findAll(data) {
+ static findAll(
+ data?: Record<string, string | number | boolean>
+ ): Promise<StaffActionLogListResponse> {
return ajax("/admin/logs/staff_action_logs.json", { data }).then(
- (result) => {
+ (result: {
+ staff_action_logs: StaffActionLogCreateAttrs[];
+ user_history_actions?: StaffActionLogListResponse["user_history_actions"];
+ }) => {
return {
staff_action_logs: result.staff_action_logs.map((s) =>
StaffActionLog.create(s)
@@ -42,7 +116,7 @@ export default class StaffActionLog extends RestModel {
showFullDetails = false;
@computed("action_name")
- get actionName() {
+ get actionName(): string {
return i18n(`admin.logs.staff_actions.actions.${this.action_name}`);
}
@@ -144,3 +218,15 @@ export default class StaffActionLog extends RestModel {
].includes(this.action_name);
}
}
+
+declare module "discourse/services/store" {
+ interface ModelRegistry {
+ "staff-action-log": StaffActionLog;
+ }
+ interface ModelCreateAttrsRegistry {
+ "staff-action-log": StaffActionLogCreateAttrs;
+ }
+}
+
+/** Legacy application global; declaring it preserves the module evaluation order. */
+declare const moment: typeof import("moment");
diff --git a/frontend/discourse/admin/models/tl3-requirements.js b/frontend/discourse/admin/models/tl3-requirements.ts
similarity index 61%
rename from frontend/discourse/admin/models/tl3-requirements.js
rename to frontend/discourse/admin/models/tl3-requirements.ts
index bbf13f48d6a..002e7b6ed21 100644
--- a/frontend/discourse/admin/models/tl3-requirements.js
+++ b/frontend/discourse/admin/models/tl3-requirements.ts
@@ -1,5 +1,43 @@
import EmberObject, { computed } from "@ember/object";
+/** Embedded TL3 serializer data; unlike the top-level user counts, these include total. */
+export interface Tl3RequirementsFields {
+ time_period: number;
+ requirements_met: boolean;
+ requirements_lost: boolean;
+ trust_level_locked: boolean;
+ on_grace_period: boolean;
+ days_visited: number;
+ min_days_visited: number;
+ num_topics_replied_to: number;
+ min_topics_replied_to: number;
+ topics_viewed: number;
+ min_topics_viewed: number;
+ posts_read: number;
+ min_posts_read: number;
+ topics_viewed_all_time: number;
+ min_topics_viewed_all_time: number;
+ posts_read_all_time: number;
+ min_posts_read_all_time: number;
+ num_flagged_posts: number;
+ max_flagged_posts: number;
+ num_flagged_by_users: number;
+ max_flagged_by_users: number;
+ num_likes_given: number;
+ min_likes_given: number;
+ num_likes_received: number;
+ min_likes_received: number;
+ num_likes_received_days: number;
+ min_likes_received_days: number;
+ num_likes_received_users: number;
+ min_likes_received_users: number;
+ penalty_counts: { silenced: number; suspended: number; total: number };
+}
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface Tl3Requirements extends Tl3RequirementsFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export default class Tl3Requirements extends EmberObject {
@computed("days_visited", "time_period")
get days_visited_percent() {
@@ -71,3 +109,13 @@ export default class Tl3Requirements extends EmberObject {
};
}
}
+
+declare module "discourse/services/store" {
+ interface ModelRegistry {
+ "tl3-requirements": Tl3Requirements;
+ }
+
+ interface ModelCreateAttrsRegistry {
+ "tl3-requirements": Partial<Tl3RequirementsFields>;
+ }
+}
diff --git a/frontend/discourse/admin/models/web-hook.js b/frontend/discourse/admin/models/web-hook.js
deleted file mode 100644
index 8cb157df734..00000000000
--- a/frontend/discourse/admin/models/web-hook.js
+++ /dev/null
@@ -1,154 +0,0 @@
-/* eslint-disable ember/no-observers */
-import { tracked } from "@glimmer/tracking";
-import { computed } from "@ember/object";
-import { isEmpty } from "@ember/utils";
-import { observes } from "@ember-decorators/object";
-import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import Group from "discourse/models/group";
-import RestModel from "discourse/models/rest";
-import Site from "discourse/models/site";
-
-class WebHookExtras {
- @tracked categories;
-
- constructor(args) {
- this.categories = args.categories || [];
- this.content_types = args.content_types || [];
- this.default_event_types = args.default_event_types || [];
- this.delivery_statuses = args.delivery_statuses || [];
- this.grouped_event_types = args.grouped_event_types || [];
- }
-
- get categoriesById() {
- if (this.categories) {
- return new Map(this.categories.map((c) => [c.id, c]));
- }
- }
-
- addCategories(categories) {
- this.categories = uniqueItemsFromArray(
- this.categories.concat(categories),
- "id"
- );
- }
-
- findCategoryById(id) {
- return this.categoriesById?.get(id);
- }
-}
-
-export default class WebHook extends RestModel {
- static ExtrasClass = WebHookExtras;
- content_type = 1; // json
- last_delivery_status = 1; // inactive
- wildcard_web_hook = false;
- verify_certificate = true;
- active = false;
-
- /** @type {Array<{ id: number, name: string }> | null} */
- web_hook_event_types = null;
-
- /**
- * Group names, or a comma-separated string of them when set by a group selector.
- *
- * @type {string[] | string | null}
- */
- group_names = null;
-
- @computed("wildcard_web_hook")
- get wildcard() {
- return this.wildcard_web_hook ? "wildcard" : "individual";
- }
-
- set wildcard(value) {
- this.set("wildcard_web_hook", value === "wildcard");
- }
-
- @computed("category_ids")
- get categories() {
- return (this.category_ids || []).map((id) =>
- this.extras.findCategoryById(id)
- );
- }
-
- set categories(value) {
- this.extras ||= new WebHookExtras({});
- this.extras.addCategories(value);
-
- this.set(
- "category_ids",
- value.map((c) => c.id)
- );
- }
-
- @computed("wildcard_web_hook", "web_hook_event_types.[]")
- get description() {
- let desc = "";
-
- this.web_hook_event_types?.forEach((type) => {
- const name = `${type.name.toLowerCase()}_event`;
- desc += desc !== "" ? `, ${name}` : name;
- });
-
- return this.wildcard_web_hook ? "*" : desc;
- }
-
- @observes("group_ids")
- updateGroupsFilter() {
- const groupIds = this.group_ids;
- this.set(
- "group_names",
- Site.currentProp("groups").reduce((groupNames, g) => {
- if (groupIds.includes(g.id)) {
- groupNames.push(g.name);
- }
- return groupNames;
- }, [])
- );
- }
-
- groupFinder(term) {
- return Group.findAll({ term, ignore_automatic: false });
- }
-
- createProperties() {
- const types = this.web_hook_event_types;
- const categoryIds = this.categories.map((c) => c.id);
- const tags = this.tags;
-
- // Hack as {{group-selector}} accepts a comma-separated string as data source, but
- // we use an array to populate the datasource above.
- const groupsFilter = this.group_names;
- const groupNames =
- typeof groupsFilter === "string" ? groupsFilter.split(",") : groupsFilter;
-
- return {
- payload_url: this.payload_url,
- content_type: this.content_type,
- secret: this.secret ?? "",
- wildcard_web_hook: this.wildcard_web_hook,
- verify_certificate: this.verify_certificate,
- active: this.active,
- web_hook_event_type_ids: isEmpty(types)
- ? [null]
- : types.map((type) => type.id),
- category_ids: isEmpty(categoryIds) ? [null] : categoryIds,
- tag_ids: isEmpty(tags)
- ? [null]
- : tags.map((t) => (typeof t === "object" ? t.id : t)),
- group_ids:
- isEmpty(groupNames) || isEmpty(groupNames[0])
- ? [null]
- : Site.currentProp("groups").reduce((groupIds, g) => {
- if (groupNames.includes(g.name)) {
- groupIds.push(g.id);
- }
- return groupIds;
- }, []),
- };
- }
-
- updateProperties() {
- return this.createProperties();
- }
-}
diff --git a/frontend/discourse/admin/models/web-hook.ts b/frontend/discourse/admin/models/web-hook.ts
new file mode 100644
index 00000000000..f84035bb0c1
--- /dev/null
+++ b/frontend/discourse/admin/models/web-hook.ts
@@ -0,0 +1,244 @@
+/* eslint-disable ember/no-observers */
+import { tracked } from "@glimmer/tracking";
+import { computed } from "@ember/object";
+import { isEmpty } from "@ember/utils";
+import { observes } from "@ember-decorators/object";
+import { uniqueItemsFromArray } from "discourse/lib/array-tools";
+import type { CategoryFields } from "discourse/models/category";
+import Group from "discourse/models/group";
+import RestModel, {
+ type RestModelClass,
+ type RestModelStoreAttrs,
+ type RestPayload,
+} from "discourse/models/rest";
+import Site, { type SiteTopTag } from "discourse/models/site";
+
+/** Raw sideloaded categories retain their required identity without becoming Category instances. */
+export type WebHookCategory = CategoryFields & { id: number; name: string };
+
+export interface WebHookEventType {
+ id: number;
+ name: string;
+ group?: string | null;
+}
+
+/** Index extras carry catalogues; show extras may contain only categories. */
+export interface WebHookExtrasAttrs {
+ categories?: WebHookCategory[] | null;
+ content_types?: { id: number; name: string }[];
+ default_event_types?: WebHookEventType[];
+ delivery_statuses?: { id: number; name: string }[];
+ grouped_event_types?: Record<string, WebHookEventType[]> | [];
+}
+
+class WebHookExtras {
+ @tracked categories: WebHookCategory[];
+ declare content_types: { id: number; name: string }[];
+ declare default_event_types: WebHookEventType[];
+ declare delivery_statuses: { id: number; name: string }[];
+ declare grouped_event_types: Record<string, WebHookEventType[]> | [];
+
+ constructor(args: WebHookExtrasAttrs) {
+ this.categories = args.categories || [];
+ this.content_types = args.content_types || [];
+ this.default_event_types = args.default_event_types || [];
+ this.delivery_statuses = args.delivery_statuses || [];
+ this.grouped_event_types = args.grouped_event_types || [];
+ }
+
+ get categoriesById() {
+ if (this.categories) {
+ return new Map(this.categories.map((c) => [c.id, c]));
+ }
+ }
+
+ addCategories(categories: WebHookCategory[]) {
+ this.categories = uniqueItemsFromArray(
+ this.categories.concat(categories),
+ "id"
+ );
+ }
+
+ findCategoryById(id: number) {
+ return this.categoriesById?.get(id);
+ }
+}
+
+/** Serialized tags and names/IDs written by the tag selector. */
+export type WebHookTag =
+ | (SiteTopTag & {
+ topic_count?: number;
+ staff?: boolean;
+ description?: string | null;
+ description_cooked?: string | null;
+ localizations?: {
+ id: number;
+ tag_id: number;
+ locale: string;
+ name: string;
+ description: string | null;
+ description_cooked: string | null;
+ }[];
+ })
+ | string
+ | number;
+
+export interface WebHookFields {
+ id?: number;
+ payload_url: string;
+ secret: string | null;
+ category_ids: number[];
+ group_ids: number[];
+ tags?: WebHookTag[] | null;
+ extras?: WebHookExtras;
+}
+
+/** Category writes require resolved selections even though reads can contain missing IDs. */
+export type WebHookCreateAttrs<M = WebHook> = Partial<Omit<M, "categories">> &
+ RestModelStoreAttrs &
+ RestPayload & { categories?: WebHookCategory[] };
+
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging
+export default interface WebHook extends WebHookFields {}
+
+// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
+export default class WebHook extends RestModel {
+ declare static create: <C extends RestModelClass>(
+ this: C,
+ attrs?: WebHookCreateAttrs<InstanceType<C>>
+ ) => InstanceType<C>;
+
+ static ExtrasClass = WebHookExtras;
+ content_type = 1; // json
+ last_delivery_status = 1; // inactive
+ wildcard_web_hook = false;
+ verify_certificate = true;
+ active = false;
+
+ web_hook_event_types: WebHookEventType[] | null = null;
+
+ /**
+ * Group names, or a comma-separated string of them when set by a group selector.
+ */
+ group_names: string[] | string | null = null;
+
+ @computed("wildcard_web_hook")
+ get wildcard() {
+ return this.wildcard_web_hook ? "wildcard" : "individual";
+ }
+
+ set wildcard(value: "wildcard" | "individual") {
+ this.set("wildcard_web_hook", value === "wildcard");
+ }
+
+ @computed("category_ids")
+ get categories(): (WebHookCategory | undefined)[] {
+ return (this.category_ids || []).map((id) =>
+ this.extras!.findCategoryById(id)
+ );
+ }
+
+ set categories(value: WebHookCategory[]) {
+ this.extras ||= new WebHookExtras({});
+ this.extras.addCategories(value);
+
+ this.set(
+ "category_ids",
+ value.map((c) => c.id)
+ );
+ }
+
+ @computed("wildcard_web_hook", "web_hook_event_types.[]")
+ get description() {
+ let desc = "";
+
+ this.web_hook_event_types?.forEach((type) => {
+ const name = `${type.name.toLowerCase()}_event`;
+ desc += desc !== "" ? `, ${name}` : name;
+ });
+
+ return this.wildcard_web_hook ? "*" : desc;
+ }
+
+ @observes("group_ids")
+ updateGroupsFilter() {
+ const groupIds = this.group_ids;
+ this.set(
+ "group_names",
+ Site.currentProp("groups").reduce((groupNames, g) => {
+ if (groupIds.includes(g.id)) {
+ groupNames.push(g.name);
+ }
+ return groupNames;
+ }, [] as string[])
+ );
+ }
+
+ groupFinder(term: string) {
+ return Group.findAll({ term, ignore_automatic: false });
+ }
+
+ createProperties(): {
+ payload_url: string;
+ content_type: number;
+ secret: string;
+ wildcard_web_hook: boolean;
+ verify_certificate: boolean;
+ active: boolean;
+ web_hook_event_type_ids: (number | null)[];
+ category_ids: (number | null)[];
+ tag_ids: (string | number | null)[];
+ group_ids: (number | null)[];
+ } {
+ const types = this.web_hook_event_types;
+ // Saving assumes selected category IDs resolve through extras, as in the original model.
+ const categoryIds = this.categories.map((c) => c!.id);
+ const tags = this.tags;
+
+ // Hack as {{group-selector}} accepts a comma-separated string as data source, but
+ // we use an array to populate the datasource above.
+ const groupsFilter = this.group_names;
+ const groupNames =
+ typeof groupsFilter === "string" ? groupsFilter.split(",") : groupsFilter;
+
+ // isEmpty handles null selections before the original map/includes calls.
+ return {
+ payload_url: this.payload_url,
+ content_type: this.content_type,
+ secret: this.secret ?? "",
+ wildcard_web_hook: this.wildcard_web_hook,
+ verify_certificate: this.verify_certificate,
+ active: this.active,
+ web_hook_event_type_ids: isEmpty(types)
+ ? [null]
+ : types!.map((type) => type.id),
+ category_ids: isEmpty(categoryIds) ? [null] : categoryIds,
+ tag_ids: isEmpty(tags)
+ ? [null]
+ : tags!.map((t) => (typeof t === "object" ? t.id : t)),
+ group_ids:
+ isEmpty(groupNames) || isEmpty(groupNames![0])
+ ? [null]
+ : Site.currentProp("groups").reduce((groupIds, g) => {
+ if (groupNames!.includes(g.name)) {
+ groupIds.push(g.id);
+ }
+ return groupIds;
+ }, [] as number[]),
+ };
+ }
+
+ updateProperties() {
+ return this.createProperties();
+ }
+}
+
+declare module "discourse/services/store" {
+ interface ModelRegistry {
+ "web-hook": WebHook;
+ }
+
+ interface ModelCreateAttrsRegistry {
+ "web-hook": WebHookCreateAttrs;
+ }
+}
diff --git a/frontend/discourse/type-tests/models/admin-users-test.ts b/frontend/discourse/type-tests/models/admin-users-test.ts
new file mode 100644
index 00000000000..9d6db0b0ee7
--- /dev/null
+++ b/frontend/discourse/type-tests/models/admin-users-test.ts
@@ -0,0 +1,490 @@
+import type EmberObject from "@ember/object";
+import { expectTypeOf } from "expect-type";
+import AdminUser, {
+ type AdminUserDetails,
+ type AdminUserFields,
+ type AdminUserGroup,
+} from "discourse/admin/models/admin-user";
+import ApiKey, { type ApiKeyFields } from "discourse/admin/models/api-key";
+import EmailLog from "discourse/admin/models/email-log";
+import IncomingEmail, {
+ type IncomingEmailDetails,
+} from "discourse/admin/models/incoming-email";
+import StaffActionLog, {
+ type StaffActionValue,
+} from "discourse/admin/models/staff-action-log";
+import Tl3Requirements, {
+ type Tl3RequirementsFields,
+} from "discourse/admin/models/tl3-requirements";
+import WebHook, {
+ type WebHookCategory,
+ type WebHookEventType,
+} from "discourse/admin/models/web-hook";
+import type { BehaviorTransformerResult } from "discourse/lib/transformer";
+import type RestModel from "discourse/models/rest";
+import type User from "discourse/models/user";
+import type {
+ default as StoreService,
+ ModelCreateAttrsFor,
+ ModelFor,
+ ResultSetOf,
+} from "discourse/services/store";
+
+declare const store: StoreService;
+
+/* Store registrations, under every spelling callers use. */
+
+expectTypeOf<ModelFor<"api-key">>().toEqualTypeOf<ApiKey>();
+expectTypeOf<ModelFor<"web-hook">>().toEqualTypeOf<WebHook>();
+expectTypeOf<ModelFor<"staff-action-log">>().toEqualTypeOf<StaffActionLog>();
+expectTypeOf<ModelFor<"tl3Requirements">>().toEqualTypeOf<Tl3Requirements>();
+expectTypeOf<ModelFor<"tl3-requirements">>().toEqualTypeOf<Tl3Requirements>();
+expectTypeOf(store.findAll("api-key")).resolves.toEqualTypeOf<
+ ResultSetOf<ApiKey> | undefined
+>();
+expectTypeOf(store.find("web-hook", 1)).resolves.toEqualTypeOf<WebHook>();
+store.createRecord("web-hook");
+store
+ .createRecord("api-key")
+ .save({ description: "New", scope_mode: "global" });
+
+/* AdminUser: `/admin/users/:id` details and `/admin/users/list` rows. */
+
+expectTypeOf(AdminUser.find(1)).resolves.toEqualTypeOf<AdminUser>();
+expectTypeOf(
+ AdminUser.find("1", { raw: false })
+).resolves.toEqualTypeOf<AdminUser>();
+// Raw lookups return the response for `setProperties`, not an instance.
+expectTypeOf(
+ AdminUser.find(1, { raw: true })
+).resolves.not.toExtend<AdminUser>();
+expectTypeOf(AdminUser.find(1, { raw: true })).resolves.toHaveProperty(
+ "loadedDetails"
+);
+expectTypeOf(
+ AdminUser.findAll("active", { filter: "bruce", show_emails: true, page: 2 })
+).resolves.toEqualTypeOf<AdminUser[]>();
+// Embedded basic users become partial instances.
+AdminUser.create({
+ id: 1,
+ username: "anne",
+ name: null,
+ avatar_template: "/a.png",
+});
+
+declare const admin: AdminUser;
+expectTypeOf(admin).toExtend<User>();
+expectTypeOf(admin.adminUserView).toEqualTypeOf<boolean>();
+expectTypeOf(admin.last_seen_at).toEqualTypeOf<string | null | undefined>();
+expectTypeOf(admin.last_emailed_at).toEqualTypeOf<string | null | undefined>();
+expectTypeOf(admin.last_seen_age).toEqualTypeOf<number | null | undefined>();
+expectTypeOf(admin.manual_locked_trust_level).toEqualTypeOf<
+ number | null | undefined
+>();
+expectTypeOf(admin.secondary_emails).toEqualTypeOf<string[] | undefined>();
+// List rows omit the detail fields, and details omit the list capabilities.
+expectTypeOf(admin.can_be_suspended).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(admin.bounce_score).toEqualTypeOf<number | undefined>();
+expectTypeOf(admin.reset_bounce_score_after).toEqualTypeOf<
+ string | null | undefined
+>();
+expectTypeOf(admin.full_suspend_reason).toEqualTypeOf<
+ string | null | undefined
+>();
+expectTypeOf(admin.next_penalty).toEqualTypeOf<string | null | undefined>();
+// The top-level counts have no total; the TL3 counts do.
+expectTypeOf(admin.penalty_counts).toEqualTypeOf<
+ { silenced: number; suspended: number } | undefined
+>();
+expectTypeOf(admin.suspended_by?.username).toEqualTypeOf<string | undefined>();
+expectTypeOf(admin.single_sign_on_record?.external_id).not.toBeAny();
+expectTypeOf(admin.upcoming_changes_stats?.[0].enabled).not.toBeAny();
+expectTypeOf(admin.tl3_requirements?.requirements_met).toEqualTypeOf<
+ boolean | undefined
+>();
+expectTypeOf(admin.can_grant_admin).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(admin.api_key_count).toEqualTypeOf<number | undefined>();
+// The admin template edits these in place.
+admin.trust_level = 2;
+admin.primary_group_id = null;
+admin.set("can_activate", false);
+
+expectTypeOf(admin.canViewProfile).toEqualTypeOf<boolean | undefined>();
+expectTypeOf(admin.canResetBounceScore).toEqualTypeOf<boolean>();
+expectTypeOf(admin.dirty).toEqualTypeOf<boolean>();
+expectTypeOf(admin.canLockTrustLevel).toEqualTypeOf<boolean>();
+expectTypeOf(admin.canSuspend).toEqualTypeOf<boolean>();
+expectTypeOf(admin.canSilence).toEqualTypeOf<boolean>();
+expectTypeOf(admin.customGroups).not.toBeAny();
+expectTypeOf(admin.automaticGroups).toEqualTypeOf<typeof admin.customGroups>();
+expectTypeOf(admin.bounceScore).toEqualTypeOf<string | number | undefined>();
+expectTypeOf(admin.bounceScoreExplanation).toEqualTypeOf<string>();
+expectTypeOf(admin.bounceLink).toEqualTypeOf<string>();
+expectTypeOf(admin.suspendDuration).toEqualTypeOf<string>();
+expectTypeOf(admin.tl3Requirements).toEqualTypeOf<
+ Tl3Requirements | undefined
+>();
+expectTypeOf(admin.suspendedBy).toEqualTypeOf<AdminUser | null>();
+expectTypeOf(admin.silencedBy).toEqualTypeOf<AdminUser | null>();
+expectTypeOf(admin.approvedBy).toEqualTypeOf<AdminUser | null>();
+
+expectTypeOf(admin.loadDetails()).resolves.toEqualTypeOf<AdminUser>();
+// Some callers grant admin without form data.
+admin.grantAdmin();
+admin.grantAdmin({ email_confirmation_token: "abc" });
+admin.lockTrustLevel(true);
+admin.groupRemoved(5);
+admin.suspend({
+ suspend_until: "2027-01-01",
+ reason: "Bad",
+ message: "msg",
+ post_id: 3,
+});
+admin.silence({ silenced_till: "2027-01-01", reason: "Noisy" });
+admin.destroy({ deletePosts: true, block_email: true });
+admin.merge({ target_username: "bruce" });
+
+/* Tl3Requirements: embedded in details for TL2 and above. */
+
+declare const tl3: Tl3Requirements;
+expectTypeOf(tl3).toExtend<EmberObject>();
+expectTypeOf(tl3.time_period).toEqualTypeOf<number>();
+expectTypeOf(tl3.min_likes_received_users).toEqualTypeOf<number>();
+expectTypeOf(tl3.requirements_lost).toEqualTypeOf<boolean>();
+expectTypeOf(tl3.on_grace_period).toEqualTypeOf<boolean>();
+expectTypeOf(tl3.penalty_counts).toEqualTypeOf<{
+ silenced: number;
+ suspended: number;
+ total: number;
+}>();
+expectTypeOf(tl3.days_visited_percent).toEqualTypeOf<number>();
+expectTypeOf(tl3.capped_topics_replied_to).toEqualTypeOf<boolean>();
+expectTypeOf(tl3.met.likes_received_days).toEqualTypeOf<boolean>();
+expectTypeOf(tl3.met.level_locked).toEqualTypeOf<boolean>();
+expectTypeOf(tl3.met.suspended).toEqualTypeOf<boolean>();
+
+/* ApiKey: `/admin/api/keys` list rows and detail records. */
+
+declare const apiKey: ApiKey;
+expectTypeOf(apiKey).toExtend<RestModel>();
+expectTypeOf(apiKey.id).toEqualTypeOf<number>();
+expectTypeOf(apiKey.truncated_key).toEqualTypeOf<string>();
+expectTypeOf(apiKey.scope_mode).toEqualTypeOf<
+ "global" | "read_only" | "granular" | null
+>();
+expectTypeOf(apiKey.last_used_at).toEqualTypeOf<string | null>();
+expectTypeOf(apiKey.revoked_at).toEqualTypeOf<string | null>();
+// Only detail records carry scopes, and only new keys carry the full key.
+expectTypeOf(apiKey.updated_at).toEqualTypeOf<string | undefined>();
+expectTypeOf(apiKey.key).toEqualTypeOf<string | undefined>();
+expectTypeOf(apiKey.api_key_scopes?.[0].allowed_parameters).toEqualTypeOf<
+ Record<string, string[]> | null | undefined
+>();
+expectTypeOf(apiKey.api_key_scopes?.[0].urls).toEqualTypeOf<
+ string[] | undefined
+>();
+expectTypeOf(apiKey.user).toEqualTypeOf<AdminUser | null | undefined>();
+expectTypeOf(apiKey.createdBy).toEqualTypeOf<AdminUser | null | undefined>();
+// The setters wrap raw basic users.
+apiKey.user = { id: 1, username: "anne", avatar_template: "/a.png" };
+apiKey.created_by = null;
+apiKey.description = "Renamed";
+expectTypeOf<ApiKey["description"]>().toEqualTypeOf<string | null>();
+expectTypeOf(apiKey.truncatedKey).toEqualTypeOf<string>();
+expectTypeOf(apiKey.shortDescription).toEqualTypeOf<string | null>();
+expectTypeOf(apiKey.basePath).toEqualTypeOf<string>();
+expectTypeOf(apiKey.revoke()).not.toBeAny();
+expectTypeOf(apiKey.createProperties()).not.toBeAny();
+
+/* EmailLog: sent, bounced and skipped rows. */
+
+expectTypeOf(
+ EmailLog.findAll({ status: "skipped", address: "[email protected]" }, 50)
+).resolves.toEqualTypeOf<EmailLog[]>();
+EmailLog.findAll();
+EmailLog.create();
+EmailLog.create({
+ id: 249,
+ to_address: "[email protected]",
+ email_type: "signup",
+ user_id: 1,
+ created_at: "2026-10-28T00:44:19.980Z",
+ cc_addresses: null,
+ post_id: null,
+ bounced: true,
+ has_bounce_key: true,
+ smtp_transaction_response: null,
+ user: { id: 1, username: "bruce", name: null, avatar_template: "/a.png" },
+});
+EmailLog.create({
+ id: 16,
+ to_address: "[email protected]",
+ email_type: "invite",
+ user_id: null,
+ created_at: "2026-10-28T00:44:19.979Z",
+ skipped_reason: "Custom reason",
+ user: null,
+});
+
+declare const emailLog: EmailLog;
+expectTypeOf(emailLog).toExtend<EmberObject>();
+expectTypeOf(emailLog.user).toEqualTypeOf<AdminUser | null>();
+expectTypeOf(emailLog.user_id).toEqualTypeOf<number | null>();
+expectTypeOf(emailLog.cc_addresses).toEqualTypeOf<
+ string[] | null | undefined
+>();
+expectTypeOf(emailLog.skipped_reason).toEqualTypeOf<string | undefined>();
+expectTypeOf(emailLog.reply_key).toEqualTypeOf<string | undefined>();
+expectTypeOf(emailLog.post_url).toEqualTypeOf<string | undefined>();
+
+/* IncomingEmail: received and rejected rows, plus the raw detail lookups. */
+
+expectTypeOf(
+ IncomingEmail.findAll({ status: "rejected" }, 0)
+).resolves.toEqualTypeOf<IncomingEmail[]>();
+expectTypeOf(IncomingEmail.find(1)).resolves.not.toExtend<IncomingEmail>();
+expectTypeOf(IncomingEmail.find(1)).resolves.toEqualTypeOf<
+ Awaited<ReturnType<typeof IncomingEmail.findByBounced>>
+>();
+expectTypeOf(IncomingEmail.find(1)).resolves.toHaveProperty("headers");
+IncomingEmail.create({
+ id: 302,
+ created_at: "2026-10-28T00:44:19.984Z",
+ from_address: "[email protected]",
+ to_addresses: ["[email protected]"],
+ cc_addresses: null,
+ subject: "Hello",
+ error: "Email::Receiver::BadDestinationAddress",
+ user: null,
+});
+
+declare const incoming: IncomingEmail;
+expectTypeOf(incoming.to_addresses).toEqualTypeOf<string[] | null>();
+expectTypeOf(incoming.error).toEqualTypeOf<string | undefined>();
+expectTypeOf(incoming.user).toEqualTypeOf<AdminUser | null>();
+
+/* StaffActionLog: `/admin/logs/staff_action_logs` rows. */
+
+declare const log: StaffActionLog;
+expectTypeOf(log).toExtend<RestModel>();
+expectTypeOf(log.action_name).toEqualTypeOf<string>();
+expectTypeOf(log.action).toEqualTypeOf<number>();
+expectTypeOf(log.details).toEqualTypeOf<string | null>();
+expectTypeOf(log.custom_type).toEqualTypeOf<string | null>();
+expectTypeOf(log.expires_at).toEqualTypeOf<string | null>();
+expectTypeOf(log.reviewable_id).toEqualTypeOf<number | undefined>();
+expectTypeOf(log.acting_user).toEqualTypeOf<AdminUser | null>();
+expectTypeOf(log.target_user).toEqualTypeOf<AdminUser | null>();
+// Theme and tag group changes send parsed JSON; other actions send strings.
+log.new_value = { name: "Cool theme" };
+log.previous_value = "Old";
+log.new_value = null;
+expectTypeOf(log.showFullDetails).toEqualTypeOf<boolean>();
+expectTypeOf(log.actionName).toEqualTypeOf<string>();
+expectTypeOf(log.formattedDetails).toEqualTypeOf<string>();
+expectTypeOf(log.useCustomModalForDetails).toEqualTypeOf<boolean>();
+expectTypeOf(log.useModalForDetails).not.toBeAny();
+expectTypeOf<boolean>().toExtend<typeof log.useModalForDetails>();
+expectTypeOf(
+ StaffActionLog.findAll({ action_name: "x" })
+).resolves.toHaveProperty("staff_action_logs");
+
+/* WebHook: `/admin/api/web_hooks` records and their extras. */
+
+declare const webHook: WebHook;
+expectTypeOf(webHook).toExtend<RestModel>();
+expectTypeOf(webHook.payload_url).toEqualTypeOf<string>();
+expectTypeOf(webHook.content_type).toEqualTypeOf<number>();
+expectTypeOf(webHook.last_delivery_status).toEqualTypeOf<number>();
+expectTypeOf(webHook.secret).toEqualTypeOf<string | null>();
+expectTypeOf(webHook.category_ids).toEqualTypeOf<number[]>();
+expectTypeOf(webHook.group_ids).toEqualTypeOf<number[]>();
+expectTypeOf(webHook.web_hook_event_types?.[0].group).toEqualTypeOf<
+ string | null | undefined
+>();
+// The group selector stores a comma-separated string.
+webHook.group_names = "staff,admins";
+webHook.group_names = ["staff"];
+webHook.group_names = null;
+// Tag selectors store names alongside serialized tags.
+webHook.tags = ["tag1", { id: 1, name: "tag2", slug: "tag2" }];
+expectTypeOf(webHook.wildcard).toEqualTypeOf<"wildcard" | "individual">();
+webHook.wildcard = "individual";
+expectTypeOf(webHook.description).toEqualTypeOf<string>();
+expectTypeOf(webHook.categories).not.toBeAny();
+expectTypeOf(webHook.groupFinder("staff")).not.toBeAny();
+expectTypeOf(webHook.createProperties().web_hook_event_type_ids).toEqualTypeOf<
+ (number | null)[]
+>();
+expectTypeOf(webHook.updateProperties()).toEqualTypeOf<
+ ReturnType<typeof webHook.createProperties>
+>();
+const extras = new WebHook.ExtrasClass({
+ content_types: [{ id: 1, name: "application/json" }],
+ delivery_statuses: [{ id: 1, name: "inactive" }],
+});
+expectTypeOf(extras.findCategoryById(1)).not.toBeAny();
+expectTypeOf(extras.grouped_event_types).not.toBeAny();
+
+/* Raw lookups, subclass factories and store creation. */
+
+declare const raw: boolean;
+
+expectTypeOf(AdminUser.find(1, { raw })).resolves.toEqualTypeOf<
+ AdminUser | AdminUserDetails
+>();
+expectTypeOf(AdminUser.find(1, null)).resolves.toEqualTypeOf<AdminUser>();
+expectTypeOf(AdminUser.find(1, { raw: true })).resolves.not.toHaveProperty(
+ "destroy"
+);
+expectTypeOf(AdminUser.find(1, { raw: true }))
+ .resolves.toHaveProperty("secondary_emails")
+ .toEqualTypeOf<string[] | undefined>();
+expectTypeOf(AdminUser.find(1, { raw: true }))
+ .resolves.toHaveProperty("associated_accounts")
+ .toEqualTypeOf<User["associated_accounts"]>();
+expectTypeOf<"canViewProfile">().not.toExtend<keyof AdminUserFields>();
+expectTypeOf<"user">().not.toExtend<keyof ApiKeyFields>();
+
+class PluginAdminUser extends AdminUser {
+ declare pluginValue?: string;
+ declare trust_level: 2;
+ declare visibleGroups: AdminUserGroup[] | undefined;
+}
+
+class PluginApiKey extends ApiKey {
+ declare pluginValue?: string;
+}
+
+class PluginStaffActionLog extends StaffActionLog {
+ declare pluginValue?: string;
+}
+
+class PluginWebHook extends WebHook {
+ declare pluginValue?: string;
+}
+
+class PluginEmailLog extends EmailLog {
+ declare pluginValue?: string;
+}
+
+class PluginIncomingEmail extends IncomingEmail {
+ declare pluginValue?: string;
+}
+
+expectTypeOf(
+ PluginAdminUser.create({ pluginValue: "x" })
+).toEqualTypeOf<PluginAdminUser>();
+expectTypeOf(
+ PluginApiKey.create({ pluginValue: "x" })
+).toEqualTypeOf<PluginApiKey>();
+expectTypeOf(
+ PluginStaffActionLog.create({ pluginValue: "x" })
+).toEqualTypeOf<PluginStaffActionLog>();
+expectTypeOf(
+ PluginEmailLog.create({ pluginValue: "x" })
+).toEqualTypeOf<PluginEmailLog>();
+expectTypeOf(
+ PluginIncomingEmail.create({ pluginValue: "x" })
+).toEqualTypeOf<PluginIncomingEmail>();
+// Web hooks sideload their categories through the basic category serializer.
+const webHookCategory = {
+ id: 1,
+ name: "Support",
+ slug: "support",
+ color: "0088CC",
+ text_color: "FFFFFF",
+ style_type: "square",
+ icon: null,
+ emoji: null,
+ read_restricted: false,
+} as const;
+expectTypeOf(
+ PluginWebHook.create({
+ pluginValue: "x",
+ categories: [webHookCategory],
+ })
+).toEqualTypeOf<PluginWebHook>();
+expectTypeOf<typeof WebHook>().toExtend<typeof RestModel>();
+expectTypeOf<typeof PluginAdminUser>().toExtend<typeof User>();
+expectTypeOf<typeof EmailLog>().toExtend<typeof EmberObject>();
+expectTypeOf<typeof IncomingEmail>().toExtend<typeof EmberObject>();
+expectTypeOf<typeof ApiKey>().toExtend<typeof RestModel>();
+expectTypeOf<typeof StaffActionLog>().toExtend<typeof RestModel>();
+
+const basic = { id: 1, username: "anne", avatar_template: "/a.png" };
+store.createRecord("apiKey", { user: basic, created_by: basic });
+store.createRecord("staff-action-log", {
+ acting_user: basic,
+ target_user: null,
+});
+expectTypeOf(
+ store.createRecord("email-log", { user: basic })
+).toEqualTypeOf<EmailLog>();
+expectTypeOf<ModelCreateAttrsFor<"tl3Requirements">>().toEqualTypeOf<
+ Partial<Tl3RequirementsFields>
+>();
+expectTypeOf(
+ store.createRecord("tl3Requirements", { requirements_met: true })
+).toEqualTypeOf<Tl3Requirements>();
+apiKey.user = null;
+apiKey.created_by = basic;
+expectTypeOf<"created_by">().not.toExtend<keyof ApiKeyFields>();
+expectTypeOf(apiKey.createdBy).toEqualTypeOf<AdminUser | null | undefined>();
+
+expectTypeOf(admin.unsuspend()).toEqualTypeOf<
+ BehaviorTransformerResult<ReturnType<AdminUser["suspend"]>>
+>();
+expectTypeOf(admin.unsilence()).toEqualTypeOf<
+ BehaviorTransformerResult<Promise<void>>
+>();
+expectTypeOf(admin.sendActivationEmail()).resolves.toEqualTypeOf<unknown>();
+expectTypeOf(admin.deleteAllPosts()).resolves.toEqualTypeOf<{
+ posts_deleted: number;
+}>();
+expectTypeOf(admin.deleteAllPostsDecider()).resolves.toEqualTypeOf<{
+ job_enqueued: boolean;
+ post_count: number;
+}>();
+
+expectTypeOf(
+ IncomingEmail.findByBounced(1)
+).resolves.toEqualTypeOf<IncomingEmailDetails>();
+expectTypeOf<IncomingEmailDetails>().not.toHaveProperty("id");
+expectTypeOf<IncomingEmailDetails>().not.toHaveProperty("user");
+expectTypeOf(StaffActionLog.findAll())
+ .resolves.toHaveProperty("user_history_actions")
+ .toEqualTypeOf<{ id: string; action_id: number }[] | undefined>();
+
+expectTypeOf(webHook.categories).toEqualTypeOf<
+ (WebHookCategory | undefined)[]
+>();
+expectTypeOf<ModelCreateAttrsFor<"web-hook">["categories"]>().toEqualTypeOf<
+ WebHookCategory[] | undefined
+>();
+webHook.categories = [webHookCategory];
+// @ts-expect-error an id and a name are not a saved category
+webHook.categories = [{ id: 1, name: "Support" }];
+webHook.tags = [1, "support", { id: 2, name: "help", slug: "help" }];
+const emptyExtras = new WebHook.ExtrasClass({ categories: null });
+expectTypeOf(emptyExtras.findCategoryById(1)).toEqualTypeOf<
+ WebHookCategory | undefined
+>();
+expectTypeOf(emptyExtras.grouped_event_types).toEqualTypeOf<
+ Record<string, WebHookEventType[]> | []
+>();
+
+// New records from the store start empty.
+expectTypeOf<ApiKey["created_at"]>().toEqualTypeOf<string | undefined>();
+expectTypeOf<EmailLog["id"]>().toEqualTypeOf<number | undefined>();
+expectTypeOf<EmailLog["to_address"]>().toEqualTypeOf<string | undefined>();
+expectTypeOf<IncomingEmail["cc_addresses"]>().toEqualTypeOf<
+ string[] | null | undefined
+>();
+expectTypeOf<StaffActionLog["new_value"]>().toEqualTypeOf<
+ StaffActionValue | undefined
+>();
+expectTypeOf<WebHook["id"]>().toEqualTypeOf<number | undefined>();
+expectTypeOf<WebHook["extras"]>().toEqualTypeOf<
+ InstanceType<typeof WebHook.ExtrasClass> | undefined
+>();