A platform for community discussion. Free, open, simple.
DEV: Convert notification, review and invite models to TypeScript (#45199)
Sérgio Saquetim0efb9ba58827
diff --git a/frontend/discourse/app/models/invite.js b/frontend/discourse/app/models/invite.jsdeleted file mode 100644index 0a4271201eb..00000000000--- a/frontend/discourse/app/models/invite.js+++ /dev/null@@ -1,116 +0,0 @@-import EmberObject, { computed, set } from "@ember/object";-import { trackedArray } from "@ember/reactive/collections";-import { isNone } from "@ember/utils";-import { ajax } from "discourse/lib/ajax";-import { popupAjaxError } from "discourse/lib/ajax-error";-import { userPath } from "discourse/lib/url";-import Topic from "discourse/models/topic";-import User from "discourse/models/user";--export default class Invite extends EmberObject {- static create() {- const result = super.create(...arguments);- if (result.user) {- result.user = User.create(result.user);- }- return result;- }-- static async findInvitedBy(user, filter, search, offset) {- if (!user) {- return;- }-- const data = {};- if (!isNone(filter)) {- data.filter = filter;- }- if (!isNone(search)) {- data.search = search;- }- data.offset = offset || 0;-- const result = await ajax(userPath(`${user.username_lower}/invited.json`), {- data,- });-- result.invites = trackedArray(result.invites.map((i) => Invite.create(i)));-- return EmberObject.create(result);- }-- static reinviteAll() {- return ajax("/invites/reinvite-all", { type: "POST" });- }-- static destroyAllExpired(user) {- return ajax("/invites/destroy-all-expired", {- type: "POST",- data: { username: user.username },- });- }-- @computed("topics.firstObject.id")- get topicId() {- return this.topics?.firstObject?.id;- }-- set topicId(value) {- set(this, "topics.firstObject.id", value);- }-- @computed("topics.firstObject.title")- get topicTitle() {- return this.topics?.firstObject?.title;- }-- set topicTitle(value) {- set(this, "topics.firstObject.title", value);- }-- @computed("invite_key")- get shortKey() {- return this.invite_key.slice(0, 4) + "...";- }-- @computed("groups")- get groupIds() {- return this.groups ? this.groups.map((group) => group.id) : [];- }-- @computed("topics.firstObject")- get topic() {- return this.topics?.firstObject- ? Topic.create(this.topics?.firstObject)- : null;- }-- @computed("email", "domain")- get emailOrDomain() {- return this.email || this.domain;- }-- save(data) {- const promise = this.id- ? ajax(`/invites/${this.id}`, { type: "PUT", data })- : ajax("/invites", { type: "POST", data });-- return promise.then((result) => this.setProperties(result));- }-- destroy() {- return ajax("/invites", {- type: "DELETE",- data: { id: this.id },- }).then(() => this.set("destroyed", true));- }-- reinvite() {- return ajax("/invites/reinvite", {- type: "POST",- data: { email: this.email },- })- .then(() => this.set("reinvited", true))- .catch(popupAjaxError);- }-}diff --git a/frontend/discourse/app/models/invite.ts b/frontend/discourse/app/models/invite.tsnew file mode 100644index 00000000000..70dd24b3452--- /dev/null+++ b/frontend/discourse/app/models/invite.ts@@ -0,0 +1,187 @@+import EmberObject, { computed, set } from "@ember/object";+import { trackedArray } from "@ember/reactive/collections";+import { isNone } from "@ember/utils";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { userPath } from "discourse/lib/url";+import Topic, { type TopicFields } from "discourse/models/topic";+import User, { type UserCreateAttrs } from "discourse/models/user";++/** Detail fields are absent for other viewers; redeemed records use a different serializer. */+export interface InviteFields {+ id?: number;+ invite_key?: string;+ link?: string;+ description?: string | null;+ email?: string | null;+ domain?: string | null;+ emailed?: boolean;+ can_delete_invite?: boolean;+ max_redemptions_allowed?: number;+ redemption_count?: number;+ custom_message?: string | null;+ created_at?: string;+ updated_at?: string;+ expires_at?: string;+ expired?: boolean;+ grants_admin?: boolean;+ grants_moderator?: boolean;+ /** Server arrays do not supply firstObject; legacy client collections can. */+ topics?: InviteTopic[] & { firstObject?: InviteTopic };+ groups?: { id: number; name: string }[];+ redeemed_at?: string;+ invite_source?: "link" | "email";+ user?: User;+ destroyed?: boolean;+ reinvited?: boolean;+}++export type InviteTopic = Pick<+ TopicFields,+ "id" | "title" | "slug" | "fancy_title" | "posts_count"+>;++/** create wraps the raw redeemed user, but save only merges the response. */+export type InviteCreateAttrs<M = Invite> = Omit<Partial<M>, "user"> & {+ user?: UserCreateAttrs | User;+};++export interface InvitedFields {+ invites: Invite[];+ can_see_invite_details: boolean;+ counts: { pending: number; expired: number; redeemed: number; total: number };+}++export type Invited = EmberObject & InvitedFields;++// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging+export default interface Invite extends InviteFields {}++// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging+export default class Invite extends EmberObject {+ static override create<C extends typeof EmberObject>(+ this: C,+ ...args: InviteCreateAttrs<InstanceType<C>>[]+ ): InstanceType<C> {+ const result = super.create(...args) as InstanceType<C> & Invite;+ if (result.user) {+ // TODO(typescript-pending): UserCreateAttrs requires an index signature; remove when User.create accepts model instances.+ result.user = User.create(result.user as UserCreateAttrs);+ }+ return result;+ }++ static async findInvitedBy(+ user?: User | null,+ filter?: string | null,+ search?: string | null,+ offset?: number+ ): Promise<Invited | undefined> {+ if (!user) {+ return;+ }++ const data: { filter?: string; search?: string; offset?: number } = {};+ if (!isNone(filter)) {+ data.filter = filter;+ }+ if (!isNone(search)) {+ data.search = search;+ }+ data.offset = offset || 0;++ // TODO(typescript-pending): ajax has no endpoint response types; remove the assertion when generic.+ const result = (await ajax(+ userPath(`${user.username_lower}/invited.json`),+ {+ data,+ }+ )) as Omit<InvitedFields, "invites"> & { invites: InviteCreateAttrs[] };++ result.invites = trackedArray(result.invites.map((i) => Invite.create(i)));++ return EmberObject.create(result as Invited);+ }++ static reinviteAll(): Promise<unknown> {+ return ajax("/invites/reinvite-all", { type: "POST" });+ }++ static destroyAllExpired(user: User): Promise<unknown> {+ return ajax("/invites/destroy-all-expired", {+ type: "POST",+ data: { username: user.username },+ });+ }++ @computed("topics.firstObject.id")+ get topicId() {+ return this.topics?.firstObject?.id;+ }++ set topicId(value: number | undefined) {+ set(this, "topics.firstObject.id", value);+ }++ @computed("topics.firstObject.title")+ get topicTitle() {+ return this.topics?.firstObject?.title;+ }++ set topicTitle(value: string | undefined) {+ set(this, "topics.firstObject.title", value);+ }++ @computed("invite_key")+ /** Requires a detail-visible pending invite with an invite key. */+ get shortKey() {+ return this.invite_key!.slice(0, 4) + "...";+ }++ @computed("groups")+ get groupIds() {+ return this.groups ? this.groups.map((group) => group.id) : [];+ }++ @computed("topics.firstObject")+ get topic() {+ return this.topics?.firstObject+ ? Topic.create(this.topics?.firstObject)+ : null;+ }++ @computed("email", "domain")+ get emailOrDomain() {+ return this.email || this.domain;+ }++ save(data: object) {+ const promise = this.id+ ? ajax(`/invites/${this.id}`, { type: "PUT", data })+ : ajax("/invites", { type: "POST", data });++ // TODO(typescript-pending): ajax has no endpoint response types; remove the callback annotation when generic.+ return promise.then((result: Partial<InviteFields>) =>+ this.setProperties(result)+ );+ }++ /** Deletes the invite remotely rather than scheduling Ember destruction. */+ override destroy(this: never, ...args: never[]): never;+ override destroy(): Promise<boolean>;+ override destroy(): Promise<boolean> {+ return ajax("/invites", {+ type: "DELETE",+ data: { id: this.id },+ }).then(() => this.set("destroyed", true));+ }++ reinvite(): Promise<boolean | void> {+ return ajax("/invites/reinvite", {+ type: "POST",+ data: { email: this.email },+ })+ .then(() => this.set("reinvited", true))+ .catch(popupAjaxError);+ }+}diff --git a/frontend/discourse/app/models/notification.js b/frontend/discourse/app/models/notification.jsdeleted file mode 100644index 24c5eb0d038..00000000000--- a/frontend/discourse/app/models/notification.js+++ /dev/null@@ -1,17 +0,0 @@-import { tracked } from "@glimmer/tracking";-import { applyModelTransformations } from "discourse/lib/model-transformers";-import RestModel from "discourse/models/rest";--export default class Notification extends RestModel {- static async applyTransformations(notifications) {- await applyModelTransformations("notification", notifications);- }-- static async initializeNotifications(rawList) {- const notifications = rawList.map((n) => this.create(n));- await this.applyTransformations(notifications);- return notifications;- }-- @tracked read;-}diff --git a/frontend/discourse/app/models/notification.ts b/frontend/discourse/app/models/notification.tsnew file mode 100644index 00000000000..4e091e175e0--- /dev/null+++ b/frontend/discourse/app/models/notification.ts@@ -0,0 +1,86 @@+import { tracked } from "@glimmer/tracking";+import { applyModelTransformations } from "discourse/lib/model-transformers";+import RestModel, { type RestModelAttrs } from "discourse/models/rest";++/** Known core packet keys are optional; other producers can add arbitrary data. */+export interface NotificationData {+ display_username?: string;+ display_name?: string | null;+ topic_title?: string;+ original_post_id?: number;+ original_post_type?: number;+ original_user_id?: number;+ original_username?: string;+ original_name?: string | null;+ revision_number?: number | null;+ group_id?: number;+ group_name?: string;+ reply_to_post_number?: number;+ consolidated_count?: number;+ previous_notification_id?: number;+ username?: string;+ username2?: string;+ name?: string | null;+ name2?: string | null;+ count?: number;+ badge_id?: number;+ badge_name?: string;+ badge_slug?: string;+ badge_title?: boolean;+ inbox_count?: number;+ message?: string;+ title?: string;+ post_url?: string;+ bookmarkable_url?: string;+ bookmark_name?: string | null;+ bookmark_id?: number;+ bookmarkable_type?: string;+ bookmarkable_id?: number;+ reviewable_id?: number;+ reviewable_note_id?: number;+ upcoming_change_names?: string[];+ upcoming_change_humanized_names?: string[];+ upcoming_change_name?: string;+ upcoming_change_humanized_name?: string;+ [key: string]: unknown;+}++export interface NotificationFields {+ id: number;+ user_id: number;+ notification_type: number;+ high_priority: boolean;+ created_at: string;+ topic_id: number | null;+ post_number: number | null;+ slug: string | null;+ data: NotificationData;+ fancy_title?: string;+ fancy_title_localized?: boolean;+ locale?: string | null;+ external_id?: string | null;+ is_warning?: boolean;+ acting_user_avatar_template?: string;+ acting_user_name?: string | null;+}++// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging+export default interface Notification extends NotificationFields {}++// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging+export default class Notification extends RestModel {+ static async applyTransformations(notifications: Notification[]) {+ await applyModelTransformations("notification", notifications);+ }++ static async initializeNotifications(+ rawList: RestModelAttrs<Notification>[]+ ) {+ const notifications = rawList.map((n) => this.create(n));+ await this.applyTransformations(notifications);+ return notifications;+ }++ /** Assigned by create; the bare tracked field starts undefined. */+ @tracked read!: boolean;+}diff --git a/frontend/discourse/app/models/reviewable.js b/frontend/discourse/app/models/reviewable.jsdeleted file mode 100644index b4f320d7529..00000000000--- a/frontend/discourse/app/models/reviewable.js+++ /dev/null@@ -1,179 +0,0 @@-import { tracked } from "@glimmer/tracking";-import { computed } from "@ember/object";-import { dasherize, underscore } from "@ember/string";-import { Promise } from "rsvp";-import { ajax } from "discourse/lib/ajax";-import { uniqueItemsFromArray } from "discourse/lib/array-tools";-import { autoTrackedArray } from "discourse/lib/tracked-tools";-import RestModel from "discourse/models/rest";-import I18n, { i18n } from "discourse-i18n";-import Category from "./category.ts";--export const PENDING = 0;-export const APPROVED = 1;-export const REJECTED = 2;-export const IGNORED = 3;-export const DELETED = 4;--export default class Reviewable extends RestModel {- static munge(json) {- // ensure we are not overriding category computed property- delete json.category;- return json;- }-- @tracked author_penalties;- @tracked blank_post;- @tracked bundled_actions;- @tracked can_edit;- @tracked category_id;- @tracked claimed_by;- @tracked cooked;- @tracked created_at;- @tracked created_by;- @tracked created_from_flag;- @tracked deleted_at;- @tracked dsa_classification;- @tracked editable_fields;- @tracked fancy_title;- @tracked id;- @tracked last_performing_username;- @tracked payload;- @tracked post_id;- @tracked post_updated_at;- @tracked post_version;- @tracked raw;- @tracked removed_topic_id;- @tracked reviewable_histories;- @tracked reviewable_scores;- @tracked score;- @tracked status;- @tracked target_created_at;- @tracked target_created_by;- @tracked target_created_by_trust_level;- @tracked target_deleted_at;- @tracked target_deleted_by;- @tracked target_id;- @tracked target_type;- @tracked target_url;- @tracked topic;- @tracked topic_id;- @tracked topic_tags;- @tracked topic_url;- @tracked type;- @tracked type_source;- @tracked version;- @autoTrackedArray reviewable_notes = [];-- @computed("type", "topic")- get resolvedType() {- // Display "Queued Topic" if the post will create a topic- if (this.type === "ReviewableQueuedPost" && !this.topic) {- return "ReviewableQueuedTopic";- }-- return this.type;- }-- @computed("resolvedType")- get humanType() {- return i18n(`review.types.${underscore(this.resolvedType)}.title`, {- defaultValue: "",- });- }-- @computed("humanType")- get humanTypeCssClass() {- return "-" + dasherize(this.humanType);- }-- @computed("resolvedType")- get humanNoun() {- return i18n(`review.types.${underscore(this.resolvedType)}.noun`, {- defaultValue: "reviewable",- });- }-- @computed("humanNoun")- get flaggedReviewableContextQuestion() {- const uniqueReviewableScores = uniqueItemsFromArray(- this.reviewable_scores,- "score_type.type"- );-- if (uniqueReviewableScores.length === 1) {- if (uniqueReviewableScores[0].score_type.type === "notify_moderators") {- return i18n("review.context_question.something_else_wrong", {- reviewable_type: this.humanNoun,- });- }- }-- const listOfQuestions = I18n.listJoiner(- uniqueItemsFromArray(- uniqueReviewableScores.map((score) =>- score.score_type.title.toLowerCase()- )- ),- i18n("review.context_question.delimiter")- );-- return i18n("review.context_question.is_this_post", {- reviewable_human_score_types: listOfQuestions,- reviewable_type: this.humanNoun,- });- }-- @computed("resolvedType", "reviewable_scores", "status")- get userReviewableContextQuestion() {- if (this.resolvedType === "ReviewableUser") {- // in this case the only remaining action is "scrub record" so the question shouldn't show- if (this.status !== PENDING) {- return null;- }- const isSuspectUser = this.reviewable_scores?.some(- (score) => score.reason_type === "suspect_user"- );- if (isSuspectUser) {- return i18n("review.context_question.suspect_user");- }- return i18n("review.context_question.approve_user");- }- if (this.resolvedType === "ReviewableQueuedPost") {- return i18n("review.context_question.approve_post");- }- if (this.resolvedType === "ReviewableQueuedTopic") {- return i18n("review.context_question.approve_topic");- }- if (this.resolvedType === "ReviewablePost") {- return i18n("review.context_question.approve_post");- }- return null;- }-- @computed("category_id")- get category() {- return Category.findById(this.category_id);- }-- update(updates) {- // If no changes, do nothing- if (Object.keys(updates).length === 0) {- return Promise.resolve();- }-- let adapter = this.store.adapterFor("reviewable");- return ajax(- `/review/${this.id}?version=${this.version}`,- adapter.getPayload("PUT", { reviewable: updates })- ).then((updated) => {- updated.payload = Object.assign(- {},- this.payload || {},- updated.payload || {}- );-- this.setProperties(updated);- });- }-}diff --git a/frontend/discourse/app/models/reviewable.ts b/frontend/discourse/app/models/reviewable.tsnew file mode 100644index 00000000000..e74bd0e7e0d--- /dev/null+++ b/frontend/discourse/app/models/reviewable.ts@@ -0,0 +1,433 @@+import { tracked } from "@glimmer/tracking";+import { computed } from "@ember/object";+import { dasherize, underscore } from "@ember/string";+import { Promise } from "rsvp";+import { ajax } from "discourse/lib/ajax";+import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import { autoTrackedArray } from "discourse/lib/tracked-tools";+import RestModel, { type RestPayload } from "discourse/models/rest";+import type ReviewableHistory from "discourse/models/reviewable-history";+import type { default as Topic, TopicBasicUser } from "discourse/models/topic";+import type User from "discourse/models/user";+import I18n, { i18n } from "discourse-i18n";+import Category from "./category.ts";++export const PENDING = 0 as const;+export const APPROVED = 1 as const;+export const REJECTED = 2 as const;+export const IGNORED = 3 as const;+export const DELETED = 4 as const;++/** Whitelisted core payload keys; extensions augment this interface. */+export interface ReviewablePayload {+ raw?: string;+ title?: string;+ archetype?: string;+ category?: number | null;+ visible?: boolean;+ is_warning?: boolean;+ first_post_checks?: boolean;+ featured_link?: string | null;+ is_poll?: boolean;+ typing_duration_msecs?: number;+ composer_open_duration_msecs?: number;+ tags?: string[] | null;+ via_email?: boolean;+ raw_email?: string | null;+ username?: string;+ email?: string | null;+ name?: string | null;+ bio?: string | null;+ website?: string | null;+ avatar_url?: string | null;+ scrubbed_by?: string;+ scrubbed_reason?: string | null;+ scrubbed_at?: string;+ [key: string]: unknown;+}++/** Histories include synthetic claim events without a model id or status. */+export type ReviewableHistoryEntry =+ | ReviewableHistory+ | {+ reviewable_history_type: number;+ created_at: string;+ created_by: User;+ };++export interface ReviewableScore {+ id: number;+ score: number;+ agree_stats: { agreed: number; disagreed: number; ignored: number };+ reason?: string;+ reason_type: string | null;+ reason_data: string[] | null;+ created_at: string;+ reviewed_at: string | null;+ status: number;+ user: User | null;+ user_id?: number;+ score_type: {+ id: number;+ title: string;+ type: string;+ icon: string;+ reviewable_priority?: number;+ } | null;+ score_type_id?: number;+ reviewed_by: User | null;+ reviewed_by_id?: number | null;+ reviewable_conversation?: {+ id: number;+ permalink: string;+ has_more: boolean;+ conversation_posts: {+ id: number;+ excerpt: string;+ user: User | null;+ user_id?: number;+ }[];+ } | null;+ reviewable_conversation_id?: number | null;+}++export interface ReviewableAction {+ id: string;+ action_name: string;+ icon: string | null;+ button_class: string | null;+ label: string;+ confirm_message?: string;+ confirm_destructive?: boolean;+ description?: string;+ server_action: string | null;+ client_action?: string;+ require_reject_reason?: boolean;+ completed_message: string | null;+ penalty_effect?: string;+}++export interface ReviewableBundledAction {+ id: string;+ icon?: string;+ label?: string;+ secondary?: boolean;+ actions: ReviewableAction[];+ action_ids?: string[];+}++export interface ReviewableClaim {+ /** Only server claims carry an id; MessageBus claims are plain objects. */+ id?: number;+ automatic: boolean;+ user: User | null;+ user_id?: number;+}++export interface ReviewableNote {+ id: number;+ content: string;+ cooked: string;+ created_at: string;+ updated_at: string;+ /** Embedded basic user JSON, not a hydrated User model. */+ user: TopicBasicUser | null;+}++export interface ReviewableAuthorPenalty {+ kind: string;+ forever: boolean;+ expires_at?: string;+ reason?: string;+ applied_at: string;+ automatic: boolean;+ from_this_target: boolean;+ can_lift: boolean;+ applied_by: TopicBasicUser | null;+}++/** Extra moderation fields attached to users in review responses. */+export interface ReviewableUserFields {+ can_delete_all_posts: boolean;+ can_be_deleted: boolean;+ post_count: number;+ topic_count: number;+ ip_address?: string | null;+ email?: string | null;+ custom_fields: Record<string, unknown>;+ flags_agreed: number;+ flags_disagreed: number;+ flags_ignored: number;+ created_at: string;+ trust_level: number;+ silenced_count: number;+ suspended_count: number;+ rejected_posts_count: number;+ silenced_till?: string;+ silence_reason?: string;+ suspended_till?: string;+ suspend_reason?: string;+}++/** Hydrated fields; resolved ids disappear, unresolved ids remain beside null relations. */+export interface ReviewableFields {+ id: number;+ type: string;+ type_source: string;+ status: number;+ score: number;+ version: number;+ created_at: string;+ can_edit: boolean;+ created_from_flag: boolean;+ category_id?: number;+ topic_id?: number | null;+ post_id?: number;+ user_id?: number;+ target_id?: number | null;+ target_type: string | null;+ removed_topic_id?: number | null;+ created_by_id?: number;+ created_by: User | null;+ target_created_by_id?: number | null;+ target_created_by?: (User & ReviewableUserFields) | null;+ target_deleted_by_id?: number;+ target_deleted_by?: User | null;+ topic?: Topic | null;+ claimed_by_id?: number | null;+ claimed_by?: ReviewableClaim | null;+ target?: RestModel | null;+ post?: RestModel | null;+ user?: User | null;+ target_url?: string;+ topic_url?: string;+ target_created_at?: string | null;+ target_deleted_at?: string;+ target_created_by_trust_level: number | null;+ raw?: string;+ cooked?: string | null;+ fancy_title?: string | null;+ deleted_at?: string;+ blank_post?: boolean;+ post_updated_at?: string | null;+ post_version?: number | null;+ payload?: ReviewablePayload | null;+ author_penalties: ReviewableAuthorPenalty[];+ bundled_actions: ReviewableBundledAction[];+ bundled_action_ids?: string[];+ editable_fields: { id: string; type: string }[];+ reviewable_histories: ReviewableHistoryEntry[];+ reviewable_history_ids?: number[];+ reviewable_scores: ReviewableScore[];+ reviewable_score_ids?: number[];+ reviewable_note_ids?: number[];+ topic_tags?: { id: number; name: string; slug: string }[];+ dsa_classification?: { statement_ids: number[] };+ last_performing_username?: string | null;+ reply_count?: number;+ reply_to_post_number?: number;+ link_admin?: boolean;+ user_fields?: Record<string, string | string[]>;+ reject_reason?: string | null;+ /** Embedded JSON, unlike the side-loaded target_created_by model. */+ target_user?: TopicBasicUser & ReviewableUserFields;+ rejectReason?: string;+ sendEmail?: boolean;+}++/** Store input uses side-loaded ids; the instance interface describes hydrated records. */+export type ReviewableWireFields = Omit<+ ReviewableFields,+ | "created_by"+ | "target_created_by"+ | "target_deleted_by"+ | "topic"+ | "claimed_by"+ | "target"+ | "post"+ | "user"+ | "reviewable_histories"+ | "reviewable_scores"+ | "bundled_actions"+> & {+ created_by_id: number;+ reviewable_history_ids: number[];+ reviewable_score_ids: number[];+ bundled_action_ids: string[];+};++// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging+export default interface Reviewable extends ReviewableFields {}++// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging+export default class Reviewable extends RestModel {+ static override munge(json: RestPayload) {+ // ensure we are not overriding category computed property+ delete json.category;+ return json;+ }++ @tracked author_penalties!: ReviewableFields["author_penalties"];+ @tracked blank_post?: ReviewableFields["blank_post"];+ @tracked bundled_actions!: ReviewableFields["bundled_actions"];+ @tracked can_edit!: ReviewableFields["can_edit"];+ @tracked category_id?: ReviewableFields["category_id"];+ @tracked claimed_by?: ReviewableFields["claimed_by"];+ @tracked cooked?: ReviewableFields["cooked"];+ @tracked created_at!: ReviewableFields["created_at"];+ @tracked created_by!: ReviewableFields["created_by"];+ @tracked created_from_flag!: ReviewableFields["created_from_flag"];+ @tracked deleted_at?: ReviewableFields["deleted_at"];+ @tracked dsa_classification?: ReviewableFields["dsa_classification"];+ @tracked editable_fields!: ReviewableFields["editable_fields"];+ @tracked fancy_title?: ReviewableFields["fancy_title"];+ @tracked id!: ReviewableFields["id"];+ @tracked+ last_performing_username?: ReviewableFields["last_performing_username"];+ @tracked payload?: ReviewableFields["payload"];+ @tracked post_id?: ReviewableFields["post_id"];+ @tracked post_updated_at?: ReviewableFields["post_updated_at"];+ @tracked post_version?: ReviewableFields["post_version"];+ @tracked raw?: ReviewableFields["raw"];+ @tracked removed_topic_id?: ReviewableFields["removed_topic_id"];+ @tracked reviewable_histories!: ReviewableFields["reviewable_histories"];+ @tracked reviewable_scores!: ReviewableFields["reviewable_scores"];+ @tracked score!: ReviewableFields["score"];+ @tracked status!: ReviewableFields["status"];+ @tracked target_created_at?: ReviewableFields["target_created_at"];+ @tracked target_created_by?: ReviewableFields["target_created_by"];+ @tracked+ target_created_by_trust_level!: ReviewableFields["target_created_by_trust_level"];+ @tracked target_deleted_at?: ReviewableFields["target_deleted_at"];+ @tracked target_deleted_by?: ReviewableFields["target_deleted_by"];+ @tracked target_id?: ReviewableFields["target_id"];+ @tracked target_type!: ReviewableFields["target_type"];+ @tracked target_url?: ReviewableFields["target_url"];+ @tracked topic?: ReviewableFields["topic"];+ @tracked topic_id?: ReviewableFields["topic_id"];+ @tracked topic_tags?: ReviewableFields["topic_tags"];+ @tracked topic_url?: ReviewableFields["topic_url"];+ @tracked type!: ReviewableFields["type"];+ @tracked type_source!: ReviewableFields["type_source"];+ @tracked version!: ReviewableFields["version"];+ @autoTrackedArray reviewable_notes: ReviewableNote[] = [];++ @computed("type", "topic")+ get resolvedType() {+ // Display "Queued Topic" if the post will create a topic+ if (this.type === "ReviewableQueuedPost" && !this.topic) {+ return "ReviewableQueuedTopic";+ }++ return this.type;+ }++ @computed("resolvedType")+ get humanType(): string {+ return i18n(`review.types.${underscore(this.resolvedType)}.title`, {+ defaultValue: "",+ });+ }++ @computed("humanType")+ get humanTypeCssClass() {+ return "-" + dasherize(this.humanType);+ }++ @computed("resolvedType")+ get humanNoun(): string {+ return i18n(`review.types.${underscore(this.resolvedType)}.noun`, {+ defaultValue: "reviewable",+ });+ }++ @computed("humanNoun")+ /** Requires scores to be loaded, including each referenced score type. */+ get flaggedReviewableContextQuestion(): string {+ // TODO(typescript-pending): uniqueItemsFromArray loses its element type; remove this assertion when generic.+ const uniqueReviewableScores = uniqueItemsFromArray(+ this.reviewable_scores,+ "score_type.type"+ ) as ReviewableScore[];++ if (uniqueReviewableScores.length === 1) {+ if (uniqueReviewableScores[0].score_type!.type === "notify_moderators") {+ return i18n("review.context_question.something_else_wrong", {+ reviewable_type: this.humanNoun,+ });+ }+ }++ const listOfQuestions = I18n.listJoiner(+ uniqueItemsFromArray(+ uniqueReviewableScores.map((score) =>+ score.score_type!.title.toLowerCase()+ )+ ) as string[],+ i18n("review.context_question.delimiter")+ );++ return i18n("review.context_question.is_this_post", {+ reviewable_human_score_types: listOfQuestions,+ reviewable_type: this.humanNoun,+ });+ }++ @computed("resolvedType", "reviewable_scores", "status")+ get userReviewableContextQuestion(): string | null {+ if (this.resolvedType === "ReviewableUser") {+ // in this case the only remaining action is "scrub record" so the question shouldn't show+ if (this.status !== PENDING) {+ return null;+ }+ const isSuspectUser = this.reviewable_scores?.some(+ (score) => score.reason_type === "suspect_user"+ );+ if (isSuspectUser) {+ return i18n("review.context_question.suspect_user");+ }+ return i18n("review.context_question.approve_user");+ }+ if (this.resolvedType === "ReviewableQueuedPost") {+ return i18n("review.context_question.approve_post");+ }+ if (this.resolvedType === "ReviewableQueuedTopic") {+ return i18n("review.context_question.approve_topic");+ }+ if (this.resolvedType === "ReviewablePost") {+ return i18n("review.context_question.approve_post");+ }+ return null;+ }++ @computed("category_id")+ get category() {+ return Category.findById(this.category_id);+ }++ /** Keeps the override assignable to RestModel; resolves without a save-result envelope. */+ override update(this: never, ...args: never[]): never;+ override update(updates: object): globalThis.Promise<void>;+ override update(updates: object): globalThis.Promise<void> {+ // If no changes, do nothing+ if (Object.keys(updates).length === 0) {+ return Promise.resolve();+ }++ // eslint-disable-next-line prefer-const+ let adapter = this.store.adapterFor("reviewable");+ // TODO(typescript-pending): ajax has no endpoint response types; remove the callback annotation when generic.+ return ajax(+ `/review/${this.id}?version=${this.version}`,+ adapter.getPayload("PUT", { reviewable: updates })+ ).then((updated: Partial<ReviewableFields>) => {+ updated.payload = Object.assign(+ {},+ this.payload || {},+ updated.payload || {}+ );++ this.setProperties(updated);+ });+ }+}diff --git a/frontend/discourse/app/models/user-menu-reviewable.js b/frontend/discourse/app/models/user-menu-reviewable.jsdeleted file mode 100644index 5feeb5a8262..00000000000--- a/frontend/discourse/app/models/user-menu-reviewable.js+++ /dev/null@@ -1,6 +0,0 @@-import { tracked } from "@glimmer/tracking";-import RestModel from "discourse/models/rest";--export default class UserMenuReviewable extends RestModel {- @tracked pending;-}diff --git a/frontend/discourse/app/models/user-menu-reviewable.ts b/frontend/discourse/app/models/user-menu-reviewable.tsnew file mode 100644index 00000000000..90a4bc9f5fe--- /dev/null+++ b/frontend/discourse/app/models/user-menu-reviewable.ts@@ -0,0 +1,24 @@+import { tracked } from "@glimmer/tracking";+import RestModel from "discourse/models/rest";++/** Basic serializer shape, also used as the fallback for extension types. */+export interface UserMenuReviewableFields {+ id: number;+ type: string;+ created_at: string;+ flagger_username: string | null;+ /** Present only on the corresponding core basic serializer. */+ post_number?: number;+ topic_fancy_title?: string;+ is_new_topic?: boolean;+ payload_title?: string;+ username?: string;+}++// eslint-disable-next-line @typescript-eslint/no-empty-object-type, @typescript-eslint/no-unsafe-declaration-merging+export default interface UserMenuReviewable extends UserMenuReviewableFields {}++// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging+export default class UserMenuReviewable extends RestModel {+ @tracked pending!: boolean;+}diff --git a/frontend/discourse/app/services/store.ts b/frontend/discourse/app/services/store.tsindex b6a57cdccbb..bb3beb9f14b 100644--- a/frontend/discourse/app/services/store.ts+++ b/frontend/discourse/app/services/store.ts@@ -13,6 +13,7 @@ import type Category from "discourse/models/category";import type Composer from "discourse/models/composer";import type Group from "discourse/models/group";import type NavItem from "discourse/models/nav-item";+import type Notification from "discourse/models/notification";import type PendingPost from "discourse/models/pending-post";import type { default as Post, PostCreateAttrs } from "discourse/models/post";import type PostStream from "discourse/models/post-stream";@@ -25,6 +26,7 @@ import RestModel, {type RestPayload,} from "discourse/models/rest";import ResultSet from "discourse/models/result-set";+import type Reviewable from "discourse/models/reviewable";import type Site from "discourse/models/site";import type {default as Topic,@@ -42,10 +44,12 @@ export interface ModelRegistry {composer: Composer;group: Group;"nav-item": NavItem;+ notification: Notification;"pending-post": PendingPost;post: Post;"post-stream": PostStream;"published-page": PublishedPage;+ reviewable: Reviewable;site: Site;topic: Topic;"topic-list": TopicList;diff --git a/frontend/discourse/type-tests/models/notification-review-invite-test.ts b/frontend/discourse/type-tests/models/notification-review-invite-test.tsnew file mode 100644index 00000000000..33bbab9b18a--- /dev/null+++ b/frontend/discourse/type-tests/models/notification-review-invite-test.ts@@ -0,0 +1,239 @@+import type EmberObject from "@ember/object";+import { expectTypeOf } from "expect-type";+import type Category from "discourse/models/category";+import Invite, {+ type InviteCreateAttrs,+ type Invited,+} from "discourse/models/invite";+import Notification, {+ type NotificationData,+} from "discourse/models/notification";+import type RestModel from "discourse/models/rest";+import Reviewable, {+ APPROVED,+ DELETED,+ IGNORED,+ PENDING,+ REJECTED,+ type ReviewableClaim,+ type ReviewableFields,+ type ReviewableHistoryEntry,+ type ReviewablePayload,+ type ReviewableScore,+ type ReviewableWireFields,+} from "discourse/models/reviewable";+import type ReviewableHistory from "discourse/models/reviewable-history";+import type Topic from "discourse/models/topic";+import type User from "discourse/models/user";+import UserMenuReviewable from "discourse/models/user-menu-reviewable";+import type {+ default as StoreService,+ ModelFor,+ ResultSetOf,+} from "discourse/services/store";++declare const store: StoreService;+declare const user: User;++/* Notification: `/notifications`, user-menu lists and the notification bus. */++expectTypeOf<ModelFor<"notification">>().toEqualTypeOf<Notification>();+declare const notification: Notification;+expectTypeOf(notification).toExtend<RestModel>();+expectTypeOf(notification.id).toEqualTypeOf<number>();+expectTypeOf(notification.user_id).toEqualTypeOf<number>();+expectTypeOf(notification.notification_type).toEqualTypeOf<number>();+expectTypeOf(notification.read).toEqualTypeOf<boolean>();+expectTypeOf(notification.high_priority).toEqualTypeOf<boolean>();+expectTypeOf(notification.created_at).toEqualTypeOf<string>();+// Badge, group and admin notifications have no topic.+expectTypeOf(notification.topic_id).toEqualTypeOf<number | null>();+expectTypeOf(notification.post_number).toEqualTypeOf<number | null>();+expectTypeOf(notification.slug).toEqualTypeOf<string | null>();+expectTypeOf(notification.fancy_title).toEqualTypeOf<string | undefined>();+// Sent only when true.+expectTypeOf(notification.is_warning).toEqualTypeOf<boolean | undefined>();+// The data packet depends on the notification type and on plugins.+expectTypeOf(notification.data.display_username).toEqualTypeOf<+ string | undefined+>();+expectTypeOf(notification.data.topic_title).toEqualTypeOf<string | undefined>();+expectTypeOf(notification.data.revision_number).toEqualTypeOf<+ number | null | undefined+>();+expectTypeOf(notification.data.badge_id).toEqualTypeOf<number | undefined>();+expectTypeOf(notification.data["plugin_key"]).toEqualTypeOf<unknown>();+notification.read = true;+expectTypeOf(Notification.initializeNotifications([])).toEqualTypeOf<+ Promise<Notification[]>+>();+expectTypeOf(Notification.applyTransformations([notification])).toEqualTypeOf<+ Promise<void>+>();+expectTypeOf(+ store.find("notification", { username: "sam", limit: 30 })+).resolves.toEqualTypeOf<ResultSetOf<Notification> | undefined>();++/* UserMenuReviewable: the basic reviewable list in the user menu. */++const menuReviewable = UserMenuReviewable.create({+ id: 1,+ type: "ReviewableFlaggedPost",+ pending: true,+ created_at: "2026-10-27T23:51:37.081Z",+ flagger_username: "sam",+});+expectTypeOf(menuReviewable.id).toEqualTypeOf<number>();+expectTypeOf(menuReviewable.type).toEqualTypeOf<string>();+expectTypeOf(menuReviewable.pending).toEqualTypeOf<boolean>();+expectTypeOf(menuReviewable.created_at).toEqualTypeOf<string>();+// A deleted flagger serializes as null.+expectTypeOf(menuReviewable.flagger_username).toEqualTypeOf<string | null>();+// Each core type adds its own fields.+expectTypeOf(menuReviewable.post_number).toEqualTypeOf<number | undefined>();+expectTypeOf(menuReviewable.topic_fancy_title).toEqualTypeOf<+ string | undefined+>();+expectTypeOf(menuReviewable.is_new_topic).toEqualTypeOf<boolean | undefined>();+expectTypeOf(menuReviewable.payload_title).toEqualTypeOf<string | undefined>();+expectTypeOf(menuReviewable.username).toEqualTypeOf<string | undefined>();++/* Reviewable: the review queue and show page. */++expectTypeOf(PENDING).toEqualTypeOf<0>();+expectTypeOf(APPROVED).toEqualTypeOf<1>();+expectTypeOf(REJECTED).toEqualTypeOf<2>();+expectTypeOf(IGNORED).toEqualTypeOf<3>();+expectTypeOf(DELETED).toEqualTypeOf<4>();+expectTypeOf<ModelFor<"reviewable">>().toEqualTypeOf<Reviewable>();+expectTypeOf(store.find("reviewable", 1)).resolves.toEqualTypeOf<Reviewable>();+expectTypeOf(+ store.findAll("reviewable", { status: "pending", type: "ReviewableUser" })+).resolves.toEqualTypeOf<ResultSetOf<Reviewable> | undefined>();+declare const reviewable: Reviewable;+expectTypeOf(reviewable.id).toEqualTypeOf<number>();+expectTypeOf(reviewable.type).toEqualTypeOf<string>();+expectTypeOf(reviewable.status).toEqualTypeOf<number>();+expectTypeOf(reviewable.score).toEqualTypeOf<number>();+expectTypeOf(reviewable.version).toEqualTypeOf<number>();+expectTypeOf(reviewable.can_edit).toEqualTypeOf<boolean>();+expectTypeOf(reviewable.created_from_flag).toEqualTypeOf<boolean>();+// The store swaps side-loaded ids for records, or null when a record is missing.+expectTypeOf(reviewable.created_by).toEqualTypeOf<User | null>();+expectTypeOf(reviewable.topic).toEqualTypeOf<Topic | null | undefined>();+const history = reviewable.reviewable_histories[0];+expectTypeOf(history.reviewable_history_type).toEqualTypeOf<number>();+expectTypeOf(history.created_at).toEqualTypeOf<string>();+// Claiming appends a client-side entry that is not a model instance.+reviewable.reviewable_histories = [+ ...reviewable.reviewable_histories,+ {+ reviewable_history_type: 3,+ created_at: "2026-10-27T23:51:37.081Z",+ created_by: user,+ },+];+declare const serverHistory: ReviewableHistory;+reviewable.reviewable_histories = [serverHistory];+expectTypeOf(reviewable.category).toEqualTypeOf<Category | undefined>();+expectTypeOf(reviewable.resolvedType).toEqualTypeOf<string>();+expectTypeOf(reviewable.humanType).toEqualTypeOf<string>();+expectTypeOf(reviewable.userReviewableContextQuestion).toEqualTypeOf<+ string | null+>();+// Queued posts carry their composer state in a whitelisted payload.+expectTypeOf(reviewable.payload).not.toBeAny();+reviewable.last_performing_username = null;+expectTypeOf(reviewable.update({ payload: { raw: "Edited" } })).toExtend<+ PromiseLike<void>+>();++/* Invite: `/u/:username/invited.json` and the invite modals. */++const invite = Invite.create();+expectTypeOf(invite).toEqualTypeOf<Invite>();+expectTypeOf(invite).toExtend<EmberObject>();+// Pending entries.+expectTypeOf(invite.id).toEqualTypeOf<number | undefined>();+expectTypeOf(invite.invite_key).toEqualTypeOf<string | undefined>();+expectTypeOf(invite.email).toEqualTypeOf<string | null | undefined>();+expectTypeOf(invite.domain).toEqualTypeOf<string | null | undefined>();+expectTypeOf(invite.expired).toEqualTypeOf<boolean | undefined>();+// Redeemed entries.+expectTypeOf(invite.redeemed_at).toEqualTypeOf<string | undefined>();+expectTypeOf(invite.user).toEqualTypeOf<User | undefined>();+expectTypeOf(invite.groupIds).toEqualTypeOf<number[]>();+expectTypeOf(invite.topic).toEqualTypeOf<Topic | null>();+expectTypeOf(invite.topicId).toEqualTypeOf<number | undefined>();+invite.topicId = 5;+invite.save({ email: "[email protected]", topic_id: 5 });+invite.destroy();+invite.reinvite();+declare const invited: Awaited<ReturnType<typeof Invite.findInvitedBy>>;+Invite.findInvitedBy(user, "pending");+expectTypeOf(invited?.invites).toEqualTypeOf<Invite[] | undefined>();+expectTypeOf(invited?.can_see_invite_details).toEqualTypeOf<+ boolean | undefined+>();+expectTypeOf(invited?.counts.redeemed).toEqualTypeOf<number | undefined>();+Invite.findInvitedBy(user, "pending", "term", 30);+Invite.destroyAllExpired(user);+Invite.reinviteAll();++/* Registry spellings, open packets and wire shapes. */++expectTypeOf<ModelFor<"Notification">>().toEqualTypeOf<Notification>();+expectTypeOf<ModelFor<"Reviewable">>().toEqualTypeOf<Reviewable>();+expectTypeOf<NotificationData["custom_key"]>().toBeUnknown();+// Plugin-only top-level fields stay out of core.+expectTypeOf<Notification>().not.toHaveProperty("topic_bumped_at");+expectTypeOf<ReviewableFields>().not.toHaveProperty("chat_channel");+// munge strips `category` so the getter wins.+expectTypeOf<ReviewableFields>().not.toHaveProperty("category");+expectTypeOf<ReviewablePayload["custom_key"]>().toBeUnknown();+expectTypeOf<ReviewablePayload["tags"]>().toEqualTypeOf<+ string[] | null | undefined+>();+expectTypeOf(reviewable.claimed_by).toEqualTypeOf<+ ReviewableClaim | null | undefined+>();+// Claims arriving over the message bus are plain objects.+reviewable.claimed_by = { user, automatic: false };+reviewable.claimed_by = null;+expectTypeOf<ReviewableWireFields["created_by_id"]>().toEqualTypeOf<number>();+expectTypeOf<ReviewableWireFields>().not.toHaveProperty("created_by");+expectTypeOf<ReviewableScore["score_type"]>().toBeNullable();+expectTypeOf<ReviewableHistoryEntry>().not.toExtend<EmberObject>();+expectTypeOf(+ reviewable.update({ payload: { raw: "Edited", extra: true } })+).resolves.toBeVoid();+// update reads the keys of its argument, so it needs one.+// @ts-expect-error updates are required+reviewable.update();++const genericMenuItem = UserMenuReviewable.create({+ id: 1,+ type: "ExtensionType",+ pending: true,+ created_at: "2026-10-27T23:51:37.081Z",+ flagger_username: null,+});+expectTypeOf(genericMenuItem.type).toEqualTypeOf<string>();++const pending = Invite.create({ email: null, domain: null, topics: [] });+const redeemed = Invite.create({+ redeemed_at: "2026-10-27T23:51:37.081Z",+ user: { id: 1, username: "sam", name: null, avatar_template: "/avatar.png" },+});+expectTypeOf(redeemed.user).toEqualTypeOf<User | undefined>();+expectTypeOf(pending.shortKey).toEqualTypeOf<string>();+expectTypeOf(pending.destroy()).resolves.toBeBoolean();+expectTypeOf<Invited>().toExtend<EmberObject>();+expectTypeOf<InviteCreateAttrs>().not.toBeAny();++class ExtendedInvite extends Invite {+ declare extension_field: string;+}+expectTypeOf(+ ExtendedInvite.create({ extension_field: "value" })+).toEqualTypeOf<ExtendedInvite>();