A platform for community discussion. Free, open, simple.
FIX: Keep missing categories from breaking selectors and board actions (#43770)
Régis Hanolc6bec61f0967
diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.jsindex a935a8742e0..2f6b0a9a43a 100644--- a/frontend/discourse/app/models/category.js+++ b/frontend/discourse/app/models/category.js@@ -29,6 +29,7 @@ import Topic from "./topic";const CATEGORY_ASYNC_SEARCH_CACHE = {};const CATEGORY_ASYNC_HIERARCHICAL_SEARCH_CACHE = {};+const HTTP_NOT_FOUND = 404;let _uncategorized;@@ -140,14 +141,7 @@ export default class Category extends RestModel {}static findByIds(ids = []) {- const categories = [];- ids.forEach((id) => {- const found = Category.findById(id);- if (found) {- categories.push(found);- }- });- return categories;+ return ids.map((id) => Category.findById(id)).filter(Boolean);}static hasAsyncFoundAll(ids) {@@ -157,8 +151,9 @@ export default class Category extends RestModel {static async asyncFindByIds(ids = []) {ids = ids.map((x) => parseInt(x, 10));+ const site = Site.current();- if (!Site.current().lazy_load_categories || this.hasAsyncFoundAll(ids)) {+ if (!site.lazy_load_categories || this.hasAsyncFoundAll(ids)) {return this.findByIds(ids);}@@ -172,16 +167,19 @@ export default class Category extends RestModel {);}- const categories = ids.map((id) =>- Site.current().updateCategory(result.get(id))- );-- // Update loadedCategoryIds list- const loadedCategoryIds = Site.current().loadedCategoryIds || new Set();- ids.forEach((id) => loadedCategoryIds.add(id));- Site.current().set("loadedCategoryIds", loadedCategoryIds);+ const loadedCategoryIds = site.loadedCategoryIds || new Set();+ for (const id of ids) {+ const category = result.get(id);+ if (category) {+ site.updateCategory(category);+ } else {+ site.removeCategory(id);+ }+ loadedCategoryIds.add(id);+ }+ site.set("loadedCategoryIds", loadedCategoryIds);- return categories;+ return this.findByIds(ids);}static async asyncFindById(id) {@@ -990,11 +988,16 @@ export default class Category extends RestModel {}const categoryMultiCache = new MultiCache(async (ids) => {- const result = await ajax("/categories/find", { data: { ids } });+ try {+ const { categories } = await ajax("/categories/find", { data: { ids } });+ return new Map(categories.map((category) => [category.id, category]));+ } catch (error) {+ if (error.jqXHR?.status === HTTP_NOT_FOUND) {+ return new Map();+ }- return new Map(- result["categories"].map((category) => [category.id, category])- );+ throw error;+ }});export function resetCategoryCache() {diff --git a/frontend/discourse/tests/unit/models/category-test.js b/frontend/discourse/tests/unit/models/category-test.jsindex 8e7fc262a27..24e87c28f4c 100644--- a/frontend/discourse/tests/unit/models/category-test.js+++ b/frontend/discourse/tests/unit/models/category-test.js@@ -540,6 +540,63 @@ module("Unit | Model | category", function (hooks) {stub.restore();});+ test("asyncFindByIds preserves request order and skips missing categories", async function (assert) {+ const missingId = 12345;+ const categoryIds = [12346, 12347];+ const site = this.owner.lookup("service:site");+ site.set("lazy_load_categories", true);+ site.updateCategory({ id: missingId, name: "Stale category" });+ pretender.get("/categories/find", () =>+ response({+ categories: categoryIds.map((id) => ({ id, name: `Category ${id}` })),+ })+ );++ const ids = [missingId, ...categoryIds.toReversed()];+ const categories = await Category.asyncFindByIds(ids);+ assert.deepEqual(+ categories.map((category) => category.id),+ categoryIds.toReversed(),+ "available categories keep their requested order"+ );+ assert.deepEqual(+ (await Category.asyncFindByIds(ids)).map((category) => category.id),+ categoryIds.toReversed(),+ "cached results match"+ );+ });++ test("asyncFindByIds caches entirely missing categories", async function (assert) {+ const notFoundStatus = 404;+ const missingId = 12345;+ this.owner.lookup("service:site").set("lazy_load_categories", true);+ const request = sinon.spy(() => response(notFoundStatus, {}));+ pretender.get("/categories/find", request);++ assert.deepEqual(+ await Category.asyncFindByIds([missingId]),+ [],+ "missing categories are omitted"+ );+ assert.strictEqual(+ await Category.asyncFindById(missingId),+ undefined,+ "single lookup returns undefined"+ );+ assert.true(request.calledOnce, "missing IDs are cached");+ });++ test("asyncFindByIds propagates server errors", async function (assert) {+ const serverErrorStatus = 500;+ this.owner.lookup("service:site").set("lazy_load_categories", true);+ pretender.get("/categories/find", () => response(serverErrorStatus, {}));++ await assert.rejects(+ Category.asyncFindByIds([12345]),+ "server errors are not treated as missing categories"+ );+ });+test("registerCategorySaveProperty includes property in save request", async function (assert) {const done = assert.async();diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjsindex a163f1a4259..3d92d212d7b 100644--- a/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs+++ b/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs@@ -453,11 +453,7 @@ export default class BoardsBoardViewer extends Component {col.copy({ cards: [...col.cards] }));- this.columns = this.columns.map((col) =>- col.copy({- cards: col.cards.filter((c) => c.id !== cardId),- })- );+ this.#handleCardDeleted(cardId);try {await ajax(`/boards/api/boards/${this.board.id}/cards/${cardId}`, {@@ -609,6 +605,11 @@ export default class BoardsBoardViewer extends Component {if (categoryId) {try {opts.category = await Category.asyncFindById(categoryId);+ if (!opts.category) {+ this._cleanupPromotion();+ this.dialog.alert(i18n("boards.board.errors.category_unavailable"));+ return;+ }} catch (error) {this._cleanupPromotion();popupAjaxError(error);@@ -885,18 +886,7 @@ export default class BoardsBoardViewer extends Component {return;}- card = Card.create(card);- this.columns = this.columns.map((col) => {- if (col.id === card.column_id) {- return col.copy({- cards: sortCardsForColumn(col, [- ...col.cards.filter((c) => c.id !== card.id),- card,- ]),- });- }- return col;- });+ this.#appendCardToColumn(card, card.column_id);}#handleCardUpdated(card) {diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjsindex 8b4bd11afe0..3faf5b61740 100644--- a/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs@@ -2,34 +2,17 @@ import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { fn } from "@ember/helper";import { action } from "@ember/object";-import { eq, not } from "discourse/truth-helpers";+import { eq, includes, not } from "discourse/truth-helpers";import DAsyncContent from "discourse/ui-kit/d-async-content";import DButton from "discourse/ui-kit/d-button";import DModal from "discourse/ui-kit/d-modal";import { i18n } from "discourse-i18n";import { loadCategories } from "../../lib/boards-categories";-function includes(arr, item) {- return arr.includes(item);-}-export default class BoardsConstraintFix extends Component {@tracked selectedCategoryId = null;@tracked selectedTagNames = [];- constructor() {- super(...arguments);- const { mismatches, topic } = this.args.model;-- if (mismatches.needsCategory && mismatches.boardCategoryIds.length === 1) {- this.selectedCategoryId = mismatches.boardCategoryIds[0];- }-- if (!mismatches.needsCategory) {- this.selectedCategoryId = topic.category_id;- }- }-get canSave() {const { mismatches } = this.args.model;if (mismatches.needsCategory && !this.selectedCategoryId) {@@ -41,6 +24,16 @@ export default class BoardsConstraintFix extends Component {return true;}+ @action+ async loadCategoryOptions(ids) {+ const categories = await loadCategories(ids);+ if (!this.isDestroying && ids.length === 1) {+ this.selectedCategoryId = categories[0]?.id ?? null;+ }++ return categories;+ }+@actionselectCategory(categoryId) {this.selectedCategoryId = categoryId;@@ -59,6 +52,10 @@ export default class BoardsConstraintFix extends Component {@actionconfirm() {+ if (!this.canSave) {+ return;+ }+const result = {};const { mismatches } = this.args.model;@@ -95,7 +92,7 @@ export default class BoardsConstraintFix extends Component {<label>{{i18n "boards.board.constraint_fix_category"}}</label><div class="discourse-boards-constraint-fix__options"><DAsyncContent- @asyncData={{loadCategories}}+ @asyncData={{this.loadCategoryOptions}}@context={{@model.mismatches.boardCategoryIds}}><:content as |categories|>diff --git a/plugins/boards/config/locales/client.en.yml b/plugins/boards/config/locales/client.en.ymlindex 325c6f52501..0a5a9612bf1 100644--- a/plugins/boards/config/locales/client.en.yml+++ b/plugins/boards/config/locales/client.en.yml@@ -130,6 +130,7 @@ en:created_by: "Created by"show_older_cards: "Show %{count} older cards"errors:+ category_unavailable: "The destination category is no longer available. Update the board or column settings before creating a topic."acl_update_failed: "Failed to update board permissions."acl_create_failed: "Failed to create board permissions."manage:diff --git a/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs b/plugins/boards/test/javascripts/components/boards-category-loading-test.gjsindex 87dae8eff35..3fb655e5bd0 100644--- a/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs+++ b/plugins/boards/test/javascripts/components/boards-category-loading-test.gjs@@ -16,6 +16,9 @@ import BoardsTopicCardDetail from "discourse/plugins/boards/discourse/componentsimport BoardsFabricators from "discourse/plugins/boards/discourse/lib/fabricators";import Board from "discourse/plugins/boards/discourse/models/board";+const HTTP_NOT_FOUND = 404;+const CONFIRM_BUTTON =+ ".discourse-boards-constraint-fix-modal .d-modal__footer .btn-primary";const CATEGORY_ID = 12345;const CATEGORY_NAME = "Unvisited category";const ADDITIONAL_CATEGORY_ID = 12346;@@ -94,7 +97,9 @@ module("Integration | Component | Boards category loading", function (hooks) {this.site.updateCategory(category);}+ const onConfirm = sinon.spy();this.constraintModel = {+ onConfirm,topic: { category_id: 1 },mismatches: {needsCategory: true,@@ -103,27 +108,79 @@ module("Integration | Component | Boards category loading", function (hooks) {};await render(<template>- <BoardsConstraintFix @model={{this.constraintModel}} />+ <BoardsConstraintFix+ @closeModal={{this.closeModal}}+ @model={{this.constraintModel}}+ /></template>);assert.dom(`[data-category-id="${CATEGORY_ID}"]`).hasText(CATEGORY_NAME);+ assert+ .dom(CONFIRM_BUTTON)+ .isEnabled("the loaded category can be confirmed");++ await click(CONFIRM_BUTTON);++ assert.deepEqual(+ onConfirm.args,+ [[{ category_id: CATEGORY_ID }]],+ "confirmation uses the loaded category"+ );});}- test("a category omitted by the server does not prevent loading the board", async function (assert) {+ test("a missing category cannot be confirmed in the constraint dialog", async function (assert) {+ pretender.get("/categories/find", () =>+ response(HTTP_NOT_FOUND, { errors: ["Not found"] })+ );+ this.constraintModel = {+ topic: { category_id: 1 },+ mismatches: {+ needsCategory: true,+ boardCategoryIds: [CATEGORY_ID],+ },+ };++ await render(+ <template>+ <BoardsConstraintFix+ @closeModal={{this.closeModal}}+ @model={{this.constraintModel}}+ />+ </template>+ );++ assert+ .dom("[data-category-id]")+ .doesNotExist("the missing category is not offered");+ assert+ .dom(CONFIRM_BUTTON)+ .isDisabled("confirmation requires an available category");+ });++ test("a partial category response keeps the settings selector available", async function (assert) {this.board.category_ids = [CATEGORY_ID, ADDITIONAL_CATEGORY_ID];pretender.get("/categories/find", () =>response({ categories: [category] }));- const payload = await Board.createPayload(this.model);+ this.settingsModel.board = (await Board.createPayload(this.model)).board;- assert.strictEqual(- payload.board.id,- this.board.id,- "the board remains available"+ await render(+ <template>+ <BoardsBoardSettings+ @closeModal={{this.closeModal}}+ @inline={{true}}+ @model={{this.settingsModel}}+ />+ </template>);++ assert+ .dom(".category-selector")+ .exists("the category selector remains available")+ .includesText(CATEGORY_NAME, "the accessible category remains selected");});test("boards list displays category constraints", async function (assert) {@@ -198,37 +255,53 @@ module("Integration | Component | Boards category loading", function (hooks) {});for (const source of ["board", "column"]) {- test(`promoting a floater passes the ${source} category to the composer`, async function (assert) {- const card = this.fabricators.card({- board_id: this.board.id,- column_id: this.column.id,- });- this.column.cards = [card];-- if (source === "column") {- this.board.category_ids = [];- this.column.move_to_category_id = CATEGORY_ID;- }+ test.each(+ `promoting a floater with a ${source} category`,+ {+ available: { categoryIds: [CATEGORY_ID], alerts: 0 },+ missing: { categoryIds: [], alerts: 1 },+ },+ async function (assert, expected) {+ const alert = sinon.stub(this.owner.lookup("service:dialog"), "alert");+ if (!expected.categoryIds.length) {+ pretender.get("/categories/find", () => response(HTTP_NOT_FOUND, {}));+ }- const openNewTopic = sinon.stub().resolves();- this.owner.register(- "service:composer",- class extends Service {- openNewTopic = openNewTopic;+ this.column.cards = [+ this.fabricators.card({+ board_id: this.board.id,+ column_id: this.column.id,+ }),+ ];+ if (source === "column") {+ this.board.category_ids = [];+ this.column.move_to_category_id = CATEGORY_ID;}- );- await render(- <template><BoardsBoardViewer @model={{this.model}} /></template>- );- await click(".discourse-boards-card__actions-trigger");- await click(".fk-d-menu button:has(.d-icon-plus)");-- assert.true(openNewTopic.calledOnce, "the composer opens");- assert.strictEqual(- openNewTopic.firstCall.args[0].category?.id,- CATEGORY_ID,- "the composer receives the intended category"- );- });++ const openNewTopic = sinon.stub().resolves();+ this.owner.register(+ "service:composer",+ class extends Service {+ openNewTopic = openNewTopic;+ }+ );+ await render(+ <template><BoardsBoardViewer @model={{this.model}} /></template>+ );+ await click(".discourse-boards-card__actions-trigger");+ await click(".fk-d-menu button:has(.d-icon-plus)");++ assert.deepEqual(+ openNewTopic.args.map(([options]) => options.category?.id),+ expected.categoryIds,+ "only an available category is passed to the composer"+ );+ assert.strictEqual(+ alert.callCount,+ expected.alerts,+ "missing categories are reported"+ );+ }+ );}});