Skip to content

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

DEV: Move discourse-kanban into core as boards (#43056)

Martin Brennan1d7ede721651
diff --git a/.github/labeler.yml b/.github/labeler.yml
index e126e97832e..94378bba654 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -1,3 +1,7 @@
+boards:
+ - changed-files:
+ - any-glob-to-any-file: plugins/boards/**/*
+
chat:
- changed-files:
- any-glob-to-any-file: plugins/chat/**/*
diff --git a/.gitignore b/.gitignore
index eb6116be9e0..f5d2318f66e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,6 +36,7 @@
!/plugins/discourse-lazy-videos
!/plugins/automation
/plugins/automation/gems
+!/plugins/boards
!/plugins/chat
!/plugins/poll
!/plugins/styleguide
diff --git a/config/official_plugins.json b/config/official_plugins.json
index 45b2930ebc0..0e90ffe04c2 100644
--- a/config/official_plugins.json
+++ b/config/official_plugins.json
@@ -73,6 +73,7 @@
"discourse-zoom",
"discourse-rewind",
"automation",
+ "boards",
"chat",
"checklist",
"docker_manager",
diff --git a/db/structure.sql b/db/structure.sql
index db4ef82a16e..9676afd53d0 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -4230,6 +4230,203 @@ CREATE SEQUENCE public.discourse_calendar_post_event_dates_id_seq
ALTER SEQUENCE public.discourse_calendar_post_event_dates_id_seq OWNED BY public.discourse_calendar_post_event_dates.id;
+--
+-- Name: discourse_kanban_board_histories; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_kanban_board_histories (
+ id bigint NOT NULL,
+ acting_user_id bigint NOT NULL,
+ action integer NOT NULL,
+ board_id bigint NOT NULL,
+ column_id bigint,
+ details jsonb,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_kanban_board_histories_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_kanban_board_histories_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_kanban_board_histories_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_kanban_board_histories_id_seq OWNED BY public.discourse_kanban_board_histories.id;
+
+
+--
+-- Name: discourse_kanban_boards; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_kanban_boards (
+ id bigint NOT NULL,
+ name character varying NOT NULL,
+ slug character varying NOT NULL,
+ allow_read_group_ids integer[] DEFAULT '{}'::integer[] NOT NULL,
+ allow_write_group_ids integer[] DEFAULT '{}'::integer[] NOT NULL,
+ require_confirmation boolean DEFAULT true NOT NULL,
+ show_tags boolean DEFAULT false NOT NULL,
+ card_style integer DEFAULT 0 NOT NULL,
+ show_topic_thumbnail boolean DEFAULT false NOT NULL,
+ created_by_id bigint,
+ updated_by_id bigint,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL,
+ category_ids integer[] DEFAULT '{}'::integer[] NOT NULL,
+ tag_ids integer[] DEFAULT '{}'::integer[] NOT NULL
+);
+
+
+--
+-- Name: discourse_kanban_boards_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_kanban_boards_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_kanban_boards_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_kanban_boards_id_seq OWNED BY public.discourse_kanban_boards.id;
+
+
+--
+-- Name: discourse_kanban_card_histories; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_kanban_card_histories (
+ id bigint NOT NULL,
+ acting_user_id bigint NOT NULL,
+ action integer NOT NULL,
+ board_id bigint NOT NULL,
+ card_id bigint NOT NULL,
+ details jsonb,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_kanban_card_histories_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_kanban_card_histories_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_kanban_card_histories_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_kanban_card_histories_id_seq OWNED BY public.discourse_kanban_card_histories.id;
+
+
+--
+-- Name: discourse_kanban_cards; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_kanban_cards (
+ id bigint NOT NULL,
+ board_id bigint NOT NULL,
+ column_id bigint,
+ topic_id bigint,
+ card_type integer DEFAULT 0 NOT NULL,
+ title character varying,
+ notes text,
+ due_at timestamp(6) without time zone,
+ "position" bigint DEFAULT 0 NOT NULL,
+ created_by_id bigint,
+ updated_by_id bigint,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL,
+ assigned_to_id bigint,
+ assigned_to_type character varying,
+ tag_ids integer[] DEFAULT '{}'::integer[] NOT NULL,
+ column_changed_at timestamp(6) without time zone NOT NULL,
+ inline_onebox_data jsonb
+);
+
+
+--
+-- Name: discourse_kanban_cards_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_kanban_cards_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_kanban_cards_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_kanban_cards_id_seq OWNED BY public.discourse_kanban_cards.id;
+
+
+--
+-- Name: discourse_kanban_columns; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_kanban_columns (
+ id bigint NOT NULL,
+ board_id bigint NOT NULL,
+ title character varying NOT NULL,
+ icon character varying,
+ "position" integer DEFAULT 0 NOT NULL,
+ move_to_category_id bigint,
+ move_to_assigned character varying,
+ move_to_status character varying,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL,
+ tag_id integer,
+ default_sort integer DEFAULT 0 NOT NULL,
+ color character varying
+);
+
+
+--
+-- Name: discourse_kanban_columns_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_kanban_columns_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_kanban_columns_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_kanban_columns_id_seq OWNED BY public.discourse_kanban_columns.id;
+
+
--
-- Name: discourse_post_event_events; Type: TABLE; Schema: public; Owner: -
--
@@ -13594,6 +13791,41 @@ ALTER TABLE ONLY public.discourse_calendar_disabled_holidays ALTER COLUMN id SET
ALTER TABLE ONLY public.discourse_calendar_post_event_dates ALTER COLUMN id SET DEFAULT nextval('public.discourse_calendar_post_event_dates_id_seq'::regclass);
+--
+-- Name: discourse_kanban_board_histories id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_board_histories ALTER COLUMN id SET DEFAULT nextval('public.discourse_kanban_board_histories_id_seq'::regclass);
+
+
+--
+-- Name: discourse_kanban_boards id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_boards ALTER COLUMN id SET DEFAULT nextval('public.discourse_kanban_boards_id_seq'::regclass);
+
+
+--
+-- Name: discourse_kanban_card_histories id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_card_histories ALTER COLUMN id SET DEFAULT nextval('public.discourse_kanban_card_histories_id_seq'::regclass);
+
+
+--
+-- Name: discourse_kanban_cards id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_cards ALTER COLUMN id SET DEFAULT nextval('public.discourse_kanban_cards_id_seq'::regclass);
+
+
+--
+-- Name: discourse_kanban_columns id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_columns ALTER COLUMN id SET DEFAULT nextval('public.discourse_kanban_columns_id_seq'::regclass);
+
+
--
-- Name: discourse_post_event_events id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -16037,6 +16269,46 @@ ALTER TABLE ONLY public.discourse_calendar_post_event_dates
ADD CONSTRAINT discourse_calendar_post_event_dates_pkey PRIMARY KEY (id);
+--
+-- Name: discourse_kanban_board_histories discourse_kanban_board_histories_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_board_histories
+ ADD CONSTRAINT discourse_kanban_board_histories_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_kanban_boards discourse_kanban_boards_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_boards
+ ADD CONSTRAINT discourse_kanban_boards_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_kanban_card_histories discourse_kanban_card_histories_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_card_histories
+ ADD CONSTRAINT discourse_kanban_card_histories_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_kanban_cards discourse_kanban_cards_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_cards
+ ADD CONSTRAINT discourse_kanban_cards_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_kanban_columns discourse_kanban_columns_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_columns
+ ADD CONSTRAINT discourse_kanban_columns_pkey PRIMARY KEY (id);
+
+
--
-- Name: discourse_post_event_events discourse_post_event_events_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -18590,6 +18862,83 @@ CREATE UNIQUE INDEX idx_group_category_notification_defaults_unique ON public.gr
CREATE UNIQUE INDEX idx_group_tag_notification_defaults_unique ON public.group_tag_notification_defaults USING btree (group_id, tag_id);
+--
+-- Name: idx_kanban_boards_category_ids; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_boards_category_ids ON public.discourse_kanban_boards USING gin (category_ids);
+
+
+--
+-- Name: idx_kanban_boards_tag_ids; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_boards_tag_ids ON public.discourse_kanban_boards USING gin (tag_ids);
+
+
+--
+-- Name: idx_kanban_cards_assigned_to; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_cards_assigned_to ON public.discourse_kanban_cards USING btree (assigned_to_type, assigned_to_id);
+
+
+--
+-- Name: idx_kanban_cards_board_column_position; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_cards_board_column_position ON public.discourse_kanban_cards USING btree (board_id, column_id, "position");
+
+
+--
+-- Name: idx_kanban_cards_board_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_cards_board_id ON public.discourse_kanban_cards USING btree (board_id);
+
+
+--
+-- Name: idx_kanban_cards_column_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_cards_column_id ON public.discourse_kanban_cards USING btree (column_id);
+
+
+--
+-- Name: idx_kanban_cards_topic_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_cards_topic_id ON public.discourse_kanban_cards USING btree (topic_id);
+
+
+--
+-- Name: idx_kanban_cards_unique_topic_per_column; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_kanban_cards_unique_topic_per_column ON public.discourse_kanban_cards USING btree (board_id, column_id, topic_id) WHERE ((topic_id IS NOT NULL) AND (column_id IS NOT NULL));
+
+
+--
+-- Name: idx_kanban_columns_board_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_columns_board_id ON public.discourse_kanban_columns USING btree (board_id);
+
+
+--
+-- Name: idx_kanban_columns_board_position; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_columns_board_position ON public.discourse_kanban_columns USING btree (board_id, "position");
+
+
+--
+-- Name: idx_kanban_columns_tag_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_kanban_columns_tag_id ON public.discourse_kanban_columns USING btree (tag_id);
+
+
--
-- Name: idx_leaderboard_scores_lb_date; Type: INDEX; Schema: public; Owner: -
--
@@ -20060,6 +20409,69 @@ CREATE INDEX index_discourse_calendar_post_event_dates_on_event_id_and_dates ON
CREATE INDEX index_discourse_calendar_post_event_dates_on_finished_at ON public.discourse_calendar_post_event_dates USING btree (finished_at);
+--
+-- Name: index_discourse_kanban_board_histories_on_acting_user_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_kanban_board_histories_on_acting_user_id ON public.discourse_kanban_board_histories USING btree (acting_user_id);
+
+
+--
+-- Name: index_discourse_kanban_board_histories_on_board_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_kanban_board_histories_on_board_id ON public.discourse_kanban_board_histories USING btree (board_id);
+
+
+--
+-- Name: index_discourse_kanban_board_histories_on_column_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_kanban_board_histories_on_column_id ON public.discourse_kanban_board_histories USING btree (column_id);
+
+
+--
+-- Name: index_discourse_kanban_board_histories_one_view_per_user_day; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_discourse_kanban_board_histories_one_view_per_user_day ON public.discourse_kanban_board_histories USING btree (board_id, acting_user_id, ((created_at)::date)) WHERE (action = 7);
+
+
+--
+-- Name: index_discourse_kanban_boards_on_created_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_kanban_boards_on_created_by_id ON public.discourse_kanban_boards USING btree (created_by_id);
+
+
+--
+-- Name: index_discourse_kanban_boards_on_slug; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_discourse_kanban_boards_on_slug ON public.discourse_kanban_boards USING btree (slug);
+
+
+--
+-- Name: index_discourse_kanban_card_histories_on_acting_user_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_kanban_card_histories_on_acting_user_id ON public.discourse_kanban_card_histories USING btree (acting_user_id);
+
+
+--
+-- Name: index_discourse_kanban_card_histories_on_board_id_and_card_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_discourse_kanban_card_histories_on_board_id_and_card_id ON public.discourse_kanban_card_histories USING btree (board_id, card_id);
+
+
+--
+-- Name: index_discourse_kanban_card_histories_one_view_per_user_day; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_discourse_kanban_card_histories_one_view_per_user_day ON public.discourse_kanban_card_histories USING btree (board_id, card_id, acting_user_id, ((created_at)::date)) WHERE (action = 7);
+
+
--
-- Name: index_discourse_post_event_events_on_image_upload_id; Type: INDEX; Schema: public; Owner: -
--
@@ -23701,6 +24113,14 @@ ALTER TABLE ONLY public.user_profiles
ADD CONSTRAINT fk_rails_1d362f2e97 FOREIGN KEY (profile_background_upload_id) REFERENCES public.uploads(id);
+--
+-- Name: discourse_kanban_cards fk_rails_23a074d40f; Type: FK CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_cards
+ ADD CONSTRAINT fk_rails_23a074d40f FOREIGN KEY (column_id) REFERENCES public.discourse_kanban_columns(id) ON DELETE SET NULL;
+
+
--
-- Name: reviewable_notes fk_rails_2fe5fa5cd0; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@@ -23717,6 +24137,14 @@ ALTER TABLE ONLY public.user_profiles
ADD CONSTRAINT fk_rails_38ea484ed4 FOREIGN KEY (granted_title_badge_id) REFERENCES public.badges(id);
+--
+-- Name: discourse_kanban_cards fk_rails_428adf8573; Type: FK CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_cards
+ ADD CONSTRAINT fk_rails_428adf8573 FOREIGN KEY (topic_id) REFERENCES public.topics(id) ON DELETE CASCADE;
+
+
--
-- Name: ad_plugin_impressions fk_rails_45ce2c4d3c; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@@ -23733,6 +24161,14 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
ADD CONSTRAINT fk_rails_4973d7060d FOREIGN KEY (ad_plugin_house_ad_id) REFERENCES public.ad_plugin_house_ads(id) ON DELETE CASCADE;
+--
+-- Name: discourse_kanban_cards fk_rails_51c00a5eb2; Type: FK CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_cards
+ ADD CONSTRAINT fk_rails_51c00a5eb2 FOREIGN KEY (board_id) REFERENCES public.discourse_kanban_boards(id) ON DELETE CASCADE;
+
+
--
-- Name: javascript_caches fk_rails_58f94aecc4; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@@ -23837,6 +24273,14 @@ ALTER TABLE ONLY public.ai_tool_actions
ADD CONSTRAINT fk_rails_bf8a76772d FOREIGN KEY (ai_agent_id) REFERENCES public.ai_agents(id);
+--
+-- Name: discourse_kanban_columns fk_rails_c2f2ed5c5d; Type: FK CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_columns
+ ADD CONSTRAINT fk_rails_c2f2ed5c5d FOREIGN KEY (move_to_category_id) REFERENCES public.categories(id) ON DELETE SET NULL;
+
+
--
-- Name: ad_plugin_house_ads_categories fk_rails_c6e88d8af5; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@@ -23869,6 +24313,14 @@ ALTER TABLE ONLY public.javascript_caches
ADD CONSTRAINT fk_rails_ed33506dbd FOREIGN KEY (theme_field_id) REFERENCES public.theme_fields(id) ON DELETE CASCADE;
+--
+-- Name: discourse_kanban_columns fk_rails_ef6a319cc1; Type: FK CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_kanban_columns
+ ADD CONSTRAINT fk_rails_ef6a319cc1 FOREIGN KEY (board_id) REFERENCES public.discourse_kanban_boards(id) ON DELETE CASCADE;
+
+
--
-- Name: ad_plugin_impressions fk_rails_f446846ed4; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@@ -23892,6 +24344,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20260901020329'),
('20260831162602'),
('20260828145150'),
('20260827064809'),
@@ -23925,6 +24378,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260813160047'),
('20260813071230'),
('20260813071223'),
+('20260813000000'),
('20260812094609'),
('20260811231259'),
('20260810154331'),
@@ -23999,10 +24453,12 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260623201925'),
('20260623090824'),
('20260623052745'),
+('20260623042355'),
('20260622201006'),
('20260622201005'),
('20260622140747'),
('20260619085855'),
+('20260618203643'),
('20260617180115'),
('20260617104005'),
('20260617053237'),
@@ -24019,10 +24475,13 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260609050938'),
('20260608104742'),
('20260607161322'),
+('20260605051007'),
('20260604052235'),
('20260603115312'),
('20260603115200'),
+('20260603055342'),
('20260603013342'),
+('20260602233501'),
('20260602104726'),
('20260601063855'),
('20260601043020'),
@@ -24055,7 +24514,10 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260430172653'),
('20260430142946'),
('20260429122035'),
+('20260429052246'),
('20260428072232'),
+('20260427025159'),
+('20260424060304'),
('20260424004343'),
('20260422144944'),
('20260422135650'),
@@ -24066,12 +24528,18 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260421061908'),
('20260420014648'),
('20260415082426'),
+('20260410040858'),
+('20260410040217'),
('20260409225129'),
('20260408214007'),
('20260408165014'),
('20260407093145'),
+('20260407065612'),
('20260402141924'),
('20260402141912'),
+('20260402064240'),
+('20260402053105'),
+('20260402052139'),
('20260402023645'),
('20260331024139'),
('20260330161714'),
@@ -24111,10 +24579,16 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260305165401'),
('20260305165400'),
('20260305162426'),
+('20260304212353'),
('20260304063335'),
+('20260303033335'),
+('20260227010000'),
+('20260226060000'),
+('20260226020000'),
('20260223032030'),
('20260220154336'),
('20260218104617'),
+('20260218044500'),
('20260218000000'),
('20260217064339'),
('20260211051130'),
diff --git a/migrations/core/config/intermediate_db.yml b/migrations/core/config/intermediate_db.yml
index ab38bda9a33..e9ab393430a 100644
--- a/migrations/core/config/intermediate_db.yml
+++ b/migrations/core/config/intermediate_db.yml
@@ -581,6 +581,7 @@ schema:
plugins:
- "automation"
+ - "boards"
- "chat"
- "checklist"
- "discourse-adplugin"
diff --git a/migrations/tooling/config/schema/intermediate_db/ignored.rb b/migrations/tooling/config/schema/intermediate_db/ignored.rb
index c30ff37d4bc..c40eac91eac 100644
--- a/migrations/tooling/config/schema/intermediate_db/ignored.rb
+++ b/migrations/tooling/config/schema/intermediate_db/ignored.rb
@@ -3,6 +3,7 @@
Migrations::Tooling::Schema.ignored do
# Plugins β€” all their tables and columns on core tables are auto-ignored via manifest
plugin :automation, "Not migrated yet"
+ plugin :boards, "Not migrated yet"
plugin :chat, "Not migrated yet"
plugin :discourse_adplugin, "Not migrated yet"
plugin :discourse_ai, "Not migrated yet"
@@ -229,6 +230,12 @@ Migrations::Tooling::Schema.ignored do
:translation_overrides,
:unsubscribe_keys,
:upcoming_change_events,
+ :voice_co_presences,
+ :voice_invites,
+ :voice_recordings,
+ :voice_room_memberships,
+ :voice_rooms,
+ :voice_sessions,
:watched_word_groups,
:watched_words,
:web_crawler_requests
diff --git a/migrations/tooling/config/schema/plugin_manifest.yml b/migrations/tooling/config/schema/plugin_manifest.yml
index c02cf990b67..58415e2053f 100644
--- a/migrations/tooling/config/schema/plugin_manifest.yml
+++ b/migrations/tooling/config/schema/plugin_manifest.yml
@@ -8,6 +8,14 @@ plugins:
- discourse_automation_stats
- discourse_automation_user_global_notices
columns: {}
+ boards:
+ tables:
+ - discourse_kanban_board_histories
+ - discourse_kanban_boards
+ - discourse_kanban_card_histories
+ - discourse_kanban_cards
+ - discourse_kanban_columns
+ columns: {}
chat:
tables:
- chat_channel_archives
@@ -17,6 +25,7 @@ plugins:
- chat_mention_notifications
- chat_mentions
- chat_message_custom_fields
+ - chat_message_hotlinked_media
- chat_message_interactions
- chat_message_links
- chat_message_reactions
@@ -96,9 +105,11 @@ plugins:
- model_accuracies
- post_custom_prompts
- rag_document_fragments
+ - rag_document_sources
- shared_ai_conversations
columns:
user_options:
+ - ai_ask_ai_default
- ai_search_discoveries
- auto_image_caption
discourse-assign:
@@ -206,11 +217,13 @@ plugins:
- discourse_workflows_execution_data
- discourse_workflows_execution_stats
- discourse_workflows_executions
+ - discourse_workflows_tags
- discourse_workflows_variables
- discourse_workflows_webhooks
- discourse_workflows_workflow_call_runs
- discourse_workflows_workflow_dependencies
- discourse_workflows_workflow_publish_history
+ - discourse_workflows_workflow_tags
- discourse_workflows_workflow_versions
- discourse_workflows_workflows
columns: {}
@@ -220,12 +233,22 @@ plugins:
- poll_votes
- polls
columns: {}
+ voice:
+ tables:
+ - voice_co_presences
+ - voice_invites
+ - voice_recordings
+ - voice_room_memberships
+ - voice_rooms
+ - voice_sessions
+ columns: {}
plugin_checksums:
automation: e69972690991bc04d92b2d161aac8921
- chat: 43ee047298d56af4fad013d534155812
+ boards: 3f7be99d5aaac4cf66318ef036e231a2
+ chat: 3324ff0e829d9282accc917503038f18
discourse-adplugin: 9e52419decf1099c5bc301a90e6cc91a
discourse-affiliate: '08c6e1a851441a082e9be9ddddc63910'
- discourse-ai: 4ff4f60e8c1744603f7f8590f8f99447
+ discourse-ai: 1dbe6a6155758187d0a34e7fb0b24181
discourse-assign: 7a7a36e8ac0214e8a6aca1a1ed9899aa
discourse-cakeday: a5bb91366c8dc8d267088eb0c2679187
discourse-captcha: fd538c1338062354276ccfda4cbafd55
@@ -251,9 +274,10 @@ plugin_checksums:
discourse-templates: a131c89a3e2b765f1eb6ec811c0fecea
discourse-topic-voting: 5464e186402b9589d71f338c704a7d21
discourse-user-notes: 4c1e04fac5708b51c1b09bd8ed0d786c
- discourse-workflows: 46b2e6fd1e8668786b498f0c06846f70
+ discourse-workflows: 61c0d4b94a17ad401490893981b23dd4
discourse-zendesk-plugin: b78b305590ffedda38455574a19fdd38
poll: e481f2cfa0e7c22778dee12a1e9c33c6
styleguide: 0fd92e5ef0c99ee047f206961a587544
+ voice: 23e33508822e87035b4bee0925d26eff
failed_plugins: []
incomplete: false
diff --git a/plugins/boards/README.md b/plugins/boards/README.md
new file mode 100644
index 00000000000..c5e1ea6280d
--- /dev/null
+++ b/plugins/boards/README.md
@@ -0,0 +1,11 @@
+# Boards Plugin
+
+A Discourse plugin that provides configurable Boards with:
+
+- Global board definitions
+- Board-level read/write ACLs via groups
+- Optional topic-backed cards
+- Optional lightweight floater cards
+- Hybrid card membership (`auto`, `manual_in`, `manual_out`)
+
+Boards source topics from `base_filter_query`, enforce topic visibility via guardian-secured queries, and persist card placement/order at the board level.
diff --git a/plugins/boards/app/controllers/boards/api/boards_controller.rb b/plugins/boards/app/controllers/boards/api/boards_controller.rb
new file mode 100644
index 00000000000..b407207be8e
--- /dev/null
+++ b/plugins/boards/app/controllers/boards/api/boards_controller.rb
@@ -0,0 +1,321 @@
+# frozen_string_literal: true
+
+module Boards
+ module Api
+ class BoardsController < ::Boards::BaseController
+ DEFAULT_INDEX_PERMISSIONS = %w[view edit manage].freeze
+
+ before_action :ensure_logged_in,
+ only: %i[create update destroy move_column constraint_preview]
+ before_action :find_board!, only: %i[show]
+ before_action :ensure_board_read!, only: %i[show]
+
+ def index
+ allowed_permissions =
+ (
+ if params[:allowed_permissions].present?
+ params[:allowed_permissions]
+ .split(",")
+ .reject { |permission| !DEFAULT_INDEX_PERMISSIONS.include?(permission) }
+ else
+ DEFAULT_INDEX_PERMISSIONS
+ end
+ )
+
+ boards =
+ Boards::Board
+ .includes(:columns, :created_by)
+ .with_any_acl_permissions(guardian, allowed_permissions)
+ .order(:name)
+ .to_a
+ tag_name_map = build_tag_name_map(*boards)
+ render json: {
+ boards:
+ serialize_data(boards, Boards::BoardSerializer, root: false, tag_name_map:),
+ }
+ end
+
+ def available
+ allowed_permissions =
+ (
+ if params[:allowed_permissions].present?
+ params[:allowed_permissions]
+ .split(",")
+ .reject { |permission| !DEFAULT_INDEX_PERMISSIONS.include?(permission) }
+ else
+ DEFAULT_INDEX_PERMISSIONS
+ end
+ )
+
+ boards =
+ Boards::Board
+ .includes(:columns, :created_by)
+ .with_any_acl_permissions(guardian, allowed_permissions)
+ .order(:name)
+ .to_a
+
+ board_memberships = []
+ if params[:topic_id].present?
+ topic = Topic.find(params[:topic_id])
+ guardian.ensure_can_see!(topic)
+ board_memberships =
+ Boards::TopicBoardMemberships.call(
+ guardian: guardian,
+ options: {
+ topics: [topic],
+ },
+ ).single_topic_memberships || []
+ end
+
+ render json: {
+ boards:
+ serialize_data(
+ boards,
+ Boards::BasicBoardSerializer,
+ root: false,
+ board_memberships: board_memberships.flatten,
+ ),
+ }
+ end
+
+ def show
+ TopicSync.backfill_board(@board)
+
+ # TODO (martin) We can further refactor this whole controller action
+ # to be in a service, for now let's just log the view history,
+ # it doesn't matter if this fails silently.
+ Boards::ViewBoard.call(guardian:, params: { id: @board.id })
+
+ topic_includes = %i[tags last_poster]
+ topic_includes << :assignment if Topic.reflect_on_association(:assignment)
+ cards =
+ @board.cards.with_column.includes(:created_by, :assigned_to, topic: topic_includes).to_a
+ visible_topic_ids = visible_topic_ids_for(cards)
+
+ assignments_by_topic = preload_all_assignments(cards, visible_topic_ids)
+ topic_users_by_topic = preload_topic_users(cards, visible_topic_ids)
+ tags_by_id = preload_floater_card_tags(cards)
+
+ tag_name_map = build_tag_name_map(@board)
+ board_columns = @board.columns.to_a
+ cards_by_column =
+ cards
+ .reject { |card| card.topic? && !visible_topic_ids.include?(card.topic_id) }
+ .group_by(&:column_id)
+ columns =
+ serialize_data(
+ board_columns,
+ Boards::ColumnSerializer,
+ root: false,
+ tag_name_map:,
+ cards_by_column:,
+ assignments_by_topic:,
+ topic_users_by_topic:,
+ tags_by_id:,
+ )
+
+ render json: {
+ board:
+ serialize_board(
+ @board,
+ tag_name_map:,
+ include_acl: guardian.can_manage_boards_board?(@board),
+ ),
+ columns: columns,
+ }
+ end
+
+ def create
+ raw = board_mutation_params.to_h
+
+ Boards::CreateBoard.call(guardian:, params: raw, raw_board_params: raw) do |result|
+ on_success { |board:| render json: { board: serialize_board(board) }, status: :created }
+ on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def update
+ raw = board_mutation_params.to_h.except("columns")
+
+ Boards::UpdateBoard.call(
+ guardian:,
+ params: raw.merge("id" => params[:id], "client_id" => params[:client_id]),
+ raw_board_params: raw,
+ ) do
+ on_success do |board:, cards_removed_count:|
+ response = {
+ board: serialize_board(board, include_acl: guardian.can_manage_boards_board?(board)),
+ }
+ response[:cards_removed_count] = cards_removed_count if cards_removed_count.to_i > 0
+ render json: response
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def move_column
+ Boards::MoveColumn.call(
+ guardian:,
+ params:
+ params
+ .permit(:column_id, :direction)
+ .to_h
+ .merge("board_id" => params[:id], "client_id" => message_bus_client_id),
+ ) do
+ on_success { |column_order:| render json: { column_order: column_order } }
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def constraint_preview
+ board = Boards::Board.find(params[:id])
+ guardian.ensure_can_manage_board!(board)
+
+ new_category_ids = Array(params[:category_ids]).map(&:to_i).reject(&:zero?)
+ new_tag_ids =
+ if params[:tag_names].present?
+ Tag.where(name: Array(params[:tag_names])).pluck(:id)
+ else
+ []
+ end
+
+ cat_empty = new_category_ids.empty?
+ tag_empty = new_tag_ids.empty?
+
+ if cat_empty && tag_empty
+ count = 0
+ else
+ count =
+ DB.query_single(
+ <<~SQL,
+ SELECT COUNT(*) FROM discourse_kanban_cards c
+ JOIN topics t ON t.id = c.topic_id
+ WHERE c.board_id = :board_id AND c.card_type = #{Boards::Card.card_types[:topic]}
+ AND NOT (
+ (:cat_empty OR t.category_id = ANY(:category_ids))
+ AND (:tag_empty OR EXISTS (
+ SELECT 1 FROM topic_tags tt WHERE tt.topic_id = t.id AND tt.tag_id = ANY(:tag_ids)
+ ))
+ )
+ SQL
+ board_id: board.id,
+ category_ids: "{#{new_category_ids.join(",")}}",
+ tag_ids: "{#{new_tag_ids.join(",")}}",
+ cat_empty: cat_empty,
+ tag_empty: tag_empty,
+ ).first
+ end
+
+ render json: { cards_to_remove: count }
+ end
+
+ def destroy
+ Boards::DestroyBoard.call(service_params) do
+ on_success { head :no_content }
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_failed_policy(:can_destroy) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def check_constraint_mismatches
+ Boards::CheckBoardTopicConstraintMismatches.call(service_params) do
+ on_success do |categories_needed:, tags_needed:|
+ render json: {
+ categories_needed:,
+ tags_needed:,
+ constraints_need_fixing:
+ categories_needed.length.positive? || tags_needed.length.positive?,
+ }
+ end
+ on_model_not_found(:board) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.board_not_found"))
+ end
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_model_not_found(:target_column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_view_topic) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_edit_board) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ private
+
+ def serialize_board(board, tag_name_map: nil, include_acl: false)
+ serialize_data(
+ board,
+ Boards::BoardSerializer,
+ root: false,
+ tag_name_map: tag_name_map || build_tag_name_map(board),
+ include_acl:,
+ )
+ end
+
+ def serialize_boards(boards, tag_name_map:)
+ end
+
+ def preload_all_assignments(cards, visible_topic_ids)
+ return {} unless defined?(Assignment)
+
+ topic_ids = cards.select(&:topic?).map(&:topic_id).compact & visible_topic_ids
+ return {} if topic_ids.empty?
+
+ Assignment
+ .where(topic_id: topic_ids, active: true, assigned_to_type: "User")
+ .includes(:assigned_to)
+ .group_by(&:topic_id)
+ end
+
+ def preload_topic_users(cards, visible_topic_ids)
+ topics = cards.filter_map { |card| card.topic if visible_topic_ids.include?(card.topic_id) }
+ TopicUser.lookup_for(current_user, topics)
+ end
+
+ def preload_floater_card_tags(cards)
+ return {} unless SiteSetting.tagging_enabled
+
+ tag_ids = cards.reject(&:topic?).flat_map(&:tag_ids).uniq
+ return {} if tag_ids.empty?
+
+ DiscourseTagging.filter_visible(Tag.where(id: tag_ids), guardian).index_by(&:id)
+ end
+
+ def visible_topic_ids_for(cards)
+ topic_ids = cards.select(&:topic?).map(&:topic_id).uniq
+ return [] if topic_ids.empty?
+
+ Topic
+ .listable_topics
+ .secured(guardian)
+ .where(id: topic_ids)
+ .where.not(id: Category.where.not(topic_id: nil).select(:topic_id))
+ .pluck(:id)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/controllers/boards/api/cards_controller.rb b/plugins/boards/app/controllers/boards/api/cards_controller.rb
new file mode 100644
index 00000000000..391e3446044
--- /dev/null
+++ b/plugins/boards/app/controllers/boards/api/cards_controller.rb
@@ -0,0 +1,195 @@
+# frozen_string_literal: true
+
+module Boards
+ module Api
+ class CardsController < ::Boards::BaseController
+ before_action :ensure_logged_in
+
+ def create
+ Boards::CreateCard.call(
+ service_params.deep_merge(
+ params: card_mutation_params.to_h.merge(board_id: params[:board_id]),
+ options: {
+ constraint_fix: constraint_fix_params,
+ },
+ ),
+ ) do
+ on_success do |card:, board:|
+ payload = CardSerializer.new(card, root: false, scope: guardian).as_json
+ publish_payload = CardSerializer.new(card, root: false).as_json
+ Publisher.publish_card_created!(
+ board,
+ publish_payload,
+ client_id: message_bus_client_id,
+ )
+ if card.topic.present?
+ Publisher.publish_topic_memberships_changed!(
+ card.topic,
+ client_id: message_bus_client_id,
+ # Constraint fixes may change the topic's category or tags, so the post
+ # stream must be refreshed along with the topic metadata.
+ refresh_stream: params[:constraint_fix].present?,
+ )
+ end
+ Jobs.enqueue(Jobs::Boards::CardPostProcess, card_id: card.id, title: card.title)
+ render json: { card: payload }, status: :created
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_write) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def update
+ raw_params = card_mutation_params.to_h
+
+ Boards::UpdateCard.call(
+ service_params.deep_merge(
+ params: raw_params.merge(board_id: params[:board_id], id: params[:id]),
+ options: {
+ raw_card_params: raw_params,
+ constraint_fix: constraint_fix_params,
+ },
+ ),
+ ) do
+ on_success do |card:, board:, original_column_id:, adopted_floater_id:|
+ card.topic&.reload
+ response = CardSerializer.new(card, root: false, scope: guardian).as_json
+ publish_response = CardSerializer.new(card, root: false).as_json
+
+ if adopted_floater_id
+ Publisher.publish_card_deleted!(
+ board,
+ adopted_floater_id,
+ client_id: message_bus_client_id,
+ )
+ Publisher.publish_card_created!(
+ board,
+ publish_response,
+ client_id: message_bus_client_id,
+ )
+ elsif card.column_id != original_column_id
+ Publisher.publish_card_moved!(
+ board,
+ publish_response,
+ client_id: message_bus_client_id,
+ )
+ else
+ Publisher.publish_card_updated!(
+ board,
+ publish_response,
+ client_id: message_bus_client_id,
+ )
+ end
+
+ if card.topic.present? && card.column_id != original_column_id
+ Publisher.publish_topic_memberships_changed!(
+ card.topic,
+ client_id: message_bus_client_id,
+ refresh_stream: params[:constraint_fix].present?,
+ )
+ end
+
+ if raw_params.key?("title")
+ Jobs.enqueue(Jobs::Boards::CardPostProcess, card_id: card.id, title: card.title)
+ end
+
+ render json: { card: response, adopted_floater_id: adopted_floater_id }
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:card) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.card_not_found"))
+ end
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_write) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_see_card_topic) { raise Discourse::NotFound }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def clear
+ Boards::ClearColumn.call(
+ service_params.deep_merge(
+ params: {
+ board_id: params[:board_id],
+ column_id: params[:column_id],
+ },
+ ),
+ ) do
+ on_success do |board:, column:|
+ Publisher.publish_column_cleared!(board, column.id, client_id: message_bus_client_id)
+ head :no_content
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_write) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def destroy
+ Boards::DestroyCard.call(
+ service_params.deep_merge(params: { board_id: params[:board_id], id: params[:id] }),
+ ) do
+ on_success do |card:, board:|
+ Publisher.publish_card_deleted!(board, card.id, client_id: message_bus_client_id)
+
+ if card.topic.present?
+ Publisher.publish_topic_memberships_changed!(
+ card.topic,
+ client_id: message_bus_client_id,
+ )
+ end
+
+ head :no_content
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:card) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.card_not_found"))
+ end
+ on_failed_policy(:can_write) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_see_card_topic) { raise Discourse::NotFound }
+ on_failed_policy(:card_is_deletable) do
+ render json: {
+ errors: [I18n.t("boards.errors.topic_covered_by_filter")],
+ },
+ status: :unprocessable_entity
+ end
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def view
+ Boards::ViewCard.call(service_params) do
+ on_success { head :no_content }
+ on_model_not_found(:card) { raise Discourse::NotFound }
+ on_failed_policy(:is_logged_in) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_view_card) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/controllers/boards/api/columns_controller.rb b/plugins/boards/app/controllers/boards/api/columns_controller.rb
new file mode 100644
index 00000000000..90af2c3e5f1
--- /dev/null
+++ b/plugins/boards/app/controllers/boards/api/columns_controller.rb
@@ -0,0 +1,96 @@
+# frozen_string_literal: true
+
+module Boards
+ module Api
+ class ColumnsController < ::Boards::BaseController
+ before_action :ensure_logged_in
+
+ def create
+ Boards::CreateColumn.call(
+ service_params.deep_merge(
+ params:
+ column_mutation_params.to_h.merge(
+ board_id: params[:board_id],
+ client_id: message_bus_client_id,
+ ),
+ ),
+ ) do
+ on_success do |column:|
+ render json: {
+ column: ColumnSerializer.new(column, root: false, scope: guardian).as_json,
+ },
+ status: :created
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:column) do |model_step|
+ if model_step.exception
+ render json: failed_json.merge(errors: [model_step.exception.message]),
+ status: :unprocessable_entity
+ else
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ end
+ on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def update
+ Boards::UpdateColumn.call(
+ service_params.deep_merge(
+ params:
+ column_mutation_params.to_h.merge(
+ board_id: params[:board_id],
+ id: params[:id],
+ client_id: message_bus_client_id,
+ ),
+ ),
+ ) do
+ on_success do |column:|
+ render json: {
+ column: ColumnSerializer.new(column, root: false, scope: guardian).as_json,
+ }
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+
+ def destroy
+ Boards::DestroyColumn.call(
+ service_params.deep_merge(
+ params: {
+ board_id: params[:board_id],
+ id: params[:id],
+ client_id: message_bus_client_id,
+ },
+ ),
+ ) do
+ on_success { head :no_content }
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_manage) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/controllers/boards/api/topic_moves_controller.rb b/plugins/boards/app/controllers/boards/api/topic_moves_controller.rb
new file mode 100644
index 00000000000..3119b0041a4
--- /dev/null
+++ b/plugins/boards/app/controllers/boards/api/topic_moves_controller.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module Boards
+ module Api
+ class TopicMovesController < ::Boards::BaseController
+ before_action :ensure_logged_in
+
+ def create
+ Boards::MoveTopicToColumn.call(
+ **service_params.deep_merge(params: { client_id: message_bus_client_id }),
+ ) do
+ on_success do |card:|
+ render json: {
+ card: CardSerializer.new(card, root: false, scope: guardian).as_json,
+ },
+ status: :created
+ end
+ on_model_not_found(:board) { raise Discourse::NotFound }
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_model_not_found(:column) do
+ raise Discourse::NotFound.new(I18n.t("boards.errors.column_not_found"))
+ end
+ on_failed_policy(:can_write) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_see_topic) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_edit_topic) { raise Discourse::InvalidAccess }
+ on_failed_policy(:topic_matches_constraints) do
+ render json:
+ failed_json.merge(
+ errors: [I18n.t("boards.errors.topic_does_not_match_constraints")],
+ ),
+ status: :unprocessable_entity
+ end
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { render json: failed_json, status: :unprocessable_entity }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/controllers/boards/base_controller.rb b/plugins/boards/app/controllers/boards/base_controller.rb
new file mode 100644
index 00000000000..dd2522e453f
--- /dev/null
+++ b/plugins/boards/app/controllers/boards/base_controller.rb
@@ -0,0 +1,92 @@
+# frozen_string_literal: true
+
+module Boards
+ class BaseController < ::ApplicationController
+ requires_plugin Boards::PLUGIN_NAME
+
+ before_action :ensure_plugin_enabled
+
+ private
+
+ def ensure_plugin_enabled
+ raise Discourse::InvalidAccess.new unless SiteSetting.boards_enabled?
+ end
+
+ def find_board!
+ board_id = params[:board_id] || params[:id]
+ @board = Boards::Board.find_by(id: board_id)
+ raise Discourse::NotFound.new(I18n.t("boards.errors.board_not_found")) if @board.blank?
+ end
+
+ def ensure_board_read!
+ unless guardian.can_read_boards_board?(@board)
+ raise Discourse::InvalidAccess.new(I18n.t("boards.errors.board_read_forbidden"))
+ end
+ end
+
+ def build_tag_name_map(*boards)
+ all_tag_ids = boards.flat_map { |b| b.tag_ids + b.columns.filter_map(&:tag_id) }.uniq
+ return {} if all_tag_ids.empty?
+ Tag.visible(guardian).where(id: all_tag_ids).pluck(:id, :name).to_h
+ end
+
+ def card_mutation_params
+ params.require(:card).permit(
+ :topic_id,
+ :column_id,
+ :title,
+ :notes,
+ :after_card_id,
+ :assigned_to_name,
+ tag_ids: [],
+ tag_names: [],
+ )
+ end
+
+ def constraint_fix_params
+ params.permit(constraint_fix: [:category_id, tag_names: []])[:constraint_fix]
+ end
+
+ def column_mutation_params
+ params.require(:column).permit(
+ :title,
+ :icon,
+ :default_sort,
+ :tag_name,
+ :move_to_category_id,
+ :move_to_assigned,
+ :move_to_status,
+ :color,
+ )
+ end
+
+ def message_bus_client_id
+ params[:client_id]
+ end
+
+ def board_mutation_params
+ params.require(:board).permit(
+ :name,
+ :slug,
+ :require_confirmation,
+ :show_tags,
+ :card_style,
+ :show_topic_thumbnail,
+ acl: %i[id type permission],
+ category_ids: [],
+ tag_names: [],
+ columns: %i[
+ id
+ title
+ icon
+ position
+ default_sort
+ tag_name
+ move_to_category_id
+ move_to_assigned
+ move_to_status
+ ],
+ )
+ end
+ end
+end
diff --git a/plugins/boards/app/controllers/boards/boards_controller.rb b/plugins/boards/app/controllers/boards/boards_controller.rb
new file mode 100644
index 00000000000..6e5fbd6d132
--- /dev/null
+++ b/plugins/boards/app/controllers/boards/boards_controller.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module Boards
+ class BoardsController < BaseController
+ def respond
+ render body: nil
+ end
+ end
+end
diff --git a/plugins/boards/app/jobs/regular/boards/card_post_process.rb b/plugins/boards/app/jobs/regular/boards/card_post_process.rb
new file mode 100644
index 00000000000..207d1b5751b
--- /dev/null
+++ b/plugins/boards/app/jobs/regular/boards/card_post_process.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Boards
+ class CardPostProcess < ::Jobs::Base
+ def execute(args)
+ return unless SiteSetting.boards_enabled?
+
+ card_id = args[:card_id]
+ title = args[:title]
+ return if card_id.blank? || title.blank?
+
+ card = ::Boards::Card.find_by(id: card_id)
+ return unless current_floater?(card, title)
+
+ inline_onebox_data = ::Boards::Action::CardInlineOnebox.call(title:)
+ return if card.inline_onebox_data == inline_onebox_data
+
+ updated =
+ ::Boards::Card.where(id: card.id, card_type: :floater, title:).update_all(
+ inline_onebox_data:,
+ )
+ return if updated.zero?
+
+ card.reload
+ payload = ::Boards::CardSerializer.new(card, root: false).as_json
+ ::Boards::Publisher.publish_card_updated!(card.board, payload, client_id: nil)
+ end
+
+ private
+
+ def current_floater?(card, title)
+ card&.floater? && card.title == title
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/jobs/regular/boards/sync_topic.rb b/plugins/boards/app/jobs/regular/boards/sync_topic.rb
new file mode 100644
index 00000000000..26cbdb56971
--- /dev/null
+++ b/plugins/boards/app/jobs/regular/boards/sync_topic.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Boards
+ class SyncTopic < ::Jobs::Base
+ def execute(args)
+ return unless SiteSetting.boards_enabled?
+
+ topic_id = args[:topic_id]
+ return if topic_id.blank?
+
+ topic = Topic.find_by(id: topic_id)
+ return if topic.blank?
+
+ ::Boards::TopicSync.sync_topic(topic)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/models/boards/board.rb b/plugins/boards/app/models/boards/board.rb
new file mode 100644
index 00000000000..6c106756d1a
--- /dev/null
+++ b/plugins/boards/app/models/boards/board.rb
@@ -0,0 +1,244 @@
+# frozen_string_literal: true
+
+module Boards
+ class Board < ActiveRecord::Base
+ include ::AclTarget
+
+ self.table_name = "discourse_kanban_boards"
+ self.ignored_columns = %w[
+ base_filter_query
+ show_activity_indicators
+ allow_read_group_ids
+ allow_write_group_ids
+ ]
+
+ has_many :columns,
+ -> { order(:position, :id) },
+ class_name: "Boards::Column",
+ dependent: :destroy,
+ inverse_of: :board
+ has_many :cards, class_name: "Boards::Card", dependent: :destroy, inverse_of: :board
+ has_many :history,
+ -> { order(created_at: :asc) },
+ class_name: "Boards::BoardHistory",
+ inverse_of: :board
+ belongs_to :created_by, class_name: "User"
+ belongs_to :updated_by, class_name: "User", optional: true
+
+ enum :card_style, { detailed: 0, simple: 1 }, default: :detailed
+
+ validates :name, :slug, presence: true
+ validates :slug, uniqueness: true
+
+ validate :validate_category_ids
+ validate :validate_tag_ids
+
+ before_validation :normalize_slug
+
+ def self.mandatory_acl
+ [{ type: :group, id: Group::AUTO_GROUPS[:admins], permission: "manage" }]
+ end
+
+ def self.banned_acl
+ [
+ { type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "manage" },
+ { type: :group, id: Group::AUTO_GROUPS[:anonymous_users], permission: "edit" },
+ # Essentially a legacy group ID, don't want anyone to use it.
+ { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: "manage" },
+ { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: "edit" },
+ { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: "view" },
+ ]
+ end
+
+ def self.loss_warning_permissions
+ ["manage"]
+ end
+
+ def url
+ "#{Discourse.base_url}/boards/#{slug}/#{id}"
+ end
+
+ def anonymous_can_read?
+ permission_acl.group_has_permission?(Group::AUTO_GROUPS[:anonymous_users], "view")
+ end
+
+ def logged_in_user_can_read?
+ permission_acl.group_has_any_permission?(
+ Group::AUTO_GROUPS[:logged_in_users],
+ %w[view edit manage],
+ )
+ end
+
+ def can_be_oneboxed?
+ if SiteSetting.login_required
+ logged_in_user_can_read?
+ else
+ anonymous_can_read?
+ end
+ end
+
+ def unicode_name
+ Emoji.gsub_emoji_to_unicode(name)
+ end
+
+ def reload(options = nil)
+ @tags = nil
+ @categories = nil
+ super
+ end
+
+ def tags
+ @tags ||= Tag.where(id: tag_ids).order(:name).to_a
+ end
+
+ def categories
+ @categories ||= Category.where(id: category_ids).order(:name).to_a
+ end
+
+ def self.preload_tags(boards)
+ preload_array_association(boards, :tag_ids, :@tags, Tag)
+ end
+
+ def self.preload_categories(boards)
+ preload_array_association(boards, :category_ids, :@categories, Category)
+ end
+
+ def self.preload_array_association(records, ids_attr, ivar, klass)
+ records = Array(records)
+ return records if records.empty?
+
+ all_ids = records.flat_map(&ids_attr).uniq
+ records_by_id = all_ids.empty? ? {} : klass.where(id: all_ids).index_by(&:id)
+
+ records.each do |record|
+ sorted =
+ record
+ .public_send(ids_attr)
+ .filter_map { |id| records_by_id[id] }
+ .sort_by { |r| r.name.to_s }
+ record.instance_variable_set(ivar, sorted)
+ end
+
+ records
+ end
+ private_class_method :preload_array_association
+
+ def tag_names=(names)
+ names = Array(names).select(&:present?)
+ resolved = Tag.where(name: names).pluck(:name, :id).to_h
+ missing = names - resolved.keys
+ if missing.any?
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_names", tag_names: missing.join(", ")),
+ )
+ end
+ self.tag_ids = resolved.values
+ end
+
+ def has_constraints?
+ category_ids.present? || tag_ids.present?
+ end
+
+ def topic_matches?(topic)
+ return false unless has_constraints?
+
+ cat_match = category_ids.blank? || category_ids.include?(topic.category_id)
+ tag_match = tag_ids.blank? || (topic.tag_ids & tag_ids).any?
+ cat_match && tag_match
+ end
+
+ def topic_will_match_after_mutation?(topic, column)
+ return true unless has_constraints?
+
+ effective_category_id = column&.move_to_category_id || topic.category_id
+ cat_match = category_ids.blank? || category_ids.include?(effective_category_id)
+
+ effective_tag_ids = topic.tag_ids.dup
+ if column
+ column_tag_ids = columns.filter_map { |candidate| candidate.tag_id.presence }.uniq
+ sibling_tag_ids = column_tag_ids - [column.tag_id].compact
+ effective_tag_ids -= sibling_tag_ids
+ effective_tag_ids << column.tag_id if column.tag_id.present?
+ effective_tag_ids.uniq!
+ end
+ tag_match = tag_ids.blank? || (effective_tag_ids & tag_ids).any?
+
+ cat_match && tag_match
+ end
+
+ def first_matching_column(topic)
+ all_matching_columns(topic).first
+ end
+
+ def all_matching_columns(topic)
+ return [] unless topic_matches?(topic)
+
+ topic_tag_id_set = topic.tag_ids.to_set
+ columns.select { |c| c.tag_id.present? && topic_tag_id_set.include?(c.tag_id) }
+ end
+
+ private
+
+ def normalize_slug
+ source = slug.presence || name
+ self.slug = Slug.for(source) if source.present?
+ end
+
+ def normalize_id_array(values)
+ Array(values).map(&:to_i).uniq.reject(&:zero?)
+ end
+
+ alias_method :normalize_group_array, :normalize_id_array
+
+ def validate_category_ids
+ return if category_ids.blank?
+
+ self.category_ids = normalize_id_array(category_ids)
+ existing = Category.where(id: category_ids).pluck(:id)
+ missing = category_ids - existing
+ return if missing.empty?
+
+ errors.add(
+ :base,
+ I18n.t("boards.errors.unknown_category_ids", category_ids: missing.join(",")),
+ )
+ end
+
+ def validate_tag_ids
+ return if tag_ids.blank?
+
+ self.tag_ids = normalize_id_array(tag_ids)
+ existing = Tag.where(id: tag_ids).pluck(:id)
+ missing = tag_ids - existing
+ return if missing.empty?
+
+ errors.add(:base, I18n.t("boards.errors.unknown_tag_ids", tag_ids: missing.join(",")))
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_kanban_boards
+#
+# id :bigint not null, primary key
+# card_style :integer default("detailed"), not null
+# category_ids :integer default([]), not null, is an Array
+# name :string not null
+# require_confirmation :boolean default(TRUE), not null
+# show_tags :boolean default(FALSE), not null
+# show_topic_thumbnail :boolean default(FALSE), not null
+# slug :string not null
+# tag_ids :integer default([]), not null, is an Array
+# created_at :datetime not null
+# updated_at :datetime not null
+# created_by_id :bigint
+# updated_by_id :bigint
+#
+# Indexes
+#
+# idx_kanban_boards_category_ids (category_ids) USING gin
+# idx_kanban_boards_tag_ids (tag_ids) USING gin
+# index_discourse_kanban_boards_on_created_by_id (created_by_id)
+# index_discourse_kanban_boards_on_slug (slug) UNIQUE
+#
diff --git a/plugins/boards/app/models/boards/board_history.rb b/plugins/boards/app/models/boards/board_history.rb
new file mode 100644
index 00000000000..f8b3f5bd47e
--- /dev/null
+++ b/plugins/boards/app/models/boards/board_history.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module Boards
+ class BoardHistory < ActiveRecord::Base
+ self.table_name = "discourse_kanban_board_histories"
+
+ belongs_to :board, class_name: "Boards::Board"
+ belongs_to :acting_user, class_name: "User"
+ belongs_to :column, class_name: "Boards::Column", optional: true
+
+ validates :action, presence: true
+ validates :acting_user_id, presence: true
+ validates :board_id, presence: true
+
+ enum :action,
+ {
+ board_created: 1,
+ board_renamed: 2,
+ board_constraints_changed: 3,
+ board_slug_changed: 4,
+ board_permissions_changed: 5,
+ board_deleted: 6,
+ board_viewed: 7,
+ column_added: 8,
+ column_renamed: 9,
+ column_edited: 10,
+ column_deleted: 11,
+ }
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_kanban_board_histories
+#
+# id :bigint not null, primary key
+# action :integer not null
+# details :jsonb
+# created_at :datetime not null
+# updated_at :datetime not null
+# acting_user_id :bigint not null
+# board_id :bigint not null
+# column_id :bigint
+#
+# Indexes
+#
+# index_discourse_kanban_board_histories_on_acting_user_id (acting_user_id)
+# index_discourse_kanban_board_histories_on_board_id (board_id)
+# index_discourse_kanban_board_histories_on_column_id (column_id)
+# index_discourse_kanban_board_histories_one_view_per_user_day (board_id, acting_user_id, ((created_at)::date)) UNIQUE WHERE (action = 7)
+#
diff --git a/plugins/boards/app/models/boards/card.rb b/plugins/boards/app/models/boards/card.rb
new file mode 100644
index 00000000000..04709b078cb
--- /dev/null
+++ b/plugins/boards/app/models/boards/card.rb
@@ -0,0 +1,193 @@
+# frozen_string_literal: true
+
+module Boards
+ class Card < ActiveRecord::Base
+ self.table_name = "discourse_kanban_cards"
+
+ belongs_to :board, class_name: "Boards::Board", inverse_of: :cards
+ belongs_to :column, class_name: "Boards::Column", inverse_of: :cards, optional: true
+ belongs_to :topic, -> { with_deleted }, optional: true
+ belongs_to :created_by, class_name: "User", optional: true
+ belongs_to :updated_by, class_name: "User", optional: true
+ belongs_to :assigned_to, polymorphic: true, optional: true
+
+ self.ignored_columns = %w[membership_mode labels]
+
+ RECENCY_WINDOW = 1.week
+
+ enum :card_type, { floater: 0, topic: 1 }, default: :floater
+
+ validates :position, presence: true
+ validates :column_id, presence: true
+
+ validate :validate_type_integrity
+
+ before_validation :normalize_card_type
+ before_validation :initialize_column_changed_at, on: :create
+ before_create :set_updated_by_id
+
+ scope :with_column, -> { where.not(column_id: nil) }
+ scope :ordered, -> { order(:position, :id) }
+
+ def url
+ "#{Discourse.base_url}/boards/#{board.slug}/#{board.id}/cards/#{id}"
+ end
+
+ def self.normalize_tag_ids!(values)
+ normalized_tag_ids = normalize_tag_id_values!(values)
+
+ unknown_tag_ids = tag_ids_missing_from_database(normalized_tag_ids)
+ return normalized_tag_ids if unknown_tag_ids.empty?
+
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_ids", tag_ids: unknown_tag_ids.join(",")),
+ )
+ end
+
+ def self.normalize_visible_tag_ids!(values, guardian)
+ normalized_tag_ids = normalize_tag_ids!(values)
+ return normalized_tag_ids if normalized_tag_ids.blank? || guardian&.is_admin?
+
+ visible_tag_ids =
+ DiscourseTagging.visible_tags(guardian).where(id: normalized_tag_ids).pluck(:id)
+ hidden_tag_ids = normalized_tag_ids - visible_tag_ids
+ return normalized_tag_ids if hidden_tag_ids.empty?
+
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_ids", tag_ids: hidden_tag_ids.join(",")),
+ )
+ end
+
+ def self.ordered_tags(tag_ids)
+ normalized_tag_ids = normalize_tag_id_values!(tag_ids)
+ return [] if normalized_tag_ids.blank?
+
+ tags_by_id = Tag.where(id: normalized_tag_ids).index_by(&:id)
+ normalized_tag_ids.filter_map { |tag_id| tags_by_id[tag_id] }
+ end
+
+ def self.preload_tags(cards)
+ cards = Array(cards)
+ return cards if cards.empty?
+
+ all_tag_ids = cards.flat_map(&:tag_ids).uniq
+ tags_by_id = all_tag_ids.empty? ? {} : Tag.where(id: all_tag_ids).index_by(&:id)
+
+ cards.each do |card|
+ sorted = card.tag_ids.filter_map { |id| tags_by_id[id] }.sort_by { |t| t.name.to_s }
+ card.instance_variable_set(:@tags, sorted)
+ end
+
+ cards
+ end
+
+ def tags
+ @tags ||= Tag.where(id: tag_ids).order(:name).to_a
+ end
+
+ def self.tag_ids_missing_from_database(tag_ids)
+ return [] if tag_ids.blank?
+
+ existing_tag_ids = Tag.where(id: tag_ids).pluck(:id)
+ tag_ids - existing_tag_ids
+ end
+
+ def self.normalize_tag_id_values!(values)
+ raw_values = Array(values)
+ raw_values.compact_blank.map { |value| Integer(value) }.reject(&:zero?).uniq
+ rescue ArgumentError, TypeError
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_ids", tag_ids: raw_values.join(",")),
+ )
+ end
+
+ def recency_at
+ @recency_at ||= [column_changed_at, topic? ? topic&.bumped_at : updated_at].compact.max
+ end
+
+ def recent_for_column?
+ recency_at.present? && recency_at >= RECENCY_WINDOW.ago
+ end
+
+ def resolved_title
+ return title if topic_id.blank?
+ topic&.title
+ end
+
+ def unicode_resolved_title
+ Emoji.gsub_emoji_to_unicode(resolved_title)
+ end
+
+ def unicode_title
+ Emoji.gsub_emoji_to_unicode(title)
+ end
+
+ private
+
+ private_class_method :normalize_tag_id_values!, :tag_ids_missing_from_database
+
+ def set_updated_by_id
+ self.updated_by_id = created_by_id
+ end
+
+ def initialize_column_changed_at
+ return if column_changed_at.present? || column_id.blank?
+
+ self.column_changed_at = updated_at || created_at || Time.zone.now
+ end
+
+ def normalize_card_type
+ return if topic_id.blank?
+
+ self.card_type = :topic
+ end
+
+ def validate_type_integrity
+ if topic?
+ errors.add(:topic_id, :blank) if topic_id.blank?
+ else
+ errors.add(:title, :blank) if title.blank?
+ errors.add(:topic_id, :present) if topic_id.present?
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_kanban_cards
+#
+# id :bigint not null, primary key
+# assigned_to_type :string
+# card_type :integer default("floater"), not null
+# column_changed_at :datetime not null
+# due_at :datetime
+# inline_onebox_data :jsonb
+# notes :text
+# position :bigint default(0), not null
+# tag_ids :integer default([]), not null, is an Array
+# title :string
+# created_at :datetime not null
+# updated_at :datetime not null
+# assigned_to_id :bigint
+# board_id :bigint not null
+# column_id :bigint
+# created_by_id :bigint
+# topic_id :bigint
+# updated_by_id :bigint
+#
+# Indexes
+#
+# idx_kanban_cards_assigned_to (assigned_to_type,assigned_to_id)
+# idx_kanban_cards_board_column_position (board_id,column_id,position)
+# idx_kanban_cards_board_id (board_id)
+# idx_kanban_cards_column_id (column_id)
+# idx_kanban_cards_topic_id (topic_id)
+# idx_kanban_cards_unique_topic_per_column (board_id,column_id,topic_id) UNIQUE WHERE ((topic_id IS NOT NULL) AND (column_id IS NOT NULL))
+#
+# Foreign Keys
+#
+# fk_rails_... (board_id => discourse_kanban_boards.id) ON DELETE => cascade
+# fk_rails_... (column_id => discourse_kanban_columns.id) ON DELETE => nullify
+# fk_rails_... (topic_id => topics.id) ON DELETE => cascade
+#
diff --git a/plugins/boards/app/models/boards/card_history.rb b/plugins/boards/app/models/boards/card_history.rb
new file mode 100644
index 00000000000..5c9e65fe1de
--- /dev/null
+++ b/plugins/boards/app/models/boards/card_history.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module Boards
+ class CardHistory < ActiveRecord::Base
+ self.table_name = "discourse_kanban_card_histories"
+
+ belongs_to :card, class_name: "Boards::Card"
+ belongs_to :board, class_name: "Boards::Board"
+ belongs_to :acting_user, class_name: "User"
+
+ validates :action, presence: true
+ validates :acting_user_id, presence: true
+ validates :board_id, presence: true
+ validates :card_id, presence: true
+
+ enum :action,
+ {
+ card_created: 1,
+ card_edited: 2,
+ card_moved: 3,
+ card_assigned: 4,
+ card_unassigned: 5,
+ card_deleted: 6,
+ card_viewed: 7,
+ }
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_kanban_card_histories
+#
+# id :bigint not null, primary key
+# action :integer not null
+# details :jsonb
+# created_at :datetime not null
+# updated_at :datetime not null
+# acting_user_id :bigint not null
+# board_id :bigint not null
+# card_id :bigint not null
+#
+# Indexes
+#
+# index_discourse_kanban_card_histories_on_acting_user_id (acting_user_id)
+# index_discourse_kanban_card_histories_on_board_id_and_card_id (board_id,card_id)
+# index_discourse_kanban_card_histories_one_view_per_user_day (board_id, card_id, acting_user_id, ((created_at)::date)) UNIQUE WHERE (action = 7)
+#
diff --git a/plugins/boards/app/models/boards/column.rb b/plugins/boards/app/models/boards/column.rb
new file mode 100644
index 00000000000..5ec70210793
--- /dev/null
+++ b/plugins/boards/app/models/boards/column.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+module Boards
+ class Column < ActiveRecord::Base
+ self.table_name = "discourse_kanban_columns"
+ self.ignored_columns = %w[wip_limit filter_query move_to_tag]
+
+ belongs_to :board, class_name: "Boards::Board", inverse_of: :columns
+ belongs_to :move_to_category, class_name: "Category", optional: true
+ belongs_to :tag, optional: true
+ has_many :cards, class_name: "Boards::Card", dependent: :nullify, inverse_of: :column
+ has_many :history,
+ ->(column) { where(board_id: column.board_id).order(created_at: :asc) },
+ class_name: "Boards::BoardHistory",
+ inverse_of: :column
+
+ enum :default_sort, { priority: 0, recency: 1 }, default: :priority
+
+ validates :title, presence: true
+ validates :position, presence: true
+ # Stored as a bare hex (no leading "#"), like core's category color. The
+ # palette presets live in JS; here we only validate the shape.
+ validates :color, format: { with: /\A(\h{3}|\h{6})\z/ }, allow_nil: true
+
+ def matches_topic?(topic)
+ tag_id.present? && topic.tag_ids.include?(tag_id)
+ end
+
+ def unicode_title
+ Emoji.gsub_emoji_to_unicode(title)
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_kanban_columns
+#
+# id :bigint not null, primary key
+# color :string
+# default_sort :integer default("priority"), not null
+# icon :string
+# move_to_assigned :string
+# move_to_status :string
+# position :integer default(0), not null
+# title :string not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# board_id :bigint not null
+# move_to_category_id :bigint
+# tag_id :integer
+#
+# Indexes
+#
+# idx_kanban_columns_board_id (board_id)
+# idx_kanban_columns_board_position (board_id,position)
+# idx_kanban_columns_tag_id (tag_id)
+#
+# Foreign Keys
+#
+# fk_rails_... (board_id => discourse_kanban_boards.id) ON DELETE => cascade
+# fk_rails_... (move_to_category_id => categories.id) ON DELETE => nullify
+#
diff --git a/plugins/boards/app/serializers/boards/basic_board_serializer.rb b/plugins/boards/app/serializers/boards/basic_board_serializer.rb
new file mode 100644
index 00000000000..5c63a90b01c
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/basic_board_serializer.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module Boards
+ class BasicBoardSerializer < ApplicationSerializer
+ attributes :id, :unicode_name, :slug, :columns, :topic_is_member?
+
+ def columns
+ object.columns.map do |column|
+ BasicColumnSerializer.new(
+ column,
+ root: false,
+ scope:,
+ board_memberships: @options[:board_memberships],
+ ).as_json
+ end
+ end
+
+ def include_topic_is_member?
+ @options[:board_memberships].present?
+ end
+
+ def topic_is_member?
+ @options[:board_memberships].map { |membership| membership.board_id }.include?(object.id)
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/basic_column_serializer.rb b/plugins/boards/app/serializers/boards/basic_column_serializer.rb
new file mode 100644
index 00000000000..4eb2b1ceb1a
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/basic_column_serializer.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module Boards
+ class BasicColumnSerializer < ApplicationSerializer
+ attributes :id, :unicode_title, :icon, :color, :topic_is_member?, :topic_card_id
+
+ def include_topic_is_member?
+ @options[:board_memberships].present?
+ end
+
+ def topic_is_member?
+ @options[:board_memberships].map { |membership| membership.column_id }.include?(object.id)
+ end
+
+ def topic_card_id
+ @options[:board_memberships].find { |membership| membership.column_id == object.id }&.id
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/board_serializer.rb b/plugins/boards/app/serializers/boards/board_serializer.rb
new file mode 100644
index 00000000000..9e1483a1861
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/board_serializer.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+module Boards
+ class BoardSerializer < ApplicationSerializer
+ attributes :id,
+ :name,
+ :unicode_name,
+ :slug,
+ :category_ids,
+ :tag_ids,
+ :tag_names,
+ :anonymous_can_read,
+ :require_confirmation,
+ :show_tags,
+ :card_style,
+ :show_topic_thumbnail,
+ :can_write,
+ :can_manage,
+ :created_by,
+ :columns,
+ :acl
+
+ def tag_ids
+ visible_tag_ids
+ end
+
+ def tag_names
+ visible_tag_ids.filter_map { |id| tag_name_map[id] }.sort
+ end
+
+ def anonymous_can_read
+ object.anonymous_can_read?
+ end
+
+ def can_write
+ scope.can_write_boards_board?(object)
+ end
+
+ def can_manage
+ scope.can_manage_boards_board?(object)
+ end
+
+ def created_by
+ return nil if object.created_by.blank?
+
+ { username: object.created_by.username, avatar_template: object.created_by.avatar_template }
+ end
+
+ def columns
+ object.columns.map do |column|
+ ColumnSerializer.new(column, root: false, scope:, tag_name_map:).as_json
+ end
+ end
+
+ def acl
+ @options[:include_acl] ? AccessControlList.where(target: object).flattened_list : nil
+ end
+
+ private
+
+ def visible_tag_ids
+ @visible_tag_ids ||= object.tag_ids.select { |tag_id| tag_name_map.key?(tag_id) }
+ end
+
+ def tag_name_map
+ @options[:tag_name_map] || {}
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/card_serializer.rb b/plugins/boards/app/serializers/boards/card_serializer.rb
new file mode 100644
index 00000000000..ba3229923f4
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/card_serializer.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+module Boards
+ class CardSerializer < ApplicationSerializer
+ attributes :id,
+ :board_id,
+ :column_id,
+ :card_type,
+ :position,
+ :title,
+ :unicode_title,
+ :inline_onebox_data,
+ :notes,
+ :tag_ids,
+ :tags,
+ :topic_id,
+ :created_at,
+ :updated_at,
+ :column_changed_at,
+ :recency_at,
+ :created_by,
+ :assigned_to
+
+ has_one :topic, serializer: CardTopicSerializer, embed: :objects
+ has_many :tags, embed: :object, serializer: CardTagSerializer
+
+ def include_topic_id?
+ object.topic?
+ end
+
+ def include_topic?
+ object.topic? && object.topic.present? && topic_visible?
+ end
+
+ def include_created_at?
+ !object.topic?
+ end
+
+ def tag_ids
+ return [] unless SiteSetting.tagging_enabled
+
+ object.topic? ? [] : ordered_tags.map(&:id)
+ end
+
+ def tags
+ object.topic? ? [] : ordered_tags
+ end
+
+ def created_by
+ { username: object.created_by.username }
+ end
+
+ def include_created_by?
+ !object.topic? && object.created_by.present?
+ end
+
+ def assigned_to
+ case object.assigned_to
+ when User
+ {
+ type: "User",
+ username: object.assigned_to.username,
+ avatar_template: object.assigned_to.avatar_template,
+ }
+ when Group
+ { type: "Group", name: object.assigned_to.name }
+ end
+ end
+
+ def include_assigned_to?
+ !object.topic? && object.assigned_to.present?
+ end
+
+ private
+
+ def ordered_tags
+ return [] unless SiteSetting.tagging_enabled
+
+ tag_ids = visible_tag_ids(object.tag_ids)
+ tags_by_id = @options[:tags_by_id]
+ return Card.ordered_tags(tag_ids) if tags_by_id.blank?
+
+ tag_ids.filter_map { |tag_id| tags_by_id[tag_id] }
+ end
+
+ def visible_tag_ids(tag_ids)
+ normalized_tag_ids = Array(tag_ids).compact_blank.map(&:to_i).reject(&:zero?).uniq
+ guardian = scope || Guardian.new
+ return normalized_tag_ids if normalized_tag_ids.blank? || guardian.is_admin?
+
+ visible_ids = DiscourseTagging.visible_tags(guardian).where(id: normalized_tag_ids).pluck(:id)
+ normalized_tag_ids & visible_ids
+ end
+
+ def topic_visible?
+ scope.present? && scope.can_see?(object.topic)
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/card_tag_serializer.rb b/plugins/boards/app/serializers/boards/card_tag_serializer.rb
new file mode 100644
index 00000000000..cbd94e07bf2
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/card_tag_serializer.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module Boards
+ class CardTagSerializer < ApplicationSerializer
+ attributes :id, :name, :slug
+
+ def slug
+ object.slug_for_url
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/card_topic_serializer.rb b/plugins/boards/app/serializers/boards/card_topic_serializer.rb
new file mode 100644
index 00000000000..0976f1e657c
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/card_topic_serializer.rb
@@ -0,0 +1,142 @@
+# frozen_string_literal: true
+
+module Boards
+ class CardTopicSerializer < ApplicationSerializer
+ attributes :id,
+ :title,
+ :unicode_title,
+ :slug,
+ :category_id,
+ :tags,
+ :bumped_at,
+ :closed,
+ :image_url,
+ :posts_count,
+ :highest_post_number,
+ :last_read_post_number
+
+ attribute :last_poster
+ attribute :assigned_to_user
+ attribute :assigned_to_group
+ attribute :all_assigned_users
+ attribute :assignments
+
+ def unicode_title
+ Emoji.gsub_emoji_to_unicode(object.title)
+ end
+
+ def tags
+ object.tags.map(&:name)
+ end
+
+ def highest_post_number
+ (scope.is_whisperer? && object.highest_staff_post_number) || object.highest_post_number
+ end
+
+ def last_read_post_number
+ topic_user&.last_read_post_number
+ end
+
+ def include_last_read_post_number?
+ topic_user.present?
+ end
+
+ def last_poster
+ poster = object.last_poster
+ { username: poster.username, avatar_template: poster.avatar_template }
+ end
+
+ def include_last_poster?
+ object.last_poster.present?
+ end
+
+ def assigned_to_user
+ assigned = object.assignment.assigned_to
+ { username: assigned.username, avatar_template: assigned.avatar_template }
+ end
+
+ def include_assigned_to_user?
+ assignment_metadata_visible? && object.respond_to?(:assignment) &&
+ object.assignment&.assigned_to.is_a?(User)
+ end
+
+ def assigned_to_group
+ group = object.assignment.assigned_to
+ { name: group.name }
+ end
+
+ def include_assigned_to_group?
+ assignment_metadata_visible? && object.respond_to?(:assignment) &&
+ object.assignment&.assigned_to.is_a?(Group)
+ end
+
+ def all_assigned_users
+ @all_assigned_users ||=
+ topic_assignments.filter_map { |a| serialize_user(a.assigned_to) }.uniq { |u| u[:username] }
+ end
+
+ def include_all_assigned_users?
+ all_assigned_users.present?
+ end
+
+ def assignments
+ topic_assignments.filter_map { |a| serialize_assignment(a) }
+ end
+
+ def include_assignments?
+ assignments.present?
+ end
+
+ private
+
+ def topic_user
+ @topic_user ||= @options.fetch(:topic_users_by_topic, {})[object.id]
+ end
+
+ def topic_assignments
+ return [] if !assignment_metadata_visible?
+
+ assignments =
+ @options.fetch(:assignments_by_topic, {}).fetch(object.id, nil) || fallback_assignments
+ assignments.select { |assignment| assignment_target_visible?(assignment) }
+ end
+
+ def fallback_assignments
+ return [] unless defined?(Assignment)
+ Assignment.active.where(topic_id: object.id).includes(:assigned_to, :target)
+ end
+
+ def assignment_metadata_visible?
+ return false unless defined?(Assignment)
+
+ SiteSetting.assigns_public || (scope.respond_to?(:can_assign?) && scope.can_assign?(object))
+ end
+
+ def assignment_target_visible?(assignment)
+ return true if assignment.target_type != "Post"
+
+ assignment.target.present? && scope.present? && scope.can_see?(assignment.target)
+ end
+
+ def serialize_user(user)
+ return unless user.is_a?(User)
+ { username: user.username, avatar_template: user.avatar_template }
+ end
+
+ def serialize_assignment(assignment)
+ assignee = assignment.assigned_to
+ result = { target_type: assignment.target_type, target_id: assignment.target_id }
+
+ if assignee.is_a?(User)
+ result[:username] = assignee.username
+ result[:avatar_template] = assignee.avatar_template
+ elsif assignee.is_a?(Group)
+ result[:group_name] = assignee.name
+ end
+
+ result[:post_number] = assignment.target&.post_number if assignment.target_type == "Post"
+
+ result
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/column_serializer.rb b/plugins/boards/app/serializers/boards/column_serializer.rb
new file mode 100644
index 00000000000..6d351698808
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/column_serializer.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module Boards
+ class ColumnSerializer < ApplicationSerializer
+ attributes :id,
+ :title,
+ :unicode_title,
+ :icon,
+ :position,
+ :default_sort,
+ :tag_id,
+ :tag_name,
+ :move_to_category_id,
+ :move_to_assigned,
+ :move_to_status,
+ :cards,
+ :color
+
+ def tag_id
+ visible_tag_id
+ end
+
+ def tag_name
+ visible_tag_id ? tag_name_map[visible_tag_id] : nil
+ end
+
+ def cards
+ sorted_cards.map do |card|
+ CardSerializer.new(
+ card,
+ root: false,
+ scope:,
+ assignments_by_topic: @options[:assignments_by_topic],
+ topic_users_by_topic: @options[:topic_users_by_topic],
+ tags_by_id: @options[:tags_by_id],
+ ).as_json
+ end
+ end
+
+ def include_cards?
+ @options.key?(:cards_by_column)
+ end
+
+ private
+
+ def visible_tag_id
+ @visible_tag_id ||= (object.tag_id if object.tag_id && tag_name_map.key?(object.tag_id))
+ end
+
+ def sorted_cards
+ cards = cards_by_column[object.id] || []
+
+ if object.recency?
+ cards.sort_by { |card| [card.recency_at || Time.zone.at(0), card.id] }.reverse
+ else
+ cards.sort_by { |card| [card.position, card.id] }
+ end
+ end
+
+ def cards_by_column
+ @options[:cards_by_column] || {}
+ end
+
+ def tag_name_map
+ @options[:tag_name_map] || {}
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/topic_board_membership_card_serializer.rb b/plugins/boards/app/serializers/boards/topic_board_membership_card_serializer.rb
new file mode 100644
index 00000000000..d40622ae84d
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/topic_board_membership_card_serializer.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module Boards
+ class TopicBoardMembershipCardSerializer < ApplicationSerializer
+ attributes :card_id,
+ :column_id,
+ :column_title,
+ :unicode_column_title,
+ :column_color,
+ :column_icon
+
+ def card_id
+ object.id
+ end
+
+ def column
+ object.column
+ end
+
+ def column_id
+ column.id
+ end
+
+ def column_title
+ column.title
+ end
+
+ def unicode_column_title
+ column.unicode_title
+ end
+
+ def column_color
+ column.color
+ end
+
+ def column_icon
+ column.icon
+ end
+ end
+end
diff --git a/plugins/boards/app/serializers/boards/topic_board_membership_serializer.rb b/plugins/boards/app/serializers/boards/topic_board_membership_serializer.rb
new file mode 100644
index 00000000000..493b66c0bfa
--- /dev/null
+++ b/plugins/boards/app/serializers/boards/topic_board_membership_serializer.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module Boards
+ # Takes a Boards::Card based on a topic, used for displaying
+ # each board and column (which is serialized in TopicBoardMembershipCardSerializer)
+ # that a topic card belongs to, which is used to link directly
+ # to the card with `?card=105` at the board URL.
+ class TopicBoardMembershipSerializer < ApplicationSerializer
+ attributes :board_id, :board_name, :unicode_board_name, :board_slug, :cards
+
+ def board_id
+ board.id
+ end
+
+ def board_name
+ board.name
+ end
+
+ def unicode_board_name
+ board.unicode_name
+ end
+
+ def board_slug
+ board.slug
+ end
+
+ def cards
+ object
+ .sort_by { |card| [card.column.position, card.column.id, card.id] }
+ .map { |card| TopicBoardMembershipCardSerializer.new(card, root: false, scope:).as_json }
+ end
+
+ private
+
+ def board
+ object.first.board
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/action/build_topic_board_memberships_map.rb b/plugins/boards/app/services/boards/action/build_topic_board_memberships_map.rb
new file mode 100644
index 00000000000..402fe821fdc
--- /dev/null
+++ b/plugins/boards/app/services/boards/action/build_topic_board_memberships_map.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module Boards
+ module Action
+ class BuildTopicBoardMembershipsMap < Service::ActionBase
+ option :topics
+ option :guardian
+
+ # Returns a hash in the format:
+ #
+ # {
+ # topic_id => {
+ # board_id => [cards]
+ # }
+ # }
+ #
+ # With the board & column details preloaded for
+ # each card.
+ def call
+ cards = cards_query(readable_board_ids).to_a
+
+ cards
+ .group_by(&:topic_id)
+ .transform_values do |topic_cards|
+ topic_cards
+ .group_by(&:board_id)
+ .sort_by do |_, board_cards|
+ [board_cards.first.board.name.downcase, board_cards.first.board_id]
+ end
+ .to_h
+ end
+ end
+
+ private
+
+ def cards_query(readable_board_ids)
+ Boards::Card
+ .topic
+ .with_column
+ .where(topic_id: Array(topics).map(&:id), board_id: readable_board_ids)
+ .includes(:column, :board)
+ end
+
+ def readable_board_ids
+ member_boards = Boards::Board.with_any_acl_permissions(guardian, %w[view edit manage])
+ anonymous_boards = Boards::Board.with_any_acl_permissions(Guardian.new, %w[view])
+
+ member_boards.or(anonymous_boards).pluck(:id).to_set
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/action/card_inline_onebox.rb b/plugins/boards/app/services/boards/action/card_inline_onebox.rb
new file mode 100644
index 00000000000..04ac97e294d
--- /dev/null
+++ b/plugins/boards/app/services/boards/action/card_inline_onebox.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module Boards
+ module Action
+ class CardInlineOnebox < Service::ActionBase
+ option :title
+
+ def call
+ url = exact_url
+ return if url.blank?
+
+ onebox = InlineOneboxer.lookup(url, invalidate: true)&.with_indifferent_access
+ return if onebox&.dig(:title).blank?
+
+ onebox.to_h.deep_stringify_keys
+ rescue StandardError => error
+ Rails.logger.warn("Boards: failed to inline onebox card title: #{error.message}")
+ nil
+ end
+
+ private
+
+ def exact_url
+ value = title.to_s.strip
+ return if value.blank? || value.match?(/\s/)
+
+ uri = URI.parse(value)
+ return if uri.scheme&.downcase != "https" || uri.host.blank?
+
+ value
+ rescue URI::InvalidURIError
+ nil
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/card_ordering.rb b/plugins/boards/app/services/boards/card_ordering.rb
new file mode 100644
index 00000000000..fa83cc556b7
--- /dev/null
+++ b/plugins/boards/app/services/boards/card_ordering.rb
@@ -0,0 +1,133 @@
+# frozen_string_literal: true
+
+module Boards
+ class CardOrdering
+ GAP_SIZE = 65_536
+
+ def self.place_card!(card, column:, after_card_id: nil, position_first: false)
+ if same_column_recency_reorder?(card, column, after_card_id, position_first)
+ raise_recency_reorder_error!
+ end
+
+ if column.recency? && !card.new_record? && card.column_id == column.id
+ card.save!
+ return card
+ end
+
+ card.transaction do
+ scope = card.board.cards.with_column.where(column_id: column.id).where.not(id: card.id)
+
+ position =
+ if column.recency?
+ insert_at_beginning(scope)
+ else
+ compute_position(scope, after_card_id:, position_first:)
+ end
+
+ if position.nil?
+ rebalance_column!(card.board, column)
+ position = compute_position(scope, after_card_id:, position_first:)
+ end
+
+ stamp_column_changed_at!(card, column)
+ card.column_id = column.id
+ card.position = position
+ card.save!
+ end
+ end
+
+ def self.append_to_column!(card, column)
+ scope = card.board.cards.with_column.where(column_id: column.id)
+ next_position =
+ if column.recency?
+ insert_at_beginning(scope)
+ else
+ scope.maximum(:position).to_i + GAP_SIZE
+ end
+
+ stamp_column_changed_at!(card, column)
+ card.column_id = column.id
+ card.position = next_position
+ card
+ end
+
+ def self.compute_position(scope, after_card_id:, position_first:)
+ if after_card_id.present?
+ insert_after_card(scope, after_card_id)
+ elsif position_first
+ insert_at_beginning(scope)
+ else
+ insert_at_end(scope)
+ end
+ end
+ private_class_method :compute_position
+
+ def self.same_column_recency_reorder?(card, column, after_card_id, position_first)
+ column.recency? && !card.new_record? && card.column_id == column.id &&
+ (after_card_id.present? || position_first)
+ end
+ private_class_method :same_column_recency_reorder?
+
+ def self.raise_recency_reorder_error!
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.cannot_reorder_recency_column"))
+ end
+ private_class_method :raise_recency_reorder_error!
+
+ def self.stamp_column_changed_at!(card, column)
+ return unless card.new_record? || card.column_id != column.id || card.column_changed_at.blank?
+
+ card.column_changed_at = Time.current
+ end
+ private_class_method :stamp_column_changed_at!
+
+ def self.insert_after_card(scope, after_card_id)
+ anchor = scope.find_by(id: after_card_id)
+ return insert_at_end(scope) if anchor.nil?
+
+ neighbor =
+ scope
+ .where(
+ "position > :pos OR (position = :pos AND id > :id)",
+ pos: anchor.position,
+ id: anchor.id,
+ )
+ .order(:position, :id)
+ .pick(:position)
+
+ if neighbor.nil?
+ anchor.position + GAP_SIZE
+ else
+ gap = neighbor - anchor.position
+ return nil if gap <= 1
+ anchor.position + gap / 2
+ end
+ end
+ private_class_method :insert_after_card
+
+ def self.insert_at_beginning(scope)
+ first_pos = scope.order(:position, :id).pick(:position)
+ return 0 if first_pos.nil?
+ first_pos - GAP_SIZE
+ end
+ private_class_method :insert_at_beginning
+
+ def self.insert_at_end(scope)
+ max_pos = scope.maximum(:position)
+ return 0 if max_pos.nil?
+ max_pos + GAP_SIZE
+ end
+ private_class_method :insert_at_end
+
+ def self.rebalance_column!(board, column)
+ card_ids =
+ board.cards.with_column.where(column_id: column.id).order(:position, :id).pluck(:id)
+
+ return if card_ids.empty?
+
+ whens = card_ids.map.with_index { |id, i| "WHEN #{id} THEN #{i * GAP_SIZE}" }.join(" ")
+
+ Card.where(id: card_ids).update_all("position = CASE id #{whens} END")
+ end
+ private_class_method :rebalance_column!
+ end
+end
diff --git a/plugins/boards/app/services/boards/check_board_topic_constraint_mismatches.rb b/plugins/boards/app/services/boards/check_board_topic_constraint_mismatches.rb
new file mode 100644
index 00000000000..9053f83291a
--- /dev/null
+++ b/plugins/boards/app/services/boards/check_board_topic_constraint_mismatches.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module Boards
+ class CheckBoardTopicConstraintMismatches
+ include Service::Base
+
+ params do
+ attribute :id, :integer
+ attribute :topic_id, :integer
+ attribute :target_column_id, :integer
+
+ validates :id, presence: true
+ validates :topic_id, presence: true
+ validates :target_column_id, presence: true
+ end
+
+ model :board
+ policy :can_edit_board
+ model :topic
+ policy :can_view_topic
+ model :target_column
+ model :categories_needed, optional: true
+ model :tags_needed, optional: true
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.id)
+ end
+
+ def can_edit_board(board:, guardian:)
+ guardian.can_write_boards_board?(board)
+ end
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def can_view_topic(topic:, guardian:)
+ guardian.can_see?(topic)
+ end
+
+ def fetch_target_column(params:, board:)
+ board.columns.find_by(id: params.target_column_id)
+ end
+
+ # If the column's category (or the topic's current category) is outside the board's
+ # categories, return the board categories so the user can choose a replacement.
+ def fetch_categories_needed(topic:, target_column:, board:)
+ return [] if board.category_ids.empty?
+
+ effective_category_id = target_column.move_to_category_id || topic.category_id
+ return [] if board.category_ids.include?(effective_category_id)
+
+ board.category_ids
+ end
+
+ # If none of the effective tags belong to the board, return its tags so the user can
+ # choose a replacement.
+ def fetch_tags_needed(topic:, target_column:, board:, guardian:)
+ return [] if board.tag_ids.empty?
+
+ effective_tag_ids = topic.tag_ids.dup
+
+ # A topic should only have the tag for its new column. Remove tags from the other
+ # columns, including every column tag when the target column is untagged.
+ sibling_tag_ids =
+ board.columns.filter_map { |column| column.tag_id if column.id != target_column.id }
+ effective_tag_ids -= sibling_tag_ids
+
+ if target_column.tag_id.present? && effective_tag_ids.exclude?(target_column.tag_id)
+ effective_tag_ids << target_column.tag_id
+ end
+
+ return [] if (board.tag_ids & effective_tag_ids).any?
+
+ Tag.visible(guardian).where(id: board.tag_ids).order(:name).pluck(:name)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/clear_column.rb b/plugins/boards/app/services/boards/clear_column.rb
new file mode 100644
index 00000000000..28d224a46c2
--- /dev/null
+++ b/plugins/boards/app/services/boards/clear_column.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module Boards
+ class ClearColumn
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :column_id, :integer
+
+ validates :board_id, presence: true
+ validates :column_id, presence: true
+ end
+
+ model :board
+ policy :can_write
+ model :column
+ step :clear
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_write(board:, guardian:)
+ guardian.can_write_boards_board?(board)
+ end
+
+ def fetch_column(board:, params:)
+ board.columns.find_by(id: params.column_id)
+ end
+
+ def clear(board:, column:, guardian:)
+ cards = clearable_cards(board, column, guardian)
+
+ remove_column_tag_from_topics(cards, column, guardian)
+
+ cards.delete_all
+ end
+
+ def clearable_cards(board, column, guardian)
+ cards = Card.where(board_id: board.id, column_id: column.id)
+ visible_topic_ids =
+ Topic
+ .listable_topics
+ .secured(guardian)
+ .where(id: cards.where(card_type: :topic).where.not(topic_id: nil).select(:topic_id))
+ .where.not(id: Category.where.not(topic_id: nil).select(:topic_id))
+ .select(:id)
+
+ cards.where(card_type: :floater).or(
+ cards.where(card_type: :topic, topic_id: visible_topic_ids),
+ )
+ end
+
+ def remove_column_tag_from_topics(cards, column, guardian)
+ return if column.tag_id.blank?
+
+ tag = Tag.find_by(id: column.tag_id)
+ return if tag.blank?
+
+ topic_ids = cards.where(card_type: :topic).where.not(topic_id: nil).pluck(:topic_id)
+ return if topic_ids.empty?
+
+ Topic
+ .where(id: topic_ids)
+ .includes(:tags)
+ .find_each do |topic|
+ next unless guardian.can_edit?(topic)
+ updated_tags = topic.tags.map(&:name) - [tag.name]
+ DiscourseTagging.tag_topic_by_names(topic, guardian, updated_tags)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/column_mutator.rb b/plugins/boards/app/services/boards/column_mutator.rb
new file mode 100644
index 00000000000..fec1ed08df6
--- /dev/null
+++ b/plugins/boards/app/services/boards/column_mutator.rb
@@ -0,0 +1,87 @@
+# frozen_string_literal: true
+
+module Boards
+ class ColumnMutator
+ def self.apply!(column:, attributes:, guardian:, position: column.position)
+ payload = attributes.with_indifferent_access
+ previous_tag_id = column.tag_id
+ resolved_tag_id = resolve_tag_id(payload, guardian)
+ ensure_tag_is_unique!(column:, tag_id: resolved_tag_id, tag_name: payload[:tag_name])
+
+ column.assign_attributes(
+ title: payload[:title],
+ icon: payload[:icon],
+ tag_id: resolved_tag_id,
+ default_sort: normalize_default_sort(payload[:default_sort]),
+ move_to_category_id: payload[:move_to_category_id],
+ move_to_assigned: payload[:move_to_assigned],
+ move_to_status: payload[:move_to_status],
+ color: payload[:color],
+ position:,
+ )
+ column.save!
+
+ if previous_tag_id != column.tag_id
+ enforce_loose_card_tags!(column.board, [[column.id, previous_tag_id]])
+ end
+
+ column
+ end
+
+ def self.destroy!(column:)
+ board = column.board
+ board.cards.where(column_id: column.id).delete_all
+ column.destroy!
+ compact_positions!(board)
+ end
+
+ def self.enforce_loose_card_tags!(board, column_tag_changes)
+ return if column_tag_changes.empty?
+
+ board.columns.reset
+ previous_tag_ids_by_column_id = column_tag_changes.to_h
+ board.columns.find_each do |column|
+ LooseCardTagMutator.apply_to_column!(
+ column:,
+ remove_tag_ids: [previous_tag_ids_by_column_id[column.id]],
+ )
+ end
+ end
+
+ def self.normalize_default_sort(value)
+ sort = value.presence || "priority"
+ sort = sort.to_s
+ return sort if Column.default_sorts.key?(sort)
+
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.invalid_column_sort", sort: sort),
+ )
+ end
+
+ def self.resolve_tag_id(payload, guardian)
+ tag_name = payload[:tag_name].presence
+ tag_name ? VisibleTagResolver.resolve_name!(tag_name, guardian:) : nil
+ end
+ private_class_method :resolve_tag_id
+
+ def self.ensure_tag_is_unique!(column:, tag_id:, tag_name:)
+ return if tag_id.blank?
+ return if column.board.columns.where(tag_id:).where.not(id: column.id).empty?
+
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.cannot_use_same_tag_multiple_times", tag_name: tag_name),
+ )
+ end
+ private_class_method :ensure_tag_is_unique!
+
+ def self.compact_positions!(board)
+ board
+ .columns
+ .order(:position, :id)
+ .each_with_index do |column, index|
+ column.update!(position: index) if column.position != index
+ end
+ end
+ private_class_method :compact_positions!
+ end
+end
diff --git a/plugins/boards/app/services/boards/column_tag_resolver.rb b/plugins/boards/app/services/boards/column_tag_resolver.rb
new file mode 100644
index 00000000000..1ce0a827d74
--- /dev/null
+++ b/plugins/boards/app/services/boards/column_tag_resolver.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module Boards
+ module ColumnTagResolver
+ def self.resolve_tag_ids(current_tag_ids:, column:)
+ current_tag_ids = existing_tag_ids(normalize_tag_ids(current_tag_ids))
+ board_column_tag_ids =
+ existing_tag_ids(column.board.columns.filter_map { |c| c.tag_id.presence }.uniq)
+
+ if column.tag_id.present?
+ return current_tag_ids if board_column_tag_ids.exclude?(column.tag_id)
+
+ sibling_tag_ids = board_column_tag_ids - [column.tag_id]
+ (current_tag_ids - sibling_tag_ids + [column.tag_id]).uniq
+ else
+ current_tag_ids - board_column_tag_ids
+ end
+ end
+
+ def self.normalize_tag_ids(values)
+ Array(values).compact_blank.map { |value| Integer(value) }.reject(&:zero?).uniq
+ rescue ArgumentError, TypeError
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_ids", tag_ids: Array(values).join(",")),
+ )
+ end
+
+ def self.existing_tag_ids(tag_ids)
+ return [] if tag_ids.empty?
+
+ Tag.where(id: tag_ids).pluck(:id)
+ end
+ private_class_method :existing_tag_ids
+ end
+end
diff --git a/plugins/boards/app/services/boards/columns_replacer.rb b/plugins/boards/app/services/boards/columns_replacer.rb
new file mode 100644
index 00000000000..90406bb8db9
--- /dev/null
+++ b/plugins/boards/app/services/boards/columns_replacer.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+module Boards
+ class ColumnsReplacer
+ def self.replace!(board:, columns_payload:, user:, guardian: user.guardian)
+ Board.transaction do
+ current_columns = board.columns.index_by(&:id)
+ kept_column_ids = []
+ used_tag_ids = []
+
+ columns_needing_loose_card_tag_enforcement = []
+
+ Array(columns_payload).each_with_index do |raw_col, index|
+ col_payload = raw_col.with_indifferent_access
+ id = col_payload[:id].presence&.to_i
+ column = id && current_columns[id] ? current_columns[id] : board.columns.build
+
+ tag_name = col_payload[:tag_name].presence
+ resolved_tag_id = nil
+ if tag_name
+ resolved_tag_id = VisibleTagResolver.resolve_name!(tag_name, guardian:)
+ if used_tag_ids.include?(resolved_tag_id)
+ raise Discourse::InvalidParameters.new(
+ I18n.t(
+ "boards.errors.cannot_use_same_tag_multiple_times",
+ tag_name: tag_name,
+ ),
+ )
+ end
+ used_tag_ids << resolved_tag_id
+ end
+
+ previous_tag_id = column.tag_id
+
+ column.assign_attributes(
+ title: col_payload[:title],
+ icon: col_payload[:icon],
+ color: col_payload[:color].presence,
+ tag_id: resolved_tag_id,
+ default_sort: normalize_default_sort(col_payload[:default_sort]),
+ move_to_category_id: col_payload[:move_to_category_id],
+ move_to_assigned: col_payload[:move_to_assigned],
+ move_to_status: col_payload[:move_to_status],
+ position: index,
+ )
+
+ column.save!
+ if previous_tag_id != column.tag_id
+ columns_needing_loose_card_tag_enforcement << [column.id, previous_tag_id]
+ end
+ kept_column_ids << column.id
+ end
+
+ removed_columns = board.columns.where.not(id: kept_column_ids)
+ removed_column_ids = removed_columns.pluck(:id)
+
+ board.cards.where(column_id: removed_column_ids).delete_all if removed_column_ids.present?
+
+ removed_columns.delete_all
+
+ enforce_loose_card_tags!(board, columns_needing_loose_card_tag_enforcement)
+ end
+ end
+
+ def self.enforce_loose_card_tags!(board, column_tag_changes)
+ return if column_tag_changes.empty?
+
+ board.columns.reset
+ previous_tag_ids_by_column_id = column_tag_changes.to_h
+ board.columns.find_each do |column|
+ LooseCardTagMutator.apply_to_column!(
+ column:,
+ remove_tag_ids: [previous_tag_ids_by_column_id[column.id]],
+ )
+ end
+ end
+
+ def self.normalize_default_sort(value)
+ sort = value.presence || "priority"
+ sort = sort.to_s
+ return sort if Column.default_sorts.key?(sort)
+
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.invalid_column_sort", sort: sort),
+ )
+ end
+ private_class_method :normalize_default_sort, :enforce_loose_card_tags!
+ end
+end
diff --git a/plugins/boards/app/services/boards/constraint_fixer.rb b/plugins/boards/app/services/boards/constraint_fixer.rb
new file mode 100644
index 00000000000..075a406abf7
--- /dev/null
+++ b/plugins/boards/app/services/boards/constraint_fixer.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module Boards
+ module ConstraintFixer
+ # Validates and applies a constraint_fix hash to make a topic conform to
+ # a board's category/tag constraints. Must be called inside a transaction
+ # when the caller needs atomicity with later writes.
+ #
+ # fix – ActionController::Parameters or Hash with optional keys:
+ # "category_id" (integer) and/or "tag_names" (array of strings)
+ # board, topic, guardian – the usual context objects
+ #
+ def self.apply!(fix:, board:, topic:, guardian:)
+ apply_category_fix!(fix, board, topic, guardian) if fix["category_id"].present?
+ apply_tag_fix!(fix, board, topic, guardian) if fix["tag_names"].present?
+ end
+
+ def self.apply_category_fix!(fix, board, topic, guardian)
+ if board.category_ids.blank?
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+
+ category_id = fix["category_id"].to_i
+ if board.category_ids.exclude?(category_id)
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+
+ category = Category.find_by(id: category_id)
+ raise Discourse::NotFound if category.blank?
+ guardian.ensure_can_edit!(topic)
+ guardian.ensure_can_move_topic_to_category!(category)
+
+ first_post = topic.first_post || topic.posts.with_deleted.order(:post_number).first
+ raise Discourse::NotFound if first_post.blank?
+
+ first_post.revise(
+ guardian.user,
+ { category_id: category.id },
+ { bypass_bump: true, validate_post: false, bypass_rate_limiter: true, skip_revision: true },
+ )
+ topic.reload
+ end
+
+ def self.apply_tag_fix!(fix, board, topic, guardian)
+ if board.tag_ids.blank?
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+
+ board_tag_names = Tag.where(id: board.tag_ids).pluck(:name)
+ requested_tags = Array(fix["tag_names"])
+ unless requested_tags.all? { |t| board_tag_names.include?(t) }
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+
+ guardian.ensure_can_edit_tags!(topic)
+
+ current_tags = topic.tags.map(&:name)
+ updated_tags = (current_tags + requested_tags).uniq
+ DiscourseTagging.tag_topic_by_names(topic, guardian, updated_tags)
+ topic.reload
+ end
+
+ private_class_method :apply_category_fix!, :apply_tag_fix!
+ end
+end
diff --git a/plugins/boards/app/services/boards/create_board.rb b/plugins/boards/app/services/boards/create_board.rb
new file mode 100644
index 00000000000..1a995d1a501
--- /dev/null
+++ b/plugins/boards/app/services/boards/create_board.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+module Boards
+ class CreateBoard
+ include Service::Base
+
+ params do
+ attribute :name, :string
+
+ validates :name, presence: true
+ end
+
+ policy :can_manage
+
+ transaction do
+ model :board, :create_board
+ step :replace_columns
+ step :create_acl
+ step :create_history
+ end
+
+ private
+
+ def can_manage(guardian:)
+ guardian.can_create_boards_board?
+ end
+
+ def create_board(guardian:)
+ raw = context[:raw_board_params]&.dup || {}
+ if raw.key?("tag_names")
+ raw["tag_ids"] = VisibleTagResolver.resolve_names!(raw.delete("tag_names"), guardian:)
+ end
+ board = Board.new(raw.except("columns", "acl"))
+ board.created_by_id = guardian.user.id
+ board.updated_by_id = guardian.user.id
+ board.save!
+ board
+ end
+
+ def replace_columns(board:, guardian:)
+ raw = context[:raw_board_params] || {}
+ ColumnsReplacer.replace!(
+ board:,
+ columns_payload: raw["columns"] || [],
+ user: guardian.user,
+ guardian:,
+ )
+ end
+
+ def create_acl(board:, guardian:)
+ raw = context[:raw_board_params] || {}
+ flattened_acl = raw["acl"] || []
+
+ # TODO (martin) We need to add the current user as Owner here
+ # when we have the user functionality ready for ACLs
+ AccessControlListManager.call(
+ guardian:,
+ params: {
+ target: board,
+ flattened_acl: flattened_acl,
+ owner: Boards::PLUGIN_NAME,
+ },
+ ) do |result|
+ on_failure do
+ Rails.logger.warn(
+ "Failed to create ACL for board #{board.id} (#{flattened_acl.to_json}): #{result.inspect_steps}",
+ )
+ fail!(I18n.t("boards.board.errors.acl_create_failed"))
+ end
+ end
+ end
+
+ def create_history(board:, guardian:)
+ BoardHistory.create!(
+ board:,
+ acting_user: guardian.user,
+ action: BoardHistory.actions[:board_created],
+ )
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/create_card.rb b/plugins/boards/app/services/boards/create_card.rb
new file mode 100644
index 00000000000..e085f0f7611
--- /dev/null
+++ b/plugins/boards/app/services/boards/create_card.rb
@@ -0,0 +1,183 @@
+# frozen_string_literal: true
+
+module Boards
+ class CreateCard
+ include Service::Base
+
+ options { attribute :constraint_fix }
+
+ params do
+ attribute :board_id, :integer
+ attribute :column_id, :integer
+ attribute :topic_id, :integer
+ attribute :title, :string
+ attribute :notes, :string
+ attribute :after_card_id, :integer
+ attribute :assigned_to_name, :string
+ attribute :tag_ids, :array
+ attribute :tag_names, :array
+
+ validates :board_id, presence: true
+ validates :column_id, presence: true
+ end
+
+ model :board
+ policy :can_write
+ model :column
+
+ transaction do
+ step :create_card
+ step :create_card_history
+ end
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_write(board:, guardian:)
+ guardian.can_write_boards_board?(board)
+ end
+
+ def fetch_column(board:, params:)
+ board.columns.find_by(id: params.column_id)
+ end
+
+ def create_card(board:, column:, params:, guardian:, options:)
+ context[:card] = if params.topic_id.present?
+ build_topic_card(board, column, params, guardian, options:)
+ else
+ build_floater_card(board, column, params, guardian)
+ end
+ end
+
+ def create_card_history(card:, guardian:)
+ CardHistory.create!(
+ card:,
+ acting_user: guardian.user,
+ action: CardHistory.actions[:card_created],
+ board_id: card.board_id,
+ )
+ end
+
+ def build_topic_card(board, column, params, guardian, options:)
+ topic = Topic.find_by(id: params.topic_id)
+ raise Discourse::NotFound if topic.nil?
+ raise Discourse::NotFound unless guardian.can_see?(topic)
+ if Category.exists?(topic_id: topic.id)
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.category_definition_topic"))
+ end
+
+ Card.transaction do
+ constraint_fix = options.constraint_fix.presence || context[:constraint_fix]
+
+ if constraint_fix.present?
+ ConstraintFixer.apply!(fix: constraint_fix, board:, topic:, guardian:)
+ end
+
+ unless board.topic_will_match_after_mutation?(topic, column)
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+
+ card = board.cards.find_or_initialize_by(topic_id: topic.id, column_id: column.id)
+ card.card_type = :topic
+ card.updated_by_id = guardian.user.id
+ card.created_by_id ||= guardian.user.id
+
+ if card.new_record?
+ CardOrdering.append_to_column!(card, column)
+ else
+ CardOrdering.place_card!(card, column:, after_card_id: params.after_card_id)
+ end
+
+ card.save!
+ apply_column_mutations!(topic, column, guardian)
+ card
+ end
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid => error
+ unless unique_topic_card_violation?(error) ||
+ board.cards.where(topic_id: topic.id, column_id: column.id).exists?
+ raise
+ end
+
+ card = board.cards.find_by!(topic_id: topic.id, column_id: column.id)
+ card.updated_by_id = guardian.user.id
+ card.created_by_id ||= guardian.user.id
+ CardOrdering.place_card!(card, column:, after_card_id: params.after_card_id)
+ card.save!
+ apply_column_mutations!(topic, column, guardian)
+ card
+ end
+
+ def apply_column_mutations!(topic, column, guardian)
+ if column.tag_id.blank? && column.move_to_category_id.blank? &&
+ column.move_to_assigned.blank? && column.move_to_status.blank?
+ return
+ end
+ return unless guardian.can_edit?(topic)
+ TopicMutator.apply!(topic:, column:, guardian:)
+ end
+
+ def build_floater_card(board, column, params, guardian)
+ tag_ids = resolve_all_tag_ids(params.tag_ids, params.tag_names, guardian)
+ card =
+ board.cards.build(
+ card_type: :floater,
+ title: params.title,
+ notes: params.notes,
+ tag_ids:,
+ assigned_to: resolve_assignee(params.assigned_to_name, guardian),
+ created_by_id: guardian.user.id,
+ updated_by_id: guardian.user.id,
+ )
+
+ LooseCardTagMutator.apply_to_card!(card:, column:)
+ CardOrdering.append_to_column!(card, column)
+ card.save!
+ card
+ end
+
+ def resolve_assignee(name, guardian)
+ return nil if name.blank?
+
+ unless guardian.can_assign?
+ raise Discourse::InvalidAccess.new(I18n.t("boards.errors.cannot_assign"))
+ end
+
+ user = User.find_by_username(name)
+ return user if user&.active
+
+ group = Group.find_by(name: name)
+ return group if group && guardian.can_see_group?(group)
+
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.invalid_assignee", name: name))
+ end
+
+ def unique_topic_card_violation?(error)
+ [error, error.cause, error.cause&.cause].compact.any? do |candidate|
+ candidate.message.include?("idx_kanban_cards_unique_topic_per_column") ||
+ topic_card_constraint_name(candidate) == "idx_kanban_cards_unique_topic_per_column"
+ end
+ end
+
+ def resolve_all_tag_ids(tag_ids, tag_names, guardian)
+ ids = Card.normalize_visible_tag_ids!(tag_ids, guardian)
+ names = Array(tag_names).compact_blank
+ if names.present?
+ tags = DiscourseTagging.find_or_create_tags!(names, guardian)
+ ids = Card.normalize_visible_tag_ids!(ids + tags.map(&:id), guardian)
+ end
+ ids
+ end
+
+ def topic_card_constraint_name(error)
+ return unless defined?(PG::Result)
+ return unless error.respond_to?(:result)
+
+ error.result&.error_field(PG::Result::PG_DIAG_CONSTRAINT_NAME)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/create_column.rb b/plugins/boards/app/services/boards/create_column.rb
new file mode 100644
index 00000000000..346e18387a3
--- /dev/null
+++ b/plugins/boards/app/services/boards/create_column.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+module Boards
+ class CreateColumn
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :title, :string
+ attribute :icon, :string
+ attribute :color, :string
+ attribute :default_sort, :string
+ attribute :tag_name, :string
+ attribute :move_to_category_id, :integer
+ attribute :move_to_assigned, :string
+ attribute :move_to_status, :string
+ attribute :client_id, :string
+
+ validates :board_id, presence: true
+ validates :title, presence: true
+ validates :color, format: { with: /\A(\h{3}|\h{6})\z/ }, allow_nil: true
+ end
+
+ model :board
+ policy :can_manage
+
+ transaction do
+ model :column, :create_column
+ step :create_history
+ end
+
+ step :publish_update
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_manage(guardian:, board:)
+ guardian.can_manage_boards_board?(board)
+ end
+
+ def create_column(board:, params:, guardian:)
+ position = (board.columns.maximum(:position) || -1) + 1
+ ColumnMutator.apply!(
+ column: board.columns.build,
+ attributes: params.to_hash,
+ guardian:,
+ position:,
+ )
+ end
+
+ def create_history(board:, column:, guardian:)
+ BoardHistory.create!(
+ board:,
+ column:,
+ acting_user: guardian.user,
+ action: :column_added,
+ details: column_details(column),
+ )
+ end
+
+ def publish_update(board:, params:)
+ Publisher.publish_board_updated!(board, client_id: params.client_id)
+ end
+
+ def column_details(column)
+ {
+ title: column.title,
+ color: column.color,
+ tag_id: column.tag_id,
+ move_to_category_id: column.move_to_category_id,
+ move_to_assigned: column.move_to_assigned,
+ move_to_status: column.move_to_status,
+ }
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/destroy_board.rb b/plugins/boards/app/services/boards/destroy_board.rb
new file mode 100644
index 00000000000..8d7e6c06936
--- /dev/null
+++ b/plugins/boards/app/services/boards/destroy_board.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module Boards
+ class DestroyBoard
+ include Service::Base
+
+ params do
+ attribute :id, :integer
+ attribute :client_id, :string
+
+ validates :id, presence: true
+ end
+
+ model :board
+ policy :can_destroy
+ step :publish_update
+
+ transaction do
+ step :destroy
+ step :create_history
+ end
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.id)
+ end
+
+ def can_destroy(guardian:, board:)
+ guardian.can_destroy_boards_board?(board)
+ end
+
+ def publish_update(board:, params:)
+ Publisher.publish_board_updated!(board, client_id: params.client_id)
+ end
+
+ def destroy(board:)
+ board.destroy!
+ end
+
+ def create_history(board:, guardian:)
+ BoardHistory.create!(board:, acting_user: guardian.user, action: "board_deleted")
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/destroy_card.rb b/plugins/boards/app/services/boards/destroy_card.rb
new file mode 100644
index 00000000000..4bb47ac5cd4
--- /dev/null
+++ b/plugins/boards/app/services/boards/destroy_card.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+module Boards
+ class DestroyCard
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :id, :integer
+
+ validates :board_id, presence: true
+ validates :id, presence: true
+ end
+
+ model :board
+ policy :can_write
+ model :card
+ policy :can_see_card_topic
+ policy :card_is_deletable
+ step :destroy
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_write(board:, guardian:)
+ guardian.can_write_boards_board?(board)
+ end
+
+ def fetch_card(board:, params:)
+ board.cards.find_by(id: params.id)
+ end
+
+ def can_see_card_topic(card:, guardian:)
+ !card.topic? || card.topic.blank? || guardian.can_see?(card.topic)
+ end
+
+ def card_is_deletable(card:)
+ true
+ end
+
+ def destroy(card:, guardian:)
+ remove_column_tag(card, guardian) if card.topic?
+ card.destroy!
+ end
+
+ def remove_column_tag(card, guardian)
+ column = card.column
+ return if column&.tag_id.blank?
+ topic = card.topic
+ return if topic.blank? || !guardian.can_edit?(topic)
+
+ tag = Tag.find_by(id: column.tag_id)
+ return if tag.blank?
+
+ updated_tags = topic.tags.map(&:name) - [tag.name]
+ DiscourseTagging.tag_topic_by_names(topic, guardian, updated_tags)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/destroy_column.rb b/plugins/boards/app/services/boards/destroy_column.rb
new file mode 100644
index 00000000000..d55cd4a9779
--- /dev/null
+++ b/plugins/boards/app/services/boards/destroy_column.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+module Boards
+ class DestroyColumn
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :id, :integer
+ attribute :client_id, :string
+
+ validates :board_id, presence: true
+ validates :id, presence: true
+ end
+
+ model :board
+ policy :can_manage
+ model :column
+
+ transaction do
+ step :create_history
+ step :destroy_column
+ end
+
+ step :publish_update
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_manage(guardian:, board:)
+ guardian.can_manage_boards_board?(board)
+ end
+
+ def fetch_column(board:, params:)
+ board.columns.find_by(id: params.id)
+ end
+
+ def create_history(board:, column:, guardian:)
+ BoardHistory.create!(
+ board:,
+ column:,
+ acting_user: guardian.user,
+ action: :column_deleted,
+ details: column_details(column),
+ )
+ end
+
+ def destroy_column(column:)
+ ColumnMutator.destroy!(column:)
+ end
+
+ def publish_update(board:, params:)
+ Publisher.publish_board_updated!(board, client_id: params.client_id)
+ end
+
+ def column_details(column)
+ { title: column.title }
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/loose_card_tag_mutator.rb b/plugins/boards/app/services/boards/loose_card_tag_mutator.rb
new file mode 100644
index 00000000000..bd23517560d
--- /dev/null
+++ b/plugins/boards/app/services/boards/loose_card_tag_mutator.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module Boards
+ module LooseCardTagMutator
+ def self.apply_to_card!(card:, column:, remove_tag_ids: [])
+ return unless card.floater?
+
+ tag_ids =
+ ColumnTagResolver.normalize_tag_ids(card.tag_ids) -
+ ColumnTagResolver.normalize_tag_ids(remove_tag_ids)
+ card.tag_ids = ColumnTagResolver.resolve_tag_ids(current_tag_ids: tag_ids, column:)
+ end
+
+ def self.apply_to_column!(column:, remove_tag_ids: [])
+ column
+ .cards
+ .where(card_type: Card.card_types[:floater])
+ .find_each do |card|
+ apply_to_card!(card:, column:, remove_tag_ids:)
+ card.save! if card.changed?
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/move_column.rb b/plugins/boards/app/services/boards/move_column.rb
new file mode 100644
index 00000000000..0382fad33dd
--- /dev/null
+++ b/plugins/boards/app/services/boards/move_column.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+module Boards
+ class MoveColumn
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :column_id, :integer
+ attribute :direction, :integer
+ attribute :client_id, :string
+
+ validates :board_id, presence: true
+ validates :column_id, presence: true
+ validates :direction, presence: true, inclusion: { in: [-1, 1] }
+ end
+
+ model :board
+ policy :can_manage
+ model :column
+
+ transaction { step :swap_positions }
+
+ step :publish_reorder
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_manage(guardian:, board:)
+ guardian.can_manage_boards_board?(board)
+ end
+
+ def fetch_column(board:, params:)
+ board.columns.find_by(id: params.column_id)
+ end
+
+ def swap_positions(board:, column:, params:)
+ ordered = board.columns.order(:position, :id).lock("FOR UPDATE").to_a
+ current_index = ordered.index(column)
+ new_index = current_index + params.direction
+
+ if new_index < 0 || new_index >= ordered.length
+ fail!(I18n.t("boards.errors.column_move_out_of_bounds"))
+ end
+
+ neighbor = ordered[new_index]
+ column.position, neighbor.position = neighbor.position, column.position
+ column.save!
+ neighbor.save!
+
+ context[:column_order] = board.columns.order(:position, :id).pluck(:id)
+ end
+
+ def publish_reorder(board:, params:)
+ Publisher.publish_columns_reordered!(
+ board,
+ context[:column_order],
+ client_id: params.client_id,
+ )
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/move_topic_to_column.rb b/plugins/boards/app/services/boards/move_topic_to_column.rb
new file mode 100644
index 00000000000..684dee65bf8
--- /dev/null
+++ b/plugins/boards/app/services/boards/move_topic_to_column.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+module Boards
+ class MoveTopicToColumn
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :topic_id, :integer
+ attribute :to_column_id, :integer
+ attribute :after_card_id, :integer
+ attribute :client_id, :string
+
+ validates :board_id, presence: true
+ validates :topic_id, presence: true
+ validates :to_column_id, presence: true
+ end
+
+ model :board
+ policy :can_write
+ model :topic
+ policy :can_see_topic
+ policy :can_edit_topic
+ model :column
+ policy :topic_matches_constraints
+
+ transaction do
+ step :apply_topic_mutations
+ model :card, :place_topic_card
+ end
+
+ only_if(:card_newly_created) { step :publish_card_created }
+ only_if(:card_repositioned) { step :publish_card_moved }
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_write(board:, guardian:)
+ guardian.can_write_boards_board?(board)
+ end
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def can_see_topic(topic:, guardian:)
+ guardian.can_see?(topic)
+ end
+
+ def can_edit_topic(topic:, guardian:)
+ guardian.can_edit?(topic)
+ end
+
+ def fetch_column(board:, params:)
+ board.columns.find_by(id: params.to_column_id)
+ end
+
+ def topic_matches_constraints(board:, topic:, column:)
+ board.topic_will_match_after_mutation?(topic, column)
+ end
+
+ def apply_topic_mutations(topic:, column:, guardian:)
+ TopicMutator.apply!(topic:, column:, guardian:)
+ end
+
+ def place_topic_card(board:, topic:, column:, params:, guardian:)
+ card = board.cards.find_or_initialize_by(topic:, column:)
+
+ card.assign_attributes(card_type: :topic, updated_by_id: guardian.user.id)
+ card.created_by_id ||= guardian.user.id
+
+ if card.new_record?
+ CardOrdering.append_to_column!(card, column)
+ card.save!
+ else
+ CardOrdering.place_card!(card, column:, after_card_id: params.after_card_id)
+ end
+
+ card
+ end
+
+ def card_newly_created(card:)
+ card.previously_new_record?
+ end
+
+ def card_repositioned(card:)
+ !card.previously_new_record?
+ end
+
+ def publish_card_created(board:, card:, params:)
+ payload = CardSerializer.new(card, root: false).as_json
+ Publisher.publish_card_created!(board, payload, client_id: params.client_id)
+ end
+
+ def publish_card_moved(board:, card:, params:)
+ payload = CardSerializer.new(card, root: false).as_json
+ Publisher.publish_card_moved!(board, payload, client_id: params.client_id)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/publisher.rb b/plugins/boards/app/services/boards/publisher.rb
new file mode 100644
index 00000000000..33ab3c79287
--- /dev/null
+++ b/plugins/boards/app/services/boards/publisher.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module Boards
+ module Publisher
+ CHANNEL_PREFIX = "/boards"
+
+ def self.publish_card_created!(board, card_payload, client_id:)
+ publish_card_event!(board, "card_created", card_payload, client_id:)
+ end
+
+ def self.publish_card_updated!(board, card_payload, client_id:)
+ publish_card_event!(board, "card_updated", card_payload, client_id:)
+ end
+
+ def self.publish_card_moved!(board, card_payload, client_id:)
+ publish_card_event!(board, "card_moved", card_payload, client_id:)
+ end
+
+ def self.publish_card_deleted!(board, card_id, client_id:)
+ publish!(board, { type: "card_deleted", client_id: client_id, card_id: card_id })
+ end
+
+ def self.publish_column_cleared!(board, column_id, client_id:)
+ publish!(board, { type: "column_cleared", client_id: client_id, column_id: column_id })
+ end
+
+ def self.publish_board_updated!(board, client_id:)
+ publish!(board, { type: "board_updated", client_id: client_id })
+ end
+
+ def self.publish_columns_reordered!(board, column_order, client_id:)
+ publish!(
+ board,
+ { type: "columns_reordered", client_id: client_id, column_order: column_order },
+ )
+ end
+
+ def self.publish_topic_memberships_changed!(topic, client_id:, refresh_stream: false)
+ data = { reload_topic: true, client_id: }
+ data[:refresh_stream] = true if refresh_stream
+
+ MessageBus.publish("/topic/#{topic.id}", data, topic.secure_audience_publish_messages)
+ end
+
+ def self.publish_card_event!(board, type, card_payload, client_id:)
+ # Strip topic data from broadcast payloads to prevent leaking
+ # private topic details to board readers who lack category access.
+ # Clients merge with existing state or refetch through the
+ # authorized show endpoint.
+ safe_payload = card_payload.except("topic", :topic)
+ publish!(board, { type: type, client_id: client_id, card: safe_payload })
+ end
+ private_class_method :publish_card_event!
+
+ def self.publish!(board, data)
+ group_ids = board.permission_acl.group_ids_with_any_permission(%w[view edit manage])
+ opts = {}
+ # Anonymous viewers belong to no group, so a board readable by anonymous
+ # users must broadcast to everyone rather than being group-restricted.
+ if group_ids.present? && !group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])
+ opts[:group_ids] = group_ids
+ end
+
+ MessageBus.publish("#{CHANNEL_PREFIX}/#{board.id}", data, opts)
+ end
+ private_class_method :publish!
+ end
+end
diff --git a/plugins/boards/app/services/boards/topic_board_memberships.rb b/plugins/boards/app/services/boards/topic_board_memberships.rb
new file mode 100644
index 00000000000..b529c20e07a
--- /dev/null
+++ b/plugins/boards/app/services/boards/topic_board_memberships.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module Boards
+ class TopicBoardMemberships
+ include Service::Base
+
+ options { attribute :topics }
+
+ model :cards_map, optional: true
+ model :single_topic_memberships, optional: true
+
+ private
+
+ def fetch_cards_map(options:, guardian:)
+ Action::BuildTopicBoardMembershipsMap.call(topics: options.topics, guardian:)
+ end
+
+ def fetch_single_topic_memberships(options:, cards_map:)
+ return if options.topics.size > 1
+
+ cards_map.fetch(options.topics.first.id, {}).values
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/topic_mutator.rb b/plugins/boards/app/services/boards/topic_mutator.rb
new file mode 100644
index 00000000000..f336bd875c4
--- /dev/null
+++ b/plugins/boards/app/services/boards/topic_mutator.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+module Boards
+ class TopicMutator
+ def self.apply!(topic:, column:, guardian:)
+ return unless mutates_topic?(column)
+
+ user = guardian.user
+ raise Discourse::InvalidAccess.new unless user
+ raise Discourse::InvalidAccess.new unless guardian.can_edit?(topic)
+
+ move_topic_to_category(topic, column, guardian, user)
+ move_topic_tags(topic, column, guardian)
+ move_topic_assignment(topic, column, guardian, user)
+ move_topic_status(topic, column, guardian, user)
+ end
+
+ def self.mutates_topic?(column)
+ return true if column.move_to_category_id.present?
+ return true if column.move_to_status.present?
+ return true if column.move_to_assigned.present?
+ column.board.columns.any? { |c| c.tag_id.present? }
+ end
+
+ def self.move_topic_to_category(topic, column, guardian, user)
+ return if column.move_to_category_id.blank?
+
+ category = Category.find_by(id: column.move_to_category_id)
+ raise Discourse::NotFound.new if category.blank?
+
+ guardian.ensure_can_move_topic_to_category!(category)
+
+ options = {
+ bypass_bump: true,
+ validate_post: false,
+ bypass_rate_limiter: true,
+ skip_revision: true,
+ }
+
+ topic.first_post.revise(user, { category_id: category.id }, options)
+ end
+
+ def self.move_topic_tags(topic, column, guardian)
+ resolved_tag_ids = ColumnTagResolver.resolve_tag_ids(current_tag_ids: topic.tag_ids, column:)
+ return if resolved_tag_ids.sort == topic.tag_ids.sort
+
+ updated_tags = Card.ordered_tags(resolved_tag_ids).map(&:name)
+ DiscourseTagging.tag_topic_by_names(topic, guardian, updated_tags)
+ end
+
+ def self.move_topic_assignment(topic, column, guardian, user)
+ return if column.move_to_assigned.blank?
+ return unless defined?(::Assigner)
+
+ return if column.move_to_assigned == "*"
+
+ validate_assignment_permission!(topic, guardian)
+
+ assigner = ::Assigner.new(topic, user)
+
+ case column.move_to_assigned
+ when "nobody"
+ assigner.unassign
+ topic
+ .posts
+ .joins(:assignment)
+ .where(assignments: { active: true })
+ .find_each { |post| ::Assigner.new(post, user).unassign }
+ else
+ target = User.find_by(username_lower: column.move_to_assigned.downcase)
+ target ||= Group.find_by(name: column.move_to_assigned)
+ assigner.assign(target) if target
+ end
+ end
+
+ def self.move_topic_status(topic, column, guardian, user)
+ return if column.move_to_status.blank?
+
+ enabled = column.move_to_status == "closed"
+ validate_status_permission!(topic, guardian, enabled)
+ topic.update_status("closed", enabled, user)
+ end
+
+ def self.validate_assignment_permission!(topic, guardian)
+ raise Discourse::InvalidAccess.new unless guardian.respond_to?(:can_assign?)
+ raise Discourse::InvalidAccess.new unless guardian.can_assign?(topic)
+ end
+
+ def self.validate_status_permission!(topic, guardian, closing)
+ allowed = closing ? guardian.can_close_topic?(topic) : guardian.can_open_topic?(topic)
+ raise Discourse::InvalidAccess.new unless allowed
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/topic_sync.rb b/plugins/boards/app/services/boards/topic_sync.rb
new file mode 100644
index 00000000000..9082e9d7ecf
--- /dev/null
+++ b/plugins/boards/app/services/boards/topic_sync.rb
@@ -0,0 +1,482 @@
+# frozen_string_literal: true
+
+module Boards
+ class TopicSync
+ MAX_CARDS_PER_COLUMN = 200
+
+ def self.backfill_board(board)
+ return unless SiteSetting.boards_enabled?
+
+ board = Board.includes(:columns).find(board.id) unless board.association(:columns).loaded?
+ columns = board.columns.to_a
+
+ # 1. Build topic-to-columns mapping via simple queries
+ column_topic_ids = build_column_topic_map(board, columns)
+
+ # 2. Build per-topic target columns (tagged = deterministic)
+ catch_all_column_ids = columns.select { |col| col.tag_id.blank? }.map(&:id).to_set
+
+ topic_to_tagged = Hash.new { |h, k| h[k] = Set.new }
+ columns.each do |col|
+ ids = column_topic_ids[col.id] || next
+ ids.each { |tid| topic_to_tagged[tid] << col.id } if col.tag_id.present?
+ end
+
+ # 3. Load all existing topic cards for this board in one query
+ existing_cards =
+ board
+ .cards
+ .where(card_type: :topic)
+ .where.not(topic_id: nil)
+ .pluck(:id, :topic_id, :column_id)
+ existing_by_topic = Hash.new { |h, k| h[k] = [] }
+ existing_cards.each do |card_id, topic_id, column_id|
+ existing_by_topic[topic_id] << { id: card_id, column_id: }
+ end
+
+ # 4. Diff: compute creates and deletes
+ to_create = []
+ to_delete = []
+
+ all_topic_ids = (topic_to_tagged.keys + existing_by_topic.keys).uniq
+
+ all_topic_ids.each do |topic_id|
+ cards = existing_by_topic[topic_id]
+ existing_column_ids = cards.map { |c| c[:column_id] }.to_set
+ tagged_targets = topic_to_tagged[topic_id]
+
+ # Tagged columns: deterministic
+ tagged_targets.each do |col_id|
+ to_create << { topic_id:, column_id: col_id } if existing_column_ids.exclude?(col_id)
+ end
+
+ # Unconstrained columns don't auto-receive cards. Manually-placed
+ # cards in them are only preserved when no tagged column matches.
+ if tagged_targets.empty?
+ valid_columns = catch_all_column_ids
+ else
+ valid_columns = tagged_targets
+ end
+
+ cards.each { |c| to_delete << c[:id] if valid_columns.exclude?(c[:column_id]) }
+ end
+
+ # 5. Apply changes in bulk
+ apply_bulk_changes(board, to_create:, to_delete:)
+ end
+
+ def self.sync_topic(topic)
+ return unless SiteSetting.boards_enabled?
+ return if topic.blank? || !topic.persisted? || topic.deleted_at.present?
+
+ with_topic_sync_retry do
+ Card.transaction do
+ snapshot = fetch_sync_snapshot(topic)
+
+ plan =
+ compute_sync_plan(
+ existing_cards: snapshot[:existing_cards],
+ matching_placements: snapshot[:matching_placements],
+ )
+ next if plan[:remove_card_ids].blank? && plan[:create_targets].blank?
+
+ execute_sync_changes(
+ topic:,
+ plan:,
+ existing_cards: snapshot[:existing_cards],
+ max_positions: snapshot[:max_positions],
+ board_groups: snapshot[:board_groups],
+ )
+ end
+ end
+ end
+
+ def self.remove_topic(topic_id)
+ return unless SiteSetting.boards_enabled?
+
+ rows = DB.query(<<~SQL, topic_id: topic_id)
+ SELECT c.id AS card_id, c.board_id,
+ COALESCE(
+ ARRAY_AGG(DISTINCT acl_group_id) FILTER (WHERE acl_group_id IS NOT NULL),
+ '{}'::bigint[]
+ ) AS allowed_group_ids
+ FROM discourse_kanban_cards c
+ JOIN discourse_kanban_boards b ON b.id = c.board_id
+ LEFT JOIN access_control_lists acl
+ ON acl.target_id = b.id
+ AND acl.target_type = 'Boards::Board'
+ AND acl.permission IN ('view', 'edit', 'manage')
+ LEFT JOIN LATERAL UNNEST(acl.allowed_group_ids) AS acl_groups(acl_group_id) ON TRUE
+ WHERE c.topic_id = :topic_id
+ GROUP BY c.id, c.board_id
+ SQL
+
+ return if rows.empty?
+
+ deleted_by_board = {}
+ board_groups = {}
+ rows.each do |row|
+ (deleted_by_board[row.board_id] ||= []) << row.card_id
+ board_groups[row.board_id] ||= row.allowed_group_ids || []
+ end
+
+ Card.where(topic_id: topic_id).delete_all
+ publish_sync_changes(board_groups:, deleted_by_board:, created_cards: [])
+ end
+
+ def self.fetch_sync_snapshot(topic)
+ sanitized_tag_ids =
+ if topic.tag_ids.present?
+ "{#{topic.tag_ids.map(&:to_i).join(",")}}"
+ else
+ "{}"
+ end
+
+ sql = <<~SQL
+ WITH matching AS (
+ SELECT b.id AS board_id, c.id AS column_id, c.tag_id AS column_tag_id
+ FROM discourse_kanban_boards b
+ JOIN discourse_kanban_columns c ON c.board_id = b.id
+ WHERE (b.category_ids != '{}' OR b.tag_ids != '{}')
+ AND (b.category_ids = '{}' OR :topic_category_id = ANY(b.category_ids))
+ AND (b.tag_ids = '{}' OR b.tag_ids && :topic_tag_ids)
+ AND (c.tag_id IS NULL OR c.tag_id = ANY(:topic_tag_ids))
+ ),
+ max_positions AS (
+ SELECT k.column_id, MAX(k.position) AS max_pos
+ FROM discourse_kanban_cards k
+ WHERE k.column_id IN (SELECT column_id FROM matching)
+ GROUP BY k.column_id
+ ),
+ board_info AS (
+ SELECT b.id AS board_id,
+ COALESCE(
+ ARRAY_AGG(DISTINCT acl_group_id) FILTER (WHERE acl_group_id IS NOT NULL),
+ '{}'::bigint[]
+ ) AS allowed_group_ids
+ FROM discourse_kanban_boards b
+ LEFT JOIN access_control_lists acl
+ ON acl.target_id = b.id
+ AND acl.target_type = 'Boards::Board'
+ AND acl.permission IN ('view', 'edit', 'manage')
+ LEFT JOIN LATERAL UNNEST(acl.allowed_group_ids) AS acl_groups(acl_group_id) ON TRUE
+ WHERE b.id IN (
+ SELECT board_id FROM matching
+ UNION ALL
+ SELECT board_id FROM discourse_kanban_cards WHERE topic_id = :topic_id
+ )
+ GROUP BY b.id
+ )
+ SELECT 'existing'::text AS source, ec.card_id, ec.board_id, ec.column_id,
+ NULL::bigint AS column_tag_id, NULL::bigint AS max_pos,
+ NULL::bigint[] AS allowed_group_ids
+ FROM (
+ SELECT c.id AS card_id, c.board_id, c.column_id
+ FROM discourse_kanban_cards c
+ JOIN discourse_kanban_boards b ON b.id = c.board_id
+ WHERE c.topic_id = :topic_id
+ AND (b.category_ids != '{}' OR b.tag_ids != '{}')
+ FOR UPDATE OF c
+ ) ec
+ UNION ALL
+ SELECT 'matching'::text, NULL, m.board_id, m.column_id,
+ m.column_tag_id, NULL,
+ NULL
+ FROM matching m
+ UNION ALL
+ SELECT 'max_pos'::text, NULL, NULL, mp.column_id,
+ NULL, mp.max_pos,
+ NULL
+ FROM max_positions mp
+ UNION ALL
+ SELECT 'board'::text, NULL, bi.board_id, NULL,
+ NULL, NULL,
+ bi.allowed_group_ids
+ FROM board_info bi
+ SQL
+
+ existing_cards = []
+ matching_placements = []
+ max_positions = {}
+ board_groups = {}
+
+ DB
+ .query(
+ sql,
+ topic_id: topic.id,
+ topic_category_id: topic.category_id.to_i,
+ topic_tag_ids: sanitized_tag_ids,
+ )
+ .each do |row|
+ case row.source
+ when "existing"
+ existing_cards << [row.card_id, row.board_id, row.column_id]
+ when "matching"
+ matching_placements << {
+ board_id: row.board_id,
+ column_id: row.column_id,
+ column_tag_id: row.column_tag_id,
+ }
+ when "max_pos"
+ max_positions[row.column_id] = row.max_pos
+ when "board"
+ board_groups[row.board_id] = row.allowed_group_ids || []
+ end
+ end
+
+ { existing_cards:, matching_placements:, max_positions:, board_groups: }
+ end
+ private_class_method :fetch_sync_snapshot
+
+ def self.compute_sync_plan(existing_cards:, matching_placements:)
+ # Build per-board sets: tagged column targets + catch-all column IDs
+ tagged_targets = Hash.new { |h, k| h[k] = Set.new }
+ catch_all_ids = Hash.new { |h, k| h[k] = Set.new }
+
+ matching_placements.each do |row|
+ if row[:column_tag_id].present?
+ tagged_targets[row[:board_id]] << row[:column_id]
+ else
+ catch_all_ids[row[:board_id]] << row[:column_id]
+ end
+ end
+
+ existing_by_board =
+ existing_cards
+ .group_by { |_, board_id, _| board_id }
+ .transform_values do |rows|
+ rows.map { |card_id, _, column_id| { id: card_id, column_id: } }
+ end
+
+ remove_card_ids = []
+ create_targets = []
+
+ all_board_ids = (tagged_targets.keys + catch_all_ids.keys + existing_by_board.keys).uniq
+
+ all_board_ids.each do |board_id|
+ cards = existing_by_board[board_id] || []
+ board_tagged = tagged_targets[board_id]
+ board_catch_alls = catch_all_ids[board_id]
+ existing_column_ids = cards.map { |c| c[:column_id] }.to_set
+
+ # Tagged columns: deterministic β€” create if missing
+ board_tagged.each do |col_id|
+ create_targets << { board_id:, column_id: col_id } if existing_column_ids.exclude?(col_id)
+ end
+
+ # Unconstrained columns don't auto-receive cards. Manually-placed
+ # cards in them are only preserved when no tagged column matches.
+ if board_tagged.empty?
+ valid_columns = board_catch_alls
+ else
+ valid_columns = board_tagged
+ end
+
+ cards.each { |c| remove_card_ids << c[:id] if valid_columns.exclude?(c[:column_id]) }
+ end
+
+ { remove_card_ids:, create_targets: }
+ end
+ private_class_method :compute_sync_plan
+
+ def self.execute_sync_changes(topic:, plan:, existing_cards:, max_positions:, board_groups:)
+ # Delete β€” derive board mapping from existing_cards snapshot (no extra query)
+ deleted_by_board = {}
+ if plan[:remove_card_ids].present?
+ remove_set = plan[:remove_card_ids].to_set
+ existing_cards.each do |card_id, board_id, _|
+ (deleted_by_board[board_id] ||= []) << card_id if remove_set.include?(card_id)
+ end
+ Card.where(id: plan[:remove_card_ids]).delete_all
+ end
+
+ # Create β€” positions precomputed from batch query
+ created_cards = []
+ if plan[:create_targets].present?
+ system_user_id = Discourse.system_user.id
+ running_positions = max_positions.dup
+
+ now = Time.zone.now
+
+ plan[:create_targets].each do |target|
+ col_id = target[:column_id]
+ running_positions[col_id] = (running_positions[col_id] || 0) + CardOrdering::GAP_SIZE
+
+ card =
+ Card.create!(
+ board_id: target[:board_id],
+ column_id: col_id,
+ card_type: :topic,
+ topic_id: topic.id,
+ position: running_positions[col_id],
+ column_changed_at: now,
+ created_by_id: system_user_id,
+ updated_by_id: system_user_id,
+ )
+ card.topic = topic
+ created_cards << card
+ end
+ end
+
+ # Trim columns that exceeded the cap β€” evict oldest topic cards
+ if created_cards.present?
+ affected_column_ids = plan[:create_targets].map { |t| t[:column_id] }.uniq
+ evicted = trim_excess_cards(affected_column_ids)
+ evicted.each { |board_id, card_ids| (deleted_by_board[board_id] ||= []).concat(card_ids) }
+ end
+
+ # Publish
+ publish_sync_changes(board_groups:, deleted_by_board:, created_cards:)
+ end
+ private_class_method :execute_sync_changes
+
+ def self.trim_excess_cards(column_ids)
+ return {} if column_ids.blank?
+
+ sanitized_col_ids = "{#{column_ids.map(&:to_i).join(",")}}"
+ evicted = DB.query(<<~SQL, column_ids: sanitized_col_ids, max_cards: MAX_CARDS_PER_COLUMN)
+ DELETE FROM discourse_kanban_cards
+ WHERE id IN (
+ SELECT id FROM (
+ SELECT id, ROW_NUMBER() OVER (PARTITION BY column_id ORDER BY position DESC, id DESC) AS rn
+ FROM discourse_kanban_cards
+ WHERE column_id = ANY(:column_ids) AND card_type = #{Card.card_types[:topic]}
+ ) ranked
+ WHERE ranked.rn > :max_cards
+ )
+ RETURNING id, board_id
+ SQL
+
+ deleted_by_board = {}
+ evicted.each { |row| (deleted_by_board[row.board_id] ||= []) << row.id }
+ deleted_by_board
+ end
+ private_class_method :trim_excess_cards
+
+ def self.publish_sync_changes(board_groups:, deleted_by_board:, created_cards:)
+ deleted_by_board.each do |board_id, card_ids|
+ card_ids.each do |card_id|
+ publish_to_board(board_groups, board_id, type: "card_deleted", card_id: card_id)
+ end
+ end
+
+ created_cards.each do |card|
+ payload = CardSerializer.new(card, root: false).as_json.except("topic", :topic)
+ publish_to_board(board_groups, card.board_id, type: "card_created", card: payload)
+ end
+ end
+ private_class_method :publish_sync_changes
+
+ def self.publish_to_board(board_groups, board_id, data)
+ group_ids = board_groups[board_id]
+ return if group_ids.nil?
+ opts = {}
+ if group_ids.present? && !group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])
+ opts[:group_ids] = group_ids
+ end
+ MessageBus.publish(
+ "#{Publisher::CHANNEL_PREFIX}/#{board_id}",
+ data.merge(client_id: nil),
+ opts,
+ )
+ end
+ private_class_method :publish_to_board
+
+ def self.with_topic_sync_retry
+ retries = 0
+
+ begin
+ yield
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid => error
+ raise unless unique_topic_card_violation?(error) && retries < 1
+
+ retries += 1
+ retry
+ end
+ end
+
+ def self.unique_topic_card_violation?(error)
+ [error, error.cause, error.cause&.cause].compact.any? do |candidate|
+ candidate.message.include?("idx_kanban_cards_unique_topic_per_column") ||
+ topic_card_constraint_name(candidate) == "idx_kanban_cards_unique_topic_per_column"
+ end
+ end
+
+ def self.topic_card_constraint_name(error)
+ return unless defined?(PG::Result)
+ return unless error.respond_to?(:result)
+
+ error.result&.error_field(PG::Result::PG_DIAG_CONSTRAINT_NAME)
+ end
+
+ def self.build_column_topic_map(board, columns)
+ result = {}
+ scope_base =
+ Topic
+ .listable_topics
+ .visible
+ .where.not(id: Category.where.not(topic_id: nil).select(:topic_id))
+ .order(bumped_at: :desc)
+
+ # Apply board-level category filter
+ scope_base = scope_base.where(category_id: board.category_ids) if board.category_ids.present?
+
+ # Apply board-level tag filter
+ if board.tag_ids.present?
+ scope_base = scope_base.where(id: TopicTag.where(tag_id: board.tag_ids).select(:topic_id))
+ end
+
+ columns.each do |col|
+ if col.tag_id.present?
+ ids =
+ scope_base
+ .where(id: TopicTag.where(tag_id: col.tag_id).select(:topic_id))
+ .limit(MAX_CARDS_PER_COLUMN)
+ .pluck(:id)
+ .to_set
+ result[col.id] = ids
+ end
+ end
+
+ result
+ end
+
+ def self.apply_bulk_changes(board, to_create:, to_delete:)
+ return if to_create.empty? && to_delete.empty?
+
+ Card.transaction do
+ Card.where(id: to_delete).delete_all if to_delete.any?
+
+ if to_create.any?
+ max_positions =
+ board.cards.with_column.group(:column_id).maximum(:position).transform_values(&:to_i)
+
+ system_user_id = Discourse.system_user.id
+ now = Time.zone.now
+
+ to_create.each do |entry|
+ col_id = entry[:column_id]
+ max_positions[col_id] = (max_positions[col_id] || -CardOrdering::GAP_SIZE) +
+ CardOrdering::GAP_SIZE
+ pos = max_positions[col_id]
+
+ Card.insert!(
+ {
+ board_id: board.id,
+ column_id: col_id,
+ topic_id: entry[:topic_id],
+ card_type: Card.card_types[:topic],
+ position: pos,
+ column_changed_at: now,
+ created_by_id: system_user_id,
+ updated_by_id: system_user_id,
+ created_at: now,
+ updated_at: now,
+ },
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/update_board.rb b/plugins/boards/app/services/boards/update_board.rb
new file mode 100644
index 00000000000..e082967897a
--- /dev/null
+++ b/plugins/boards/app/services/boards/update_board.rb
@@ -0,0 +1,150 @@
+# frozen_string_literal: true
+
+module Boards
+ class UpdateBoard
+ include Service::Base
+
+ params do
+ attribute :id, :integer
+ attribute :client_id, :string
+
+ validates :id, presence: true
+ end
+
+ model :board
+ policy :can_manage
+
+ transaction do
+ step :update_acl
+ step :update_board
+ step :remove_non_matching_cards
+ step :create_histories
+ end
+
+ step :publish_update
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.id)
+ end
+
+ def can_manage(guardian:, board:)
+ guardian.can_manage_boards_board?(board)
+ end
+
+ def update_acl(board:, guardian:)
+ raw = context[:raw_board_params] || {}
+ return if !raw.key?("acl")
+ flattened_acl = raw["acl"]
+
+ AccessControlListManager.call(
+ guardian:,
+ params: {
+ target: board,
+ flattened_acl: flattened_acl,
+ owner: Boards::PLUGIN_NAME,
+ },
+ ) do |result|
+ on_success do |previous_permissions:, new_permissions:|
+ context[:histories] ||= {}
+ context[:histories][:permissions_changed] = { previous_permissions:, new_permissions: }
+ end
+
+ on_failure do
+ Rails.logger.warn(
+ "Failed to update ACL for board #{board.id} (#{flattened_acl.to_json}): #{result.inspect_steps}",
+ )
+ fail!(I18n.t("boards.board.errors.acl_update_failed"))
+ end
+ end
+ end
+
+ def update_board(board:, guardian:)
+ raw = context[:raw_board_params]&.dup || {}
+ context[:histories] ||= {}
+ if raw.key?("tag_names")
+ raw["tag_ids"] = VisibleTagResolver.resolve_names!(raw.delete("tag_names"), guardian:)
+ end
+ board.assign_attributes(raw.except("columns", "acl"))
+ board.updated_by_id = guardian.user.id
+
+ if board.name_changed?
+ context[:histories][:renamed] = { previous_value: board.name_was, new_value: board.name }
+ end
+
+ if board.category_ids_changed?
+ context[:histories][:constraints_changed] ||= {}
+ context[:histories][:constraints_changed].merge!(
+ previous_category_ids: board.category_ids_was,
+ new_category_ids: board.category_ids,
+ )
+ end
+
+ if board.tag_ids_changed?
+ context[:histories][:constraints_changed] ||= {}
+ context[:histories][:constraints_changed].merge!(
+ previous_tag_ids: board.tag_ids_was,
+ new_tag_ids: board.tag_ids,
+ )
+ end
+
+ if board.slug_changed?
+ context[:histories][:slug_changed] = {
+ previous_value: board.slug_was,
+ new_value: board.slug,
+ }
+ end
+
+ board.save!
+ end
+
+ def remove_non_matching_cards(board:, guardian:)
+ if board.has_constraints?
+ non_matching_card_ids =
+ DB.query_single(
+ <<~SQL,
+ SELECT c.id FROM discourse_kanban_cards c
+ JOIN topics t ON t.id = c.topic_id
+ WHERE c.board_id = :board_id AND c.card_type = #{Card.card_types[:topic]}
+ AND NOT (
+ (:cat_empty OR t.category_id = ANY(:category_ids))
+ AND (:tag_empty OR EXISTS (
+ SELECT 1 FROM topic_tags tt WHERE tt.topic_id = t.id AND tt.tag_id = ANY(:tag_ids)
+ ))
+ )
+ SQL
+ board_id: board.id,
+ category_ids: pg_array(board.category_ids),
+ tag_ids: pg_array(board.tag_ids),
+ cat_empty: board.category_ids.empty?,
+ tag_empty: board.tag_ids.empty?,
+ )
+ else
+ non_matching_card_ids = []
+ end
+
+ Card.where(id: non_matching_card_ids).delete_all if non_matching_card_ids.present?
+ context[:cards_removed_count] = non_matching_card_ids.length
+ end
+
+ def pg_array(ids)
+ "{#{ids.join(",")}}"
+ end
+
+ def create_histories(board:, guardian:, histories:)
+ histories.each do |action, details|
+ BoardHistory.create!(
+ board:,
+ acting_user: guardian.user,
+ action: "board_#{action}",
+ details:,
+ )
+ end
+ end
+
+ def publish_update(board:, params:)
+ Publisher.publish_board_updated!(board, client_id: params.client_id)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/update_card.rb b/plugins/boards/app/services/boards/update_card.rb
new file mode 100644
index 00000000000..bbff3e5bfa3
--- /dev/null
+++ b/plugins/boards/app/services/boards/update_card.rb
@@ -0,0 +1,332 @@
+# frozen_string_literal: true
+
+module Boards
+ class UpdateCard
+ include Service::Base
+
+ options do
+ attribute :raw_card_params, default: -> { {} }
+ attribute :constraint_fix
+ end
+
+ params do
+ attribute :board_id, :integer
+ attribute :id, :integer
+ attribute :topic_id, :integer
+ attribute :column_id, :integer
+ attribute :title, :string
+ attribute :notes
+ attribute :after_card_id, :integer
+ attribute :assigned_to_name, :string
+ attribute :tag_ids, :array
+ attribute :tag_names, :array
+
+ validates :board_id, presence: true
+ validates :id, presence: true
+ end
+
+ model :board
+ policy :can_write
+ model :card
+ policy :can_see_card_topic
+ model :column
+ step :capture_original_state
+
+ step :resolve_promotion
+ step :update_attributes
+ step :place_and_save
+ step :log_history
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_write(board:, guardian:)
+ guardian.can_write_boards_board?(board)
+ end
+
+ def fetch_card(board:, params:)
+ board.cards.find_by(id: params.id)
+ end
+
+ def can_see_card_topic(card:, guardian:)
+ !card.topic? || card.topic.blank? || guardian.can_see?(card.topic)
+ end
+
+ def capture_original_state(card:)
+ context[:original_column_id] = card.column_id
+ context[:adopted_floater_id] = nil
+ end
+
+ def fetch_column(board:, card:, params:)
+ if params.column_id.present?
+ board.columns.find_by(id: params.column_id)
+ else
+ card.column
+ end
+ end
+
+ def resolve_promotion(card:, column:, params:, guardian:, options:, board:)
+ return unless card.floater? && params.topic_id.present?
+
+ topic = Topic.find_by(id: params.topic_id)
+ raise Discourse::NotFound if topic.nil?
+ raise Discourse::InvalidAccess.new unless guardian.can_see?(topic)
+ if Category.exists?(topic_id: topic.id)
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.category_definition_topic"))
+ end
+
+ constraint_fix = options.constraint_fix.presence || context[:constraint_fix]
+
+ if constraint_fix.present?
+ ConstraintFixer.apply!(fix: constraint_fix, board:, topic:, guardian:)
+ end
+
+ unless board.topic_will_match_after_mutation?(topic, column)
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+
+ card_assignee = card.assigned_to
+ validate_assignment_carry_over!(card_assignee, column, guardian)
+
+ existing = board.cards.find_by(topic_id: topic.id, column_id: column.id)
+ if existing
+ context[:card] = adopt_existing_topic_card!(
+ card,
+ existing,
+ column,
+ params,
+ guardian,
+ options:,
+ )
+ context[:promoted] = true
+ assign_card_assignee_to_topic(card_assignee, topic, column, guardian)
+ return
+ end
+
+ card.topic_id = topic.id
+ card.title = nil
+ card.inline_onebox_data = nil
+ card.notes = nil
+ card.tag_ids = []
+ card.assigned_to_id = nil
+ card.assigned_to_type = nil
+ card.updated_by_id = guardian.user.id
+ TopicMutator.apply!(topic:, column:, guardian:)
+ assign_card_assignee_to_topic(card_assignee, topic, column, guardian)
+ context[:promoted] = true
+ end
+
+ def update_attributes(card:, params:, guardian:, options:)
+ raw = options.raw_card_params.presence || context[:raw_card_params] || {}
+ if card.floater? && !context[:promoted]
+ card.title = params.title || card.title
+ card.inline_onebox_data = nil if param_provided?(raw, "title")
+ card.notes = raw.key?("notes") ? raw["notes"] : card.notes
+ if raw.key?("tag_ids") || raw.key?("tag_names")
+ card.tag_ids = resolve_all_tag_ids(params.tag_ids, params.tag_names, guardian)
+ end
+ card.assigned_to = resolve_assignee(raw["assigned_to_name"], guardian) if raw.key?(
+ "assigned_to_name",
+ )
+ card.updated_by_id = guardian.user.id
+ context[:card_edited] = true
+ elsif !context[:promoted]
+ card.updated_by_id = guardian.user.id
+ end
+ end
+
+ def resolve_assignee(name, guardian)
+ return nil if name.blank?
+
+ unless guardian.can_assign?
+ raise Discourse::InvalidAccess.new(I18n.t("boards.errors.cannot_assign"))
+ end
+
+ user = User.find_by_username(name)
+ return user if user&.active
+
+ group = Group.find_by(name: name)
+ return group if group && guardian.can_see_group?(group)
+
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.invalid_assignee", name: name))
+ end
+
+ def param_provided?(raw, key)
+ raw.key?(key) || raw.key?(key.to_sym)
+ end
+
+ def place_and_save(card:, column:, params:, guardian:, options:, board:, original_column_id:)
+ raw = options.raw_card_params.presence || context[:raw_card_params] || {}
+ tags_changed = raw.key?("tag_ids") || raw.key?("tag_names")
+ position_first = raw.key?("after_card_id") && raw["after_card_id"].blank?
+ needs_placement =
+ context[:promoted] || column.id != card.column_id || raw.key?("after_card_id")
+
+ Card.transaction do
+ column_changed = !context[:promoted] && column.id != card.column_id
+ column_changed_for_topic_card = column_changed && card.topic? && card.topic.present?
+
+ if column_changed_for_topic_card
+ constraint_fix = options.constraint_fix.presence || context[:constraint_fix]
+
+ if constraint_fix.present?
+ ConstraintFixer.apply!(fix: constraint_fix, board:, topic: card.topic, guardian:)
+ end
+
+ unless board.topic_will_match_after_mutation?(card.topic, column)
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.topic_does_not_match_constraints"),
+ )
+ end
+ end
+
+ if needs_placement
+ CardOrdering.place_card!(
+ card,
+ column:,
+ after_card_id: params.after_card_id,
+ position_first:,
+ )
+ end
+
+ if card.floater? && (column.id != original_column_id || tags_changed)
+ LooseCardTagMutator.apply_to_card!(card:, column:)
+ end
+ TopicMutator.apply!(topic: card.topic, column:, guardian:) if column_changed_for_topic_card
+
+ card.save!
+ context[:column_changed] = column_changed
+ context[:column_changed_details] = {
+ from: Boards::Column.find_by(id: original_column_id)&.title,
+ to: column.title,
+ }
+ end
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::StatementInvalid => error
+ raise unless unique_topic_card_violation?(error)
+
+ if context[:promoted] && params.topic_id.present?
+ existing =
+ board
+ .cards
+ .where(topic_id: params.topic_id, column_id: column.id)
+ .where.not(id: card.id)
+ .first!
+ context[:card] = adopt_existing_topic_card!(
+ card,
+ existing,
+ column,
+ params,
+ guardian,
+ options:,
+ )
+ else
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.topic_already_in_column"))
+ end
+ end
+
+ # TODO (martin) These are very light on details for now,
+ # this whole service needs a big refactor to avoid doing
+ # so much and to make it easier to track details for
+ # history logging. For now let's at least get the events
+ # tracking and add the details later.
+ def log_history(card:, params:, guardian:)
+ if context[:card_edited]
+ Boards::CardHistory.create!(
+ card:,
+ board: card.board,
+ acting_user: guardian.user,
+ action: Boards::CardHistory.actions[:card_edited],
+ )
+ end
+
+ if context[:column_changed]
+ Boards::CardHistory.create!(
+ card:,
+ board: card.board,
+ acting_user: guardian.user,
+ action: Boards::CardHistory.actions[:card_moved],
+ details: context[:column_changed_details],
+ )
+ end
+ end
+
+ def adopt_existing_topic_card!(floater, existing, column, params, guardian, options:)
+ floater.reload if floater.changed?
+ floater_id = floater.id
+
+ raw = options.raw_card_params.presence || context[:raw_card_params] || {}
+ position_first = raw.key?("after_card_id") && raw["after_card_id"].blank?
+
+ Card.transaction do
+ existing = existing.lock!
+ context[:original_column_id] = existing.column_id
+ existing.updated_by_id = guardian.user.id
+ topic = existing.topic || Topic.find_by(id: params.topic_id)
+ raise Discourse::NotFound if topic.nil?
+ TopicMutator.apply!(topic:, column:, guardian:)
+ CardOrdering.place_card!(
+ existing,
+ column:,
+ after_card_id: params.after_card_id,
+ position_first:,
+ )
+ existing.save!
+ floater.destroy!
+ end
+
+ context[:adopted_floater_id] = floater_id
+ existing
+ end
+
+ def unique_topic_card_violation?(error)
+ [error, error.cause, error.cause&.cause].compact.any? do |candidate|
+ candidate.message.include?("idx_kanban_cards_unique_topic_per_column") ||
+ topic_card_constraint_name(candidate) == "idx_kanban_cards_unique_topic_per_column"
+ end
+ end
+
+ def validate_assignment_carry_over!(assignee, column, guardian)
+ return if assignee.blank?
+ return unless defined?(::Assigner)
+ return if column.move_to_assigned.present? && column.move_to_assigned != "*"
+
+ unless guardian.can_assign?
+ raise Discourse::InvalidAccess.new(I18n.t("boards.errors.cannot_assign"))
+ end
+ end
+
+ def assign_card_assignee_to_topic(assignee, topic, column, guardian)
+ return if assignee.blank?
+ return unless defined?(::Assigner)
+ return if column.move_to_assigned.present? && column.move_to_assigned != "*"
+
+ result = ::Assigner.new(topic, guardian.user).assign(assignee, skip_small_action_post: true)
+
+ unless result[:success]
+ raise Discourse::InvalidParameters.new(I18n.t("boards.errors.assignment_carry_over_failed"))
+ end
+ end
+
+ def resolve_all_tag_ids(tag_ids, tag_names, guardian)
+ ids = Card.normalize_visible_tag_ids!(tag_ids, guardian)
+ names = Array(tag_names).compact_blank
+ if names.present?
+ tags = DiscourseTagging.find_or_create_tags!(names, guardian)
+ ids = Card.normalize_visible_tag_ids!(ids + tags.map(&:id), guardian)
+ end
+ ids
+ end
+
+ def topic_card_constraint_name(error)
+ return unless defined?(PG::Result)
+ return unless error.respond_to?(:result)
+
+ error.result&.error_field(PG::Result::PG_DIAG_CONSTRAINT_NAME)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/update_column.rb b/plugins/boards/app/services/boards/update_column.rb
new file mode 100644
index 00000000000..1c1cf94a06f
--- /dev/null
+++ b/plugins/boards/app/services/boards/update_column.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+module Boards
+ class UpdateColumn
+ include Service::Base
+
+ params do
+ attribute :board_id, :integer
+ attribute :id, :integer
+ attribute :title, :string
+ attribute :icon, :string
+ attribute :color, :string
+ attribute :default_sort, :string
+ attribute :tag_name, :string
+ attribute :move_to_category_id, :integer
+ attribute :move_to_assigned, :string
+ attribute :move_to_status, :string
+ attribute :client_id, :string
+
+ validates :board_id, presence: true
+ validates :id, presence: true
+ validates :title, presence: true
+ validates :color, format: { with: /\A(\h{3}|\h{6})\z/ }, allow_nil: true
+ end
+
+ model :board
+ policy :can_manage
+ model :column
+
+ transaction do
+ step :update_column
+ step :create_histories
+ end
+
+ step :publish_update
+
+ private
+
+ def fetch_board(params:)
+ Board.find_by(id: params.board_id)
+ end
+
+ def can_manage(guardian:, board:)
+ guardian.can_manage_boards_board?(board)
+ end
+
+ def fetch_column(board:, params:)
+ board.columns.find_by(id: params.id)
+ end
+
+ def update_column(column:, params:, guardian:)
+ ColumnMutator.apply!(column:, attributes: params.to_hash, guardian:)
+ end
+
+ def create_histories(board:, column:, guardian:)
+ changes = history_changes(column)
+
+ if changes.key?(:title)
+ previous_title, new_title = changes.delete(:title)
+ BoardHistory.create!(
+ board:,
+ column:,
+ acting_user: guardian.user,
+ action: :column_renamed,
+ details: {
+ previous_value: previous_title,
+ new_value: new_title,
+ },
+ )
+ end
+
+ if changes.present?
+ BoardHistory.create!(
+ board:,
+ column:,
+ acting_user: guardian.user,
+ action: :column_edited,
+ details: {
+ previous_values: changes.transform_values(&:first),
+ new_values: changes.transform_values(&:last),
+ },
+ )
+ end
+ end
+
+ def publish_update(board:, params:)
+ Publisher.publish_board_updated!(board, client_id: params.client_id)
+ end
+
+ def history_changes(column)
+ column
+ .saved_changes
+ .slice(
+ "title",
+ "icon",
+ "color",
+ "default_sort",
+ "tag_id",
+ "move_to_category_id",
+ "move_to_assigned",
+ "move_to_status",
+ )
+ .transform_keys(&:to_sym)
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/view_board.rb b/plugins/boards/app/services/boards/view_board.rb
new file mode 100644
index 00000000000..63d6299b3b8
--- /dev/null
+++ b/plugins/boards/app/services/boards/view_board.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module Boards
+ class ViewBoard
+ include Service::Base
+
+ params { attribute :id, :integer }
+
+ policy :is_logged_in
+ model :board
+ policy :can_read_board
+ step :create_view_history
+
+ private
+
+ def is_logged_in(guardian:)
+ guardian.authenticated?
+ end
+
+ def fetch_board(params:)
+ Boards::Board.find_by(id: params.id)
+ end
+
+ def can_read_board(guardian:, board:)
+ guardian.can_read_boards_board?(board)
+ end
+
+ def create_view_history(guardian:, board:)
+ BoardHistory.create!(
+ board:,
+ acting_user: guardian.user,
+ action: BoardHistory.actions[:board_viewed],
+ )
+ rescue ActiveRecord::RecordNotUnique
+ # We only want to record one view per user per board per day,
+ # see the index_discourse_kanban_board_histories_one_view_per_user_day index.
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/view_card.rb b/plugins/boards/app/services/boards/view_card.rb
new file mode 100644
index 00000000000..6b23d77967a
--- /dev/null
+++ b/plugins/boards/app/services/boards/view_card.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module Boards
+ class ViewCard
+ include Service::Base
+
+ params { attribute :id, :integer }
+
+ policy :is_logged_in
+ model :card
+ policy :can_view_card
+ step :create_view_history
+
+ private
+
+ def is_logged_in(guardian:)
+ guardian.authenticated?
+ end
+
+ def fetch_card(params:)
+ Boards::Card.find_by(id: params.id)
+ end
+
+ def can_view_card(guardian:, card:)
+ guardian.can_view_boards_card?(card)
+ end
+
+ def create_view_history(guardian:, card:)
+ CardHistory.create!(
+ card:,
+ acting_user: guardian.user,
+ action: CardHistory.actions[:card_viewed],
+ board_id: card.board_id,
+ )
+ rescue ActiveRecord::RecordNotUnique
+ # We only want to record one view per user per card per day,
+ # see the index_discourse_kanban_card_histories_one_view_per_user_day index.
+ end
+ end
+end
diff --git a/plugins/boards/app/services/boards/visible_tag_resolver.rb b/plugins/boards/app/services/boards/visible_tag_resolver.rb
new file mode 100644
index 00000000000..b6b8b37adec
--- /dev/null
+++ b/plugins/boards/app/services/boards/visible_tag_resolver.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module Boards
+ module VisibleTagResolver
+ def self.resolve_names!(tag_names, guardian:)
+ names = Array(tag_names).compact_blank.map(&:to_s)
+ return [] if names.empty?
+
+ visible_tags =
+ DiscourseTagging
+ .visible_tags(guardian)
+ .where_name(names)
+ .index_by { |tag| tag.name.downcase }
+ resolved_ids = []
+ missing_names = []
+
+ names.each do |name|
+ tag = visible_tags[name.downcase]
+ if tag && guardian.can_see_tag?(tag)
+ resolved_ids << tag.id
+ elsif guardian.can_create_tag?
+ cleaned_name = DiscourseTagging.clean_tag(name)
+ if cleaned_name.present? && !Tag.where_name([cleaned_name]).exists?
+ resolved_ids << Tag.create!(name: cleaned_name).id
+ else
+ missing_names << name
+ end
+ else
+ missing_names << name
+ end
+ end
+
+ if missing_names.any?
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_names", tag_names: missing_names.join(", ")),
+ )
+ end
+
+ resolved_ids
+ end
+
+ def self.resolve_name!(tag_name, guardian:)
+ resolve_names!([tag_name], guardian:).first
+ rescue Discourse::InvalidParameters
+ raise Discourse::InvalidParameters.new(
+ I18n.t("boards.errors.unknown_tag_name", tag_name: tag_name),
+ )
+ end
+ end
+end
diff --git a/plugins/boards/assets/javascripts/discourse/boards-route-map.js b/plugins/boards/assets/javascripts/discourse/boards-route-map.js
new file mode 100644
index 00000000000..aa19c71b6e3
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/boards-route-map.js
@@ -0,0 +1,10 @@
+export default function () {
+ this.route("boards");
+ this.route("boardsBoard", { path: "/boards/:slug/:id" });
+ this.route("boardsBoardConfigure", {
+ path: "/boards/:slug/:id/configure",
+ });
+ this.route("boardsBoardCard", {
+ path: "/boards/:slug/:id/cards/:card_id",
+ });
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/auto-linked-text.gjs b/plugins/boards/assets/javascripts/discourse/components/auto-linked-text.gjs
new file mode 100644
index 00000000000..f494094490c
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/auto-linked-text.gjs
@@ -0,0 +1,67 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { generateLinkifyFunction } from "discourse/lib/text";
+
+let cachedLinkify = null;
+
+export default class AutoLinkedText extends Component {
+ @tracked linkify = cachedLinkify;
+
+ constructor() {
+ super(...arguments);
+ if (!this.linkify) {
+ generateLinkifyFunction({}).then((instance) => {
+ cachedLinkify = instance;
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.linkify = instance;
+ }
+ });
+ }
+ }
+
+ get segments() {
+ const text = this.args.text ?? "";
+ if (!this.linkify || !text) {
+ return [{ isUrl: false, value: text }];
+ }
+
+ const matches = this.linkify.match(text);
+ if (!matches) {
+ return [{ isUrl: false, value: text }];
+ }
+
+ const result = [];
+ let lastIndex = 0;
+
+ for (const match of matches) {
+ if (match.index > lastIndex) {
+ result.push({
+ isUrl: false,
+ value: text.slice(lastIndex, match.index),
+ });
+ }
+ result.push({ isUrl: true, value: match.raw, href: match.url });
+ lastIndex = match.index + match.raw.length;
+ }
+
+ if (lastIndex < text.length) {
+ result.push({ isUrl: false, value: text.slice(lastIndex) });
+ }
+
+ return result;
+ }
+
+ <template>
+ {{#each this.segments as |segment|}}
+ {{#if segment.isUrl}}
+ <a
+ href={{segment.href}}
+ target="_blank"
+ rel="noopener noreferrer"
+ >{{segment.value}}</a>
+ {{else}}
+ {{segment.value}}
+ {{/if}}
+ {{/each}}
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-add-from-topic-column-submenu.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-add-from-topic-column-submenu.gjs
new file mode 100644
index 00000000000..9ba925af579
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-add-from-topic-column-submenu.gjs
@@ -0,0 +1,196 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { isValidHex, normalizeHex } from "discourse/lib/color-transformations";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import BoardsConstraintFix from "./modal/boards-constraint-fix";
+
+export default class BoardsAddFromTopicColumnSubmenu extends Component {
+ @service messageBus;
+ @service modal;
+ @service toasts;
+
+ @action
+ async addToColumn(column) {
+ const response = await this.#checkConstraints(column);
+
+ if (!response) {
+ return;
+ }
+
+ if (response.constraints_need_fixing) {
+ return this.#onConstraintMismatch(column, response);
+ }
+
+ await this.#completeAddToColumn(column);
+ }
+
+ @action
+ async removeFromColumn(column) {
+ try {
+ await ajax(
+ `/boards/api/boards/${this.args.data.board.id}/cards/${column.topic_card_id}`,
+ {
+ type: "DELETE",
+ }
+ );
+
+ this.toasts.success({
+ duration: "short",
+ data: {
+ message: i18n("boards.board.removed_topic_from_board", {
+ boardName: this.args.data.board.unicode_name,
+ columnName: column.unicode_title,
+ }),
+ },
+ });
+
+ this.args.close({ data: { cardSaved: true } });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ async #checkConstraints(column) {
+ try {
+ const response = await ajax(
+ `/boards/api/boards/${this.args.data.board.id}/check-constraint-mismatches`,
+ {
+ method: "PUT",
+ data: {
+ topic_id: this.args.data.topic.id,
+ target_column_id: column.id,
+ },
+ }
+ );
+ return response;
+ } catch (error) {
+ popupAjaxError(error);
+ return null;
+ }
+ }
+
+ #onConstraintMismatch(column, response) {
+ const mismatches = {
+ needsTags: response.tags_needed.length > 0,
+ needsCategory: response.categories_needed.length > 0,
+ boardTagNames: response.tags_needed,
+ boardCategoryIds: response.categories_needed,
+ };
+
+ this.modal.show(BoardsConstraintFix, {
+ model: {
+ topic: this.args.data.topic,
+ board: this.args.data.board,
+ column,
+ mismatches,
+ onConfirm: (result) => this.#completeAddToColumn(column, result),
+ },
+ });
+ }
+
+ async #completeAddToColumn(column, constraintFixResult = null) {
+ const data = {
+ client_id: this.messageBus.clientId,
+ card: {
+ column_id: column.id,
+ topic_id: this.args.data.topic.id,
+ },
+ };
+
+ if (constraintFixResult) {
+ data.constraint_fix = constraintFixResult;
+ }
+
+ try {
+ await ajax(`/boards/api/boards/${this.args.data.board.id}/cards`, {
+ type: "POST",
+ data,
+ });
+
+ this.toasts.success({
+ duration: "short",
+ data: {
+ message: i18n("boards.board.added_topic_to_board", {
+ boardName: this.args.data.board.unicode_name,
+ columnName: column.unicode_title,
+ }),
+ },
+ });
+
+ this.args.close({ data: { cardSaved: true } });
+ } catch (error) {
+ popupAjaxError(error);
+ return;
+ }
+ }
+
+ get availableColumns() {
+ return this.args.data.board.columns.filter(
+ (column) => !column.topic_is_member
+ );
+ }
+
+ get alreadyAddedColumns() {
+ return this.args.data.board.columns.filter(
+ (column) => column.topic_is_member
+ );
+ }
+
+ columnStyle(column) {
+ if (!isValidHex(column.color)) {
+ return null;
+ }
+
+ return trustHTML(
+ `--discourse-boards-column-icon-color: #${normalizeHex(column.color)};`
+ );
+ }
+
+ <template>
+ <DDropdownMenu
+ class="discourse-boards-add-from-topic-column-menu"
+ as |dropdown|
+ >
+ {{#if this.availableColumns.length}}
+ <dropdown.subheader>
+ {{@data.board.unicode_name}}
+ </dropdown.subheader>
+ {{#each this.availableColumns as |column|}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.addToColumn column}}
+ @icon={{column.icon}}
+ @translatedLabel={{column.fancyTitle}}
+ style={{this.columnStyle column}}
+ class="btn-transparent discourse-boards-add-from-topic-column-menu__column"
+ />
+ </dropdown.item>
+ {{/each}}
+ {{/if}}
+ {{#if this.alreadyAddedColumns.length}}
+ <dropdown.subheader>
+ {{i18n "boards.topic_footer.already_added"}}
+ </dropdown.subheader>
+ {{#each this.alreadyAddedColumns as |column|}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.removeFromColumn column}}
+ @icon={{column.icon}}
+ @translatedLabel={{column.fancyTitle}}
+ @suffixIcon="xmark"
+ style={{this.columnStyle column}}
+ class="btn-transparent discourse-boards-add-from-topic-column-menu__column"
+ />
+ </dropdown.item>
+ {{/each}}
+ {{/if}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-add-from-topic-menu.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-add-from-topic-menu.gjs
new file mode 100644
index 00000000000..463dab96280
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-add-from-topic-menu.gjs
@@ -0,0 +1,157 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import Board from "discourse/plugins/boards/discourse/models/board";
+import BoardsAddFromTopicColumnSubmenu from "./boards-add-from-topic-column-submenu";
+
+const SKELETON_ROWS = Array.from({ length: 3 });
+
+const BoardSkeleton = <template>
+ <div
+ class="discourse-boards-add-from-topic-menu__skeleton"
+ aria-hidden="true"
+ >
+ <div class="discourse-boards-add-from-topic-menu__skeleton-label"></div>
+ <div class="discourse-boards-add-from-topic-menu__skeleton-icon"></div>
+ </div>
+</template>;
+
+export default class BoardsAddFromTopicMenu extends Component {
+ @service menu;
+
+ @tracked boards = [];
+ @tracked loading = true;
+
+ skeletonRows = SKELETON_ROWS;
+ #requestedBoards = false;
+
+ @action
+ loadBoards() {
+ if (this.#requestedBoards) {
+ return;
+ }
+
+ this.#requestedBoards = true;
+ this.#fetchBoards();
+ }
+
+ async #fetchBoards() {
+ try {
+ const result = await ajax(
+ `/boards/api/boards/available?topic_id=${this.args.data.topic.id}&allowed_permissions=edit,manage`
+ );
+ this.boards = result.boards
+ .filter((board) => board.columns?.length)
+ .map((board) => Board.create(board));
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ openBoardSubmenu(board, event) {
+ return this.menu.show(event.currentTarget, {
+ identifier: "discourse-boards-add-from-topic-column-menu",
+ component: BoardsAddFromTopicColumnSubmenu,
+ modalForMobile: true,
+ placement: "right-start",
+ offset: { mainAxis: 10, crossAxis: -5 },
+ data: { board, topic: this.args.data?.topic },
+ onClose: (data) => {
+ if (data?.cardSaved) {
+ this.args.close();
+ }
+ },
+ });
+ }
+
+ get availableBoards() {
+ return this.boards.filter((board) => !board.topic_is_member);
+ }
+
+ get alreadyAddedBoards() {
+ return this.boards.filter((board) => board.topic_is_member);
+ }
+
+ <template>
+ <DDropdownMenu
+ class="discourse-boards-add-from-topic-menu"
+ {{didInsert this.loadBoards}}
+ as |dropdown|
+ >
+ {{#if this.loading}}
+ {{#each this.skeletonRows}}
+ <dropdown.item>
+ <BoardSkeleton />
+ </dropdown.item>
+ {{/each}}
+ {{else}}
+ {{#if this.boards.length}}
+ {{#if this.availableBoards.length}}
+ <dropdown.subheader>
+ {{i18n "boards.topic_footer.add_to_board"}}
+ </dropdown.subheader>
+ {{#each this.availableBoards as |board|}}
+ <dropdown.item
+ class="discourse-boards-add-from-topic-menu__board-item"
+ {{on
+ "mouseenter"
+ (fn this.openBoardSubmenu board)
+ passive=true
+ }}
+ >
+ <DButton
+ @actionParam={{board}}
+ @action={{this.openBoardSubmenu}}
+ @forwardEvent={{true}}
+ @suffixIcon="angle-right"
+ @translatedLabel={{board.fancyTitle}}
+ class="btn-transparent discourse-boards-add-from-topic-menu__board"
+ />
+ </dropdown.item>
+ {{/each}}
+ {{/if}}
+ {{#if this.alreadyAddedBoards.length}}
+ <dropdown.subheader>
+ {{i18n "boards.topic_footer.already_added"}}
+ </dropdown.subheader>
+ {{#each this.alreadyAddedBoards as |board|}}
+ <dropdown.item
+ class="discourse-boards-add-from-topic-menu__board-item"
+ {{on
+ "mouseenter"
+ (fn this.openBoardSubmenu board)
+ passive=true
+ }}
+ >
+ <DButton
+ @actionParam={{board}}
+ @action={{this.openBoardSubmenu}}
+ @forwardEvent={{true}}
+ @suffixIcon="angle-right"
+ @translatedLabel={{board.fancyTitle}}
+ class="btn-transparent discourse-boards-add-from-topic-menu__board"
+ />
+ </dropdown.item>
+ {{/each}}
+ {{/if}}
+ {{else}}
+ <dropdown.item class="discourse-boards-add-from-topic-menu__empty">
+ {{i18n "boards.topic_footer.no_boards"}}
+ </dropdown.item>
+ {{/if}}
+ {{/if}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs
new file mode 100644
index 00000000000..89286f5eeac
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-board-viewer.gjs
@@ -0,0 +1,1544 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { cancel, next, schedule } from "@ember/runloop";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import BackButton from "discourse/components/back-button";
+import PermanentlyDeleteConfirmModal from "discourse/components/modal/permanently-delete-confirm";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import bodyClass from "discourse/helpers/body-class";
+import { reload } from "discourse/helpers/page-reloader";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { waitForAnimationEnd } from "discourse/lib/animation-utils";
+import { bind } from "discourse/lib/decorators";
+import { isTesting } from "discourse/lib/environment";
+import discourseLater from "discourse/lib/later";
+import DiscourseURL from "discourse/lib/url";
+import { prefersReducedMotion } from "discourse/lib/utilities";
+import Category from "discourse/models/category";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dBoundCategoryLink from "discourse/ui-kit/helpers/d-bound-category-link";
+import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ autoScrollSpeedForPointer,
+ dragToScroll,
+} from "../lib/boards-auto-scroll";
+import {
+ isRecencyColumn,
+ sortCardsForColumn,
+} from "../lib/boards-card-ordering";
+import { boardsBoardConfigureUrl, boardsBoardUrl } from "../lib/boards-urls";
+import Board from "../models/board";
+import Card from "../models/card";
+import Column from "../models/column";
+import BoardsColumn from "./boards-column";
+import BoardsBoardSettings from "./modal/boards-board-settings";
+import BoardsCardDetailModal from "./modal/boards-card-detail";
+import BoardsColumnSettings from "./modal/boards-column-settings";
+import BoardsConstraintFix from "./modal/boards-constraint-fix";
+import BoardsTopicCardDetailModal from "./modal/boards-topic-card-detail";
+
+const onWindowResize = modifier((element, [callback]) => {
+ const wrappedCallback = () => callback(element);
+ window.addEventListener("resize", wrappedCallback);
+
+ const visualViewport = window.visualViewport;
+ if (visualViewport) {
+ visualViewport.addEventListener("resize", wrappedCallback);
+ }
+
+ return () => {
+ window.removeEventListener("resize", wrappedCallback);
+ if (visualViewport) {
+ visualViewport.removeEventListener("resize", wrappedCallback);
+ }
+ };
+});
+
+const matchLastColumnHeight = modifier((element) => {
+ const container = element.parentElement;
+ if (!container) {
+ return;
+ }
+
+ const update = () => {
+ const columns = container.querySelectorAll(
+ ":scope > .discourse-boards-column"
+ );
+ const last = columns[columns.length - 1];
+ element.style.height = last ? `${last.offsetHeight}px` : "";
+ columns.forEach((col) => ro.observe(col));
+ };
+
+ const ro = new ResizeObserver(update);
+ ro.observe(container);
+ update();
+
+ return () => ro.disconnect();
+});
+
+function calcAvailableHeight(element) {
+ schedule("afterRender", () => {
+ const vv = window.visualViewport;
+ const viewportHeight = vv?.height ?? window.innerHeight;
+ const offsetTop = vv?.offsetTop ?? 0;
+ const top = element.getBoundingClientRect().top - offsetTop;
+ const available = viewportHeight - top;
+ document.documentElement.style.setProperty(
+ "--discourse-boards-available-height",
+ `${available}px`
+ );
+ });
+}
+
+export function shouldRefetchMovedCardPayload(existingCard, cardPayload) {
+ return !existingCard && !!cardPayload?.topic_id && !cardPayload.topic;
+}
+
+export default class BoardsBoardViewer extends Component {
+ @service appEvents;
+ @service composer;
+ @service dialog;
+ @service messageBus;
+ @service modal;
+ @service router;
+ @service toasts;
+
+ @tracked board;
+ @tracked columns;
+ @tracked dragData = null;
+ @tracked dropHighlightCardId = null;
+ @tracked fullscreen = false;
+ @tracked linkHighlightCardId = null;
+ @tracked linkedCardId = null;
+
+ horizontalAutoScrollFrame = null;
+ horizontalAutoScrollSpeed = 0;
+ horizontalAutoScrollContainer = null;
+ horizontalAutoScrollHasDocumentListeners = false;
+ stopHorizontalAutoScroll = () => this.#stopHorizontalAutoScroll();
+ updateHorizontalAutoScroll = (event) => {
+ if (!this.dragData || !this.horizontalAutoScrollContainer) {
+ this.#stopHorizontalAutoScroll();
+ return;
+ }
+
+ this.#updateHorizontalAutoScroll(
+ this.horizontalAutoScrollContainer,
+ event.clientX
+ );
+ };
+
+ setupMessageBus = modifier((element) => {
+ const channel = `/boards/${this.board.id}`;
+ this.messageBus.subscribe(channel, this.onBoardMessage);
+
+ const handleKeyboardMove = (event) => {
+ this.#handleCardMoved(event.detail);
+ };
+ element.addEventListener("boards:card-moved", handleKeyboardMove);
+
+ return () => {
+ this.messageBus.unsubscribe(channel, this.onBoardMessage);
+ element.removeEventListener("boards:card-moved", handleKeyboardMove);
+ };
+ });
+
+ _promotionAppEventListenersBound = false;
+ _promotionRouteListenerBound = false;
+
+ constructor() {
+ super(...arguments);
+ this.board = Board.create(this.args.model.board);
+ this.columns = this.args.model.columns.map((column) =>
+ Column.create(column)
+ );
+
+ if (this.args.initialCardId) {
+ schedule("afterRender", () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ const card = this.#findCard(this.args.initialCardId);
+ if (card) {
+ this.#openInitialCardModal(card);
+ } else {
+ DiscourseURL.routeTo(boardsBoardUrl(this.board));
+ }
+ });
+ }
+
+ if (this.args.highlightCardId) {
+ schedule("afterRender", () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ this.#focusHighlightCard(this.args.highlightCardId);
+ });
+ }
+
+ if (this.args.openBoardSettings && this.canManage) {
+ schedule("afterRender", () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ this.#openBoardSettingsModal({ updateUrl: false });
+ });
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this._clearDropHighlight();
+ this._cleanupPromotion();
+ this.#stopHorizontalAutoScroll();
+ }
+
+ @bind
+ onBoardMessage(data) {
+ if (data.client_id && data.client_id === this.messageBus.clientId) {
+ return;
+ }
+
+ switch (data.type) {
+ case "card_created":
+ this.#handleCardCreated(data.card);
+ break;
+ case "card_updated":
+ this.#handleCardUpdated(data.card);
+ break;
+ case "card_moved":
+ this.#handleCardMoved(data.card);
+ break;
+ case "card_deleted":
+ this.#handleCardDeleted(data.card_id);
+ break;
+ case "column_cleared":
+ this.#handleColumnCleared(data.column_id);
+ break;
+ case "columns_reordered":
+ this.#handleColumnsReordered(data.column_order);
+ break;
+ case "board_updated":
+ this.#handleBoardUpdated();
+ break;
+ }
+ }
+
+ #handleCardCreated(card) {
+ if (card.topic_id && !card.topic) {
+ this.#handleBoardUpdated();
+ 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;
+ });
+ }
+
+ #handleCardUpdated(card) {
+ this.columns = this.columns.map((col) => {
+ const cards = col.cards.map((c) => (c.id === card.id ? c.copy(card) : c));
+ return col.copy({ cards: sortCardsForColumn(col, cards) });
+ });
+ }
+
+ #handleCardMoved(card) {
+ const existing = this.#findCard(card.id);
+ if (shouldRefetchMovedCardPayload(existing, card)) {
+ this.#handleBoardUpdated();
+ return;
+ }
+
+ const mergedCard = existing ? existing.copy(card) : Card.create(card);
+
+ const withoutCard = this.columns.map((col) =>
+ col.copy({
+ cards: col.cards.filter((c) => c.id !== card.id),
+ })
+ );
+
+ this.columns = withoutCard.map((col) => {
+ if (col.id === mergedCard.column_id) {
+ return col.copy({
+ cards: sortCardsForColumn(col, [...col.cards, mergedCard]),
+ });
+ }
+ return col;
+ });
+ }
+
+ #handleCardDeleted(cardId) {
+ this.columns = this.columns.map((col) =>
+ col.copy({
+ cards: col.cards.filter((c) => c.id !== cardId),
+ })
+ );
+ }
+
+ #handleColumnCleared(columnId) {
+ this.columns = this.columns.map((col) => {
+ if (col.id === columnId) {
+ return col.copy({ cards: [] });
+ }
+ return col;
+ });
+ }
+
+ #handleColumnsReordered(columnOrder) {
+ const orderMap = new Map(columnOrder.map((id, idx) => [id, idx]));
+ this.columns = [...this.columns].sort(
+ (a, b) =>
+ (orderMap.get(a.id) ?? Infinity) - (orderMap.get(b.id) ?? Infinity)
+ );
+ }
+
+ async #handleBoardUpdated() {
+ try {
+ const result = await ajax(`/boards/api/boards/${this.board.id}.json`);
+ if (result.columns) {
+ this.columns = result.columns.map((col) =>
+ Column.create({
+ ...col,
+ cards: sortCardsForColumn(col, col.cards || []),
+ })
+ );
+ }
+ Object.assign(this.board, result.board || result);
+ } catch {
+ // Board may have been deleted β€” no action needed
+ }
+ }
+
+ @bind
+ refreshBoard() {
+ return this.#handleBoardUpdated();
+ }
+
+ get canWrite() {
+ return this.board.can_write;
+ }
+
+ get canManage() {
+ return this.board.can_manage;
+ }
+
+ get boardCategories() {
+ return (this.board.category_ids || [])
+ .map((id) => Category.findById(id))
+ .filter(Boolean);
+ }
+
+ get boardTagNames() {
+ return this.board.tag_names || [];
+ }
+
+ get hasBoardFilters() {
+ return this.boardCategories.length > 0 || this.boardTagNames.length > 0;
+ }
+
+ get allSameCategory() {
+ let seenCategory = null;
+ for (const col of this.columns) {
+ for (const card of col.cards || []) {
+ const catId = card.topic?.category_id;
+ if (catId == null) {
+ continue;
+ }
+ if (seenCategory === null) {
+ seenCategory = catId;
+ } else if (seenCategory !== catId) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ @action
+ toggleFullscreen() {
+ this.fullscreen = !this.fullscreen;
+ }
+
+ @action
+ exitFullscreen() {
+ this.fullscreen = false;
+ }
+
+ @action
+ onDragStart(data) {
+ this.dragData = data;
+ }
+
+ @action
+ onDragEnd(cardId) {
+ next(this, () => {
+ if (this.dragData?.cardId === cardId) {
+ this.dragData = null;
+ }
+ });
+ }
+
+ @action
+ dragOverBoardContainer(event) {
+ const dragData = this.dragData;
+ if (!dragData) {
+ this.#stopHorizontalAutoScroll();
+ return;
+ }
+
+ event.preventDefault();
+ this.#updateHorizontalAutoScroll(event.currentTarget, event.clientX);
+ }
+
+ @action
+ dragLeaveBoardContainer(event) {
+ if (!this.dragData && !event.currentTarget.contains(event.relatedTarget)) {
+ this.#stopHorizontalAutoScroll();
+ }
+ }
+
+ @action
+ dropBoardContainer() {
+ this.#stopHorizontalAutoScroll();
+ }
+
+ @action
+ async onDrop(cardId, toColumnId, afterCardId, fromColumnId) {
+ if (!fromColumnId) {
+ return;
+ }
+
+ const fromColumn = this.columns.find((c) => c.id === fromColumnId);
+ const toColumn = this.columns.find((c) => c.id === toColumnId);
+ if (!fromColumn || !toColumn) {
+ return;
+ }
+
+ const cardIndex = fromColumn.cards.findIndex((c) => c.id === cardId);
+ if (cardIndex === -1) {
+ return;
+ }
+
+ const card = fromColumn.cards[cardIndex];
+ const isSameColumn = fromColumnId === toColumnId;
+ const targetIsRecency = isRecencyColumn(toColumn);
+ if (isSameColumn && targetIsRecency) {
+ this.dragData = null;
+ return;
+ }
+
+ if (targetIsRecency) {
+ afterCardId = null;
+ }
+
+ let constraintFix = null;
+
+ if (!isSameColumn && card.topic) {
+ try {
+ constraintFix = await this.#resolveConstraintFix(
+ card.topic_id || card.topic.id,
+ card.topic,
+ toColumn
+ );
+ } catch (error) {
+ popupAjaxError(error);
+ return;
+ }
+
+ if (constraintFix === false) {
+ return;
+ }
+ }
+
+ if (!isSameColumn && !constraintFix && this.board.require_confirmation) {
+ const confirmed = await this._confirmMove(card, toColumn);
+ if (!confirmed) {
+ return;
+ }
+ }
+
+ const snapshot = this.columns.map((col) =>
+ col.copy({ cards: col.cards.map((c) => c.copy()) })
+ );
+
+ fromColumn.cards.splice(cardIndex, 1);
+
+ let insertIndex = targetIsRecency ? 0 : toColumn.cards.length;
+ if (!targetIsRecency && afterCardId != null) {
+ const idx = toColumn.cards.findIndex((c) => c.id === afterCardId);
+ if (idx !== -1) {
+ insertIndex = idx + 1;
+ }
+ } else {
+ insertIndex = 0;
+ }
+ toColumn.cards.splice(insertIndex, 0, card);
+ card.column_id = toColumnId;
+
+ this.columns = this.columns.map((col) => {
+ if (col.id === fromColumnId || col.id === toColumnId) {
+ return col.copy({ cards: [...col.cards] });
+ }
+ return col;
+ });
+ this.dragData = null;
+
+ const data = {
+ client_id: this.messageBus.clientId,
+ card: {
+ column_id: toColumnId,
+ after_card_id: afterCardId,
+ },
+ };
+ if (constraintFix) {
+ data.constraint_fix = constraintFix;
+ }
+
+ try {
+ const result = await ajax(
+ `/boards/api/boards/${this.board.id}/cards/${card.id}`,
+ { type: "PUT", data }
+ );
+ if (result?.card) {
+ const existingCard = this.columns
+ .flatMap((col) => col.cards)
+ .find((c) => c.id === result.card.id);
+ const mergedCard = existingCard
+ ? existingCard.copy(result.card)
+ : Card.create(result.card);
+ const withoutCard = this.columns.map((col) =>
+ col.copy({
+ cards: col.cards.filter((c) => c.id !== result.card.id),
+ })
+ );
+
+ this.columns = withoutCard.map((col) => {
+ if (col.id === mergedCard.column_id) {
+ return col.copy({
+ cards: sortCardsForColumn(col, [...col.cards, mergedCard]),
+ });
+ }
+ return col;
+ });
+ }
+ this._highlightDroppedCard(card.id);
+ } catch (error) {
+ this.columns = snapshot;
+ popupAjaxError(error);
+ }
+ }
+
+ #updateHorizontalAutoScroll(container, clientX) {
+ const speed = autoScrollSpeedForPointer(
+ clientX,
+ container.getBoundingClientRect(),
+ "x"
+ );
+
+ if (
+ (speed < 0 && container.scrollLeft <= 0) ||
+ (speed > 0 &&
+ container.scrollLeft + container.clientWidth >= container.scrollWidth)
+ ) {
+ this.#stopHorizontalAutoScroll();
+ return;
+ }
+
+ this.horizontalAutoScrollSpeed = speed;
+ this.horizontalAutoScrollContainer = container;
+ this.#ensureHorizontalAutoScrollDocumentListeners();
+
+ if (speed === 0) {
+ this.#stopHorizontalAutoScroll();
+ return;
+ }
+
+ if (!this.horizontalAutoScrollFrame) {
+ this.#horizontalAutoScroll();
+ }
+ }
+
+ #horizontalAutoScroll() {
+ this.horizontalAutoScrollFrame = requestAnimationFrame(() => {
+ this.horizontalAutoScrollFrame = null;
+
+ const container = this.horizontalAutoScrollContainer;
+ if (!container || this.horizontalAutoScrollSpeed === 0) {
+ return;
+ }
+
+ const previousScrollLeft = container.scrollLeft;
+ container.scrollLeft += this.horizontalAutoScrollSpeed;
+
+ if (container.scrollLeft === previousScrollLeft) {
+ this.#stopHorizontalAutoScroll();
+ return;
+ }
+
+ this.#horizontalAutoScroll();
+ });
+ }
+
+ #ensureHorizontalAutoScrollDocumentListeners() {
+ if (this.horizontalAutoScrollHasDocumentListeners) {
+ return;
+ }
+
+ document.addEventListener(
+ "dragover",
+ this.updateHorizontalAutoScroll,
+ true
+ );
+ document.addEventListener("dragend", this.stopHorizontalAutoScroll, true);
+ document.addEventListener("drop", this.stopHorizontalAutoScroll, true);
+ this.horizontalAutoScrollHasDocumentListeners = true;
+ }
+
+ #removeHorizontalAutoScrollDocumentListeners() {
+ if (!this.horizontalAutoScrollHasDocumentListeners) {
+ return;
+ }
+
+ document.removeEventListener(
+ "dragover",
+ this.updateHorizontalAutoScroll,
+ true
+ );
+ document.removeEventListener(
+ "dragend",
+ this.stopHorizontalAutoScroll,
+ true
+ );
+ document.removeEventListener("drop", this.stopHorizontalAutoScroll, true);
+ this.horizontalAutoScrollHasDocumentListeners = false;
+ }
+
+ #stopHorizontalAutoScroll() {
+ if (this.horizontalAutoScrollFrame) {
+ cancelAnimationFrame(this.horizontalAutoScrollFrame);
+ this.horizontalAutoScrollFrame = null;
+ }
+
+ this.horizontalAutoScrollSpeed = 0;
+ this.horizontalAutoScrollContainer = null;
+ this.#removeHorizontalAutoScrollDocumentListeners();
+ }
+
+ _showConstraintFixModal(topic, column, mismatches) {
+ return new Promise((resolve) => {
+ this.modal.show(BoardsConstraintFix, {
+ model: {
+ topic,
+ board: this.board,
+ column,
+ mismatches,
+ onConfirm: (result) => resolve(result),
+ onCancel: () => resolve(null),
+ },
+ });
+ });
+ }
+
+ _confirmMove(card, toColumn) {
+ return new Promise((resolve) => {
+ const cardTitle = card.fancyTitle || "";
+ this.dialog.yesNoConfirm({
+ message: i18n("boards.board.move_confirm", {
+ topic_title: cardTitle,
+ column_title: toColumn.fancyTitle,
+ }),
+ didConfirm: () => resolve(true),
+ didCancel: () => resolve(false),
+ });
+ });
+ }
+
+ @action
+ async onDeleteCard(cardId) {
+ const snapshot = this.columns.map((col) =>
+ col.copy({ cards: [...col.cards] })
+ );
+
+ this.columns = this.columns.map((col) =>
+ col.copy({
+ cards: col.cards.filter((c) => c.id !== cardId),
+ })
+ );
+
+ try {
+ await ajax(`/boards/api/boards/${this.board.id}/cards/${cardId}`, {
+ type: "DELETE",
+ data: { client_id: this.messageBus.clientId },
+ });
+ } catch (error) {
+ this.columns = snapshot;
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async onUpdateCard(cardId, updates) {
+ try {
+ const result = await ajax(
+ `/boards/api/boards/${this.board.id}/cards/${cardId}`,
+ {
+ type: "PUT",
+ data: { client_id: this.messageBus.clientId, card: updates },
+ }
+ );
+
+ if (result.card) {
+ if (result.adopted_floater_id) {
+ this.columns = this.columns.map((col) =>
+ col.copy({
+ cards: col.cards.filter((c) => c.id !== cardId),
+ })
+ );
+ this.#handleCardMoved(result.card);
+ } else {
+ this.#handleCardUpdated(result.card);
+ }
+ }
+ } catch (error) {
+ popupAjaxError(error);
+ throw error;
+ }
+ }
+
+ @action
+ async onAddCard({
+ topicId,
+ title,
+ columnId,
+ notes,
+ tag_ids,
+ assigned_to_name,
+ }) {
+ if (topicId) {
+ try {
+ const column = this.columns.find(
+ (candidate) => candidate.id === columnId
+ );
+ const constraintFix = await this.#resolveConstraintFix(
+ topicId,
+ { id: topicId },
+ column
+ );
+ if (constraintFix === false) {
+ return;
+ }
+
+ const data = {
+ client_id: this.messageBus.clientId,
+ card: { column_id: columnId, topic_id: topicId },
+ };
+ if (constraintFix) {
+ data.constraint_fix = constraintFix;
+ }
+
+ const result = await ajax(`/boards/api/boards/${this.board.id}/cards`, {
+ type: "POST",
+ data,
+ });
+ this.#appendCardToColumn(result.card, columnId);
+ return;
+ } catch (error) {
+ if (this.#isTopicNotFoundError(error)) {
+ await this.#createFallbackFloater(title, columnId);
+ return;
+ }
+ popupAjaxError(error);
+ return;
+ }
+ }
+
+ try {
+ const result = await ajax(`/boards/api/boards/${this.board.id}/cards`, {
+ type: "POST",
+ data: {
+ client_id: this.messageBus.clientId,
+ card: {
+ column_id: columnId,
+ title,
+ notes,
+ tag_ids,
+ assigned_to_name,
+ },
+ },
+ });
+ this.#appendCardToColumn(result.card, columnId);
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ async #resolveConstraintFix(topicId, topic, column) {
+ if (!column) {
+ return null;
+ }
+
+ const response = await ajax(
+ `/boards/api/boards/${this.board.id}/check-constraint-mismatches`,
+ {
+ method: "PUT",
+ data: {
+ topic_id: topicId,
+ target_column_id: column.id,
+ },
+ }
+ );
+
+ if (!response.constraints_need_fixing) {
+ return null;
+ }
+
+ const mismatches = {
+ needsTags: response.tags_needed.length > 0,
+ needsCategory: response.categories_needed.length > 0,
+ boardTagNames: response.tags_needed,
+ boardCategoryIds: response.categories_needed,
+ };
+
+ const constraintFix = await this._showConstraintFixModal(
+ topic,
+ column,
+ mismatches
+ );
+
+ return constraintFix ?? false;
+ }
+
+ #isTopicNotFoundError(error) {
+ return error?.jqXHR?.status === 404;
+ }
+
+ #appendCardToColumn(card, columnId) {
+ if (!card) {
+ return;
+ }
+ card = Card.create(card);
+ this.columns = this.columns.map((col) => {
+ if (col.id === columnId) {
+ return col.copy({
+ cards: sortCardsForColumn(col, [
+ ...col.cards.filter((c) => c.id !== card.id),
+ card,
+ ]),
+ });
+ }
+ return col;
+ });
+ }
+
+ async #createFallbackFloater(title, columnId) {
+ try {
+ const result = await ajax(`/boards/api/boards/${this.board.id}/cards`, {
+ type: "POST",
+ data: {
+ client_id: this.messageBus.clientId,
+ card: { column_id: columnId, title },
+ },
+ });
+ this.#appendCardToColumn(result.card, columnId);
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ onPromoteToTopic(cardId) {
+ let card;
+ let column;
+ for (const col of this.columns) {
+ const found = col.cards.find((c) => c.id === cardId);
+ if (found) {
+ card = found;
+ column = col;
+ break;
+ }
+ }
+ if (!card) {
+ return;
+ }
+
+ this._promotingCardId = cardId;
+ this.#bindPromotionListeners();
+
+ const opts = { title: card.title };
+ if (card.notes) {
+ opts.body = card.notes;
+ }
+
+ const tagNames = new Set();
+ if (card.tags?.length) {
+ card.tags.forEach((tag) => tagNames.add(tag.name));
+ }
+ if (this.board.tag_names?.length) {
+ this.board.tag_names.forEach((name) => tagNames.add(name));
+ }
+ if (column.tag_name) {
+ tagNames.add(column.tag_name);
+ }
+ if (tagNames.size) {
+ opts.tags = [...tagNames].join(",");
+ }
+
+ const categoryId =
+ column.move_to_category_id || this.board.category_ids?.[0];
+ if (categoryId) {
+ opts.category = Category.findById(categoryId);
+ }
+ this.composer.openNewTopic(opts);
+ }
+
+ // Column management actions
+
+ @action
+ openAddColumnModal(closeMenu) {
+ if (typeof closeMenu === "function") {
+ closeMenu();
+ }
+ this.modal.show(BoardsColumnSettings, {
+ model: {
+ column: null,
+ board: this.board,
+ onSave: (columnData) => this.addColumn(columnData),
+ },
+ });
+ }
+
+ @action
+ openEditColumnModal(columnId) {
+ const column = this.columns.find((c) => c.id === columnId);
+ if (!column) {
+ return;
+ }
+ this.modal.show(BoardsColumnSettings, {
+ model: {
+ column,
+ board: this.board,
+ onSave: (columnData) => this.editColumn(columnId, columnData),
+ },
+ });
+ }
+
+ _serializeColumn(col) {
+ return {
+ id: col.id,
+ title: col.title,
+ icon: col.icon,
+ color: col.color || null,
+ default_sort: col.default_sort || "priority",
+ tag_name: col.tag_name || null,
+ move_to_category_id: col.move_to_category_id,
+ move_to_assigned:
+ col.move_to_assigned === "_user" ? "" : col.move_to_assigned,
+ move_to_status: col.move_to_status,
+ };
+ }
+
+ @action
+ async addColumn(columnData) {
+ await this._saveColumn(
+ "POST",
+ `/boards/api/boards/${this.board.id}/columns`,
+ {
+ column: this._serializeColumn(columnData),
+ }
+ );
+ }
+
+ @action
+ async editColumn(columnId, columnData) {
+ const column = this.columns.find((col) => col.id === columnId);
+ if (!column) {
+ return;
+ }
+
+ await this._saveColumn(
+ "PUT",
+ `/boards/api/boards/${this.board.id}/columns/${columnId}`,
+ { column: this._serializeColumn(column.copy(columnData)) }
+ );
+ }
+
+ @action
+ async moveColumn(columnId, direction) {
+ const index = this.columns.findIndex((c) => c.id === columnId);
+ if (index === -1) {
+ return;
+ }
+ const newIndex = index + direction;
+ if (newIndex < 0 || newIndex >= this.columns.length) {
+ return;
+ }
+
+ const snapshot = this.columns;
+ const reordered = [...this.columns];
+ [reordered[index], reordered[newIndex]] = [
+ reordered[newIndex],
+ reordered[index],
+ ];
+
+ this.columns = reordered;
+ try {
+ const result = await ajax(
+ `/boards/api/boards/${this.board.id}/move-column`,
+ {
+ type: "POST",
+ data: {
+ column_id: columnId,
+ direction,
+ client_id: this.messageBus.clientId,
+ },
+ }
+ );
+ if (result?.column_order) {
+ this.#handleColumnsReordered(result.column_order);
+ }
+ } catch (error) {
+ this.columns = snapshot;
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ async deleteColumn(column) {
+ const saveColumns = async () => {
+ try {
+ return await this._saveColumn(
+ "DELETE",
+ `/boards/api/boards/${this.board.id}/columns/${column.id}`
+ );
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ };
+
+ // No need for confirmation if there are no cards in the column.
+ if (column.cards.length === 0) {
+ await saveColumns();
+ return;
+ }
+
+ // Need a bit of a stronger delete confirmation when getting rid
+ // of a lot of cards.
+ if (column.cards.length > 5) {
+ return this.modal.show(PermanentlyDeleteConfirmModal, {
+ model: {
+ message: i18n("boards.board.confirm_delete_column_with_cards", {
+ count: column.cards.length,
+ }),
+ confirmPhrase: column.title,
+ didConfirm: () => {
+ saveColumns();
+ },
+ },
+ });
+ }
+
+ this.dialog.confirm({
+ message: i18n("boards.board.confirm_delete_column"),
+ didConfirm: saveColumns,
+ });
+ }
+
+ @action
+ clearColumn(columnId) {
+ const column = this.columns.find((col) => col.id === columnId);
+ const cardCount = column?.cards?.length || 0;
+ if (cardCount === 0) {
+ return;
+ }
+
+ this.dialog.confirm({
+ message: i18n("boards.board.confirm_clear_column", {
+ count: cardCount,
+ column_title: column.fancyTitle,
+ }),
+ didConfirm: async () => {
+ const snapshot = this.columns.map((col) =>
+ col.copy({ cards: [...col.cards] })
+ );
+
+ this.columns = this.columns.map((col) => {
+ if (col.id === columnId) {
+ return col.copy({ cards: [] });
+ }
+ return col;
+ });
+
+ try {
+ await ajax(
+ `/boards/api/boards/${this.board.id}/columns/${columnId}/cards`,
+ {
+ type: "DELETE",
+ data: { client_id: this.messageBus.clientId },
+ }
+ );
+ } catch (error) {
+ this.columns = snapshot;
+ popupAjaxError(error);
+ }
+ },
+ });
+ }
+
+ // Board settings actions
+
+ @action
+ openBoardSettings(closeMenu) {
+ closeMenu();
+ this.#openBoardSettingsModal();
+ }
+
+ #openBoardSettingsModal({ updateUrl = true } = {}) {
+ const boardUrl = boardsBoardUrl(this.board);
+
+ if (updateUrl) {
+ DiscourseURL.replaceState(boardsBoardConfigureUrl(this.board));
+ }
+
+ this.modal
+ .show(BoardsBoardSettings, {
+ model: {
+ board: this.board,
+ isNew: false,
+ onSave: (boardData) => this.saveBoardSettings(boardData),
+ onDelete: () => this.deleteBoard(),
+ },
+ })
+ .then((result) => {
+ if (!this.isDestroying && !this.isDestroyed) {
+ DiscourseURL.replaceState(boardUrl);
+
+ if (result?.reloadAfterSave) {
+ reload();
+ }
+ }
+ });
+ }
+
+ @action
+ async saveBoardSettings(boardData) {
+ const payload = {
+ board: boardData,
+ };
+
+ const originalSlug = this.board.slug;
+
+ const result = await ajax(`/boards/api/boards/${this.board.id}`, {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify(payload),
+ });
+
+ if (result.board) {
+ this.board = Board.create({ ...this.board, ...result.board });
+ }
+
+ this.toasts.success({
+ data: { message: i18n("saved") },
+ duration: "short",
+ });
+
+ if (this.board.slug && this.board.slug !== originalSlug) {
+ this.router.replaceWith("boardsBoard", this.board.slug, this.board.id);
+ }
+ }
+
+ @action
+ deleteBoard(closeMenu) {
+ closeMenu?.();
+ this.dialog.confirm({
+ message: i18n("boards.manage.confirm_delete"),
+ didConfirm: async () => {
+ try {
+ await ajax(`/boards/api/boards/${this.board.id}`, {
+ type: "DELETE",
+ });
+ this.router.transitionTo("boards");
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ },
+ });
+ }
+
+ @action
+ goToAllBoards(closeMenu) {
+ closeMenu?.();
+ this.router.transitionTo("boards");
+ }
+
+ async _saveColumn(type, url, payload = {}) {
+ await ajax(url, {
+ type,
+ contentType: "application/json",
+ data: JSON.stringify({
+ ...payload,
+ client_id: this.messageBus.clientId,
+ }),
+ });
+
+ this.toasts.success({
+ data: { message: i18n("saved") },
+ duration: "short",
+ });
+
+ await this.#handleBoardUpdated();
+ }
+
+ @bind
+ _onTopicCreated(createdPost) {
+ const cardId = this._promotingCardId;
+ this._cleanupPromotion();
+ this.onUpdateCard(cardId, { topic_id: createdPost.topic_id });
+ }
+
+ @bind
+ _onRouteWillChange(transition) {
+ if (this._promotingCardId) {
+ transition.abort();
+ this.#unbindPromotionRouteListener();
+ this._promotingCardId = null;
+ }
+ }
+
+ _cleanupPromotion() {
+ this._promotingCardId = null;
+ this.#unbindPromotionAppEventListeners();
+ this.#unbindPromotionRouteListener();
+ }
+
+ #bindPromotionListeners() {
+ if (!this._promotionAppEventListenersBound) {
+ this.appEvents.on("topic:created", this, this._onTopicCreated);
+ this.appEvents.on("composer:cancelled", this, this._cleanupPromotion);
+ this._promotionAppEventListenersBound = true;
+ }
+
+ if (!this._promotionRouteListenerBound) {
+ this.router.on("routeWillChange", this._onRouteWillChange);
+ this._promotionRouteListenerBound = true;
+ }
+ }
+
+ #unbindPromotionAppEventListeners() {
+ if (!this._promotionAppEventListenersBound) {
+ return;
+ }
+
+ this.appEvents.off("topic:created", this, this._onTopicCreated);
+ this.appEvents.off("composer:cancelled", this, this._cleanupPromotion);
+ this._promotionAppEventListenersBound = false;
+ }
+
+ #unbindPromotionRouteListener() {
+ if (!this._promotionRouteListenerBound) {
+ return;
+ }
+
+ this.router.off("routeWillChange", this._onRouteWillChange);
+ this._promotionRouteListenerBound = false;
+ }
+
+ #findCard(cardId) {
+ for (const col of this.columns) {
+ const card = col.cards.find((c) => c.id === cardId);
+ if (card) {
+ return card;
+ }
+ }
+ return null;
+ }
+
+ #focusHighlightCard(cardId) {
+ if (!this.#findCard(cardId)) {
+ return;
+ }
+
+ // The deep-linked card stays flagged for the lifetime of the board so a
+ // card outside its column's recency window keeps rendering; only the pulse
+ // highlight below is transient.
+ this.linkedCardId = cardId;
+ this.linkHighlightCardId = cardId;
+
+ // next() rather than afterRender: this can be called mid-afterRender
+ // flush, before the highlight class renders, and waitForAnimationEnd
+ // would then see no animation and fall back to resolving immediately.
+ next(this, async () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ const cardElement = document.querySelector(
+ `.discourse-boards-card[data-card-id="${cardId}"]`
+ );
+ cardElement?.scrollIntoView({ block: "center", inline: "center" });
+
+ // With reduced motion there is no animation to wait for; the static
+ // highlight stays as a persistent indicator instead.
+ if (!cardElement || isTesting() || prefersReducedMotion()) {
+ return;
+ }
+
+ await waitForAnimationEnd(cardElement);
+
+ if (
+ !this.isDestroying &&
+ !this.isDestroyed &&
+ this.linkHighlightCardId === cardId
+ ) {
+ this.linkHighlightCardId = null;
+ }
+ });
+ }
+
+ #openInitialCardModal(card) {
+ const boardUrl = boardsBoardUrl(this.board);
+ const isTopicCard = card.card_type === "topic" && card.topic;
+ const ModalComponent = isTopicCard
+ ? BoardsTopicCardDetailModal
+ : BoardsCardDetailModal;
+ let navigatedAway = false;
+
+ const column = this.columns.find((col) => col.id === card.column_id);
+ const model = isTopicCard
+ ? {
+ card,
+ columnTitle: column?.fancyTitle,
+ columnIcon: column?.icon,
+ columnColor: column?.color,
+ onNavigateAway: (url) => {
+ navigatedAway = true;
+ DiscourseURL.routeTo(url);
+ },
+ }
+ : { card, canWrite: this.canWrite, onUpdateCard: this.onUpdateCard };
+
+ this.modal.show(ModalComponent, { model }).finally(() => {
+ if (!navigatedAway && !this.isDestroying && !this.isDestroyed) {
+ DiscourseURL.replaceState(boardUrl);
+ }
+ });
+ }
+
+ _highlightDroppedCard(cardId) {
+ this._clearDropHighlight();
+ this.dropHighlightCardId = null;
+
+ schedule("afterRender", () => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.dropHighlightCardId = cardId;
+ if (isTesting()) {
+ return;
+ }
+
+ this._dropHighlightTimeout = discourseLater(
+ this,
+ () => {
+ if (this.dropHighlightCardId === cardId) {
+ this.dropHighlightCardId = null;
+ }
+ this._dropHighlightTimeout = null;
+ },
+ 1000
+ );
+ });
+ }
+
+ _clearDropHighlight() {
+ if (this._dropHighlightTimeout) {
+ cancel(this._dropHighlightTimeout);
+ this._dropHighlightTimeout = null;
+ }
+ }
+
+ <template>
+ {{#if this.fullscreen}}
+ {{bodyClass "discourse-boards-fullscreen"}}
+ {{/if}}
+
+ <div
+ class="discourse-boards-board-viewer
+ {{if this.fullscreen 'discourse-boards-board-viewer--fullscreen'}}"
+ {{this.setupMessageBus}}
+ {{onWindowResize calcAvailableHeight}}
+ {{didInsert calcAvailableHeight}}
+ >
+ <div class="discourse-boards-board-viewer__header">
+ <div class="discourse-boards-board-viewer__title-wrapper">
+ <BackButton @route="boards" @label="boards.board.all_boards" />
+ <h2
+ class="discourse-boards-board-viewer__title"
+ >{{this.board.fancyTitle}}</h2>
+
+ <div class="discourse-boards-board-viewer__metadata">
+ {{#if this.hasBoardFilters}}
+ <div class="discourse-boards-board-viewer__constraint">
+ {{#each this.boardCategories as |category|}}
+ {{dBoundCategoryLink category link=true}}
+ {{/each}}
+ {{#if this.boardTagNames.length}}
+ <div class="list-tags">
+ {{dDiscourseTags null tags=this.boardTagNames}}
+ </div>
+ {{/if}}
+ <DTooltip>
+ <:trigger>
+ {{dIcon "circle-info"}}
+ </:trigger>
+ <:content>
+ <span>{{i18n "boards.board.constraint_tooltip"}}</span>
+ </:content>
+ </DTooltip>
+ </div>
+ {{/if}}
+ </div>
+ </div>
+
+ <div class="discourse-boards-board-viewer__controls">
+ <DMenu
+ @identifier="boards-board-controls"
+ @icon="ellipsis"
+ @title="boards.board.controls"
+ @triggerClass="btn-flat"
+ >
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.canManage}}
+ <dropdown.item data-identifier="add-column">
+ <DButton
+ @action={{fn this.openAddColumnModal args.close}}
+ @icon="plus"
+ @label="boards.board.add_column"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item data-identifier="board-settings">
+ <DButton
+ @action={{fn this.openBoardSettings args.close}}
+ @icon="gear"
+ @label="boards.board.board_settings"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item data-identifier="delete-board">
+ <DButton
+ @action={{fn this.deleteBoard args.close}}
+ @icon="trash-can"
+ @label="boards.board.delete_board"
+ class="btn-transparent btn-danger"
+ />
+ </dropdown.item>
+ {{/if}}
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{#if this.fullscreen}}
+ <DButton
+ @action={{this.exitFullscreen}}
+ @icon="discourse-compress"
+ @title="boards.board.exit_fullscreen"
+ class="btn-flat discourse-boards-board-viewer__exit-fullscreen"
+ />
+ {{else}}
+ <DButton
+ @action={{this.toggleFullscreen}}
+ @icon="discourse-expand"
+ @title="boards.board.fullscreen"
+ class="btn-flat"
+ />
+ {{/if}}
+ </div>
+ </div>
+
+ {{#if this.columns.length}}
+ <div
+ class="discourse-boards-board-container"
+ {{on "dragover" this.dragOverBoardContainer}}
+ {{on "dragleave" this.dragLeaveBoardContainer}}
+ {{on "drop" this.dropBoardContainer}}
+ {{dragToScroll}}
+ >
+ {{#each this.columns key="id" as |column|}}
+ <BoardsColumn
+ @column={{column}}
+ @board={{this.board}}
+ @canWrite={{this.canWrite}}
+ @canManage={{this.canManage}}
+ @allSameCategory={{this.allSameCategory}}
+ @dropHighlightCardId={{this.dropHighlightCardId}}
+ @linkHighlightCardId={{this.linkHighlightCardId}}
+ @linkedCardId={{this.linkedCardId}}
+ @dragData={{this.dragData}}
+ @onDragStart={{this.onDragStart}}
+ @onDragEnd={{this.onDragEnd}}
+ @onDrop={{this.onDrop}}
+ @onAddCard={{this.onAddCard}}
+ @onUpdateCard={{this.onUpdateCard}}
+ @onDeleteCard={{this.onDeleteCard}}
+ @onPromoteToTopic={{this.onPromoteToTopic}}
+ @onRefreshBoard={{this.refreshBoard}}
+ @onEditColumn={{this.openEditColumnModal}}
+ @onMoveColumn={{this.moveColumn}}
+ @onDeleteColumn={{this.deleteColumn}}
+ @onClearColumn={{this.clearColumn}}
+ @allColumns={{this.columns}}
+ />
+ {{/each}}
+ {{#if this.canManage}}
+ <button
+ type="button"
+ class="discourse-boards-board-container__add-column"
+ title={{i18n "boards.board.add_column"}}
+ {{on "click" this.openAddColumnModal}}
+ {{matchLastColumnHeight}}
+ >
+ {{dIcon "plus"}}
+ </button>
+ {{/if}}
+ </div>
+ {{else}}
+ <div class="discourse-boards-board-viewer__empty">
+ <div class="discourse-boards-board-viewer__empty-column">
+ {{dIcon "table-columns"}}
+ <h3>{{i18n "boards.board.empty_board"}}</h3>
+ <p>{{i18n "boards.board.empty_board_cta"}}</p>
+ {{#if this.canManage}}
+ <DButton
+ @action={{this.openAddColumnModal}}
+ @icon="plus"
+ @label="boards.board.add_column"
+ class="btn-primary"
+ />
+ {{/if}}
+ </div>
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs
new file mode 100644
index 00000000000..ac55e39de00
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-card.gjs
@@ -0,0 +1,714 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import { cancel } from "@ember/runloop";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import TopicStatus from "discourse/components/topic-status";
+import DMenu from "discourse/float-kit/components/d-menu";
+import discourseLater from "discourse/lib/later";
+import renderTags from "discourse/lib/render-tags";
+import { emojiUnescape } from "discourse/lib/text";
+import DiscourseURL from "discourse/lib/url";
+import { escapeExpression } from "discourse/lib/utilities";
+import Category from "discourse/models/category";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { renderAvatar } from "discourse/ui-kit/helpers/d-user-avatar";
+import { i18n } from "discourse-i18n";
+import { boardsBoardUrl, boardsCardUrl } from "../lib/boards-urls";
+import AutoLinkedText from "./auto-linked-text";
+import BoardsCardDetailModal from "./modal/boards-card-detail";
+import BoardsFloaterAssignModal from "./modal/boards-floater-assign";
+import BoardsTopicCardDetailModal from "./modal/boards-topic-card-detail";
+
+export function shouldInsertSourceDropIndicator(root = document) {
+ return !root.querySelector(
+ ".discourse-boards-column__drop-indicator:not(.discourse-boards-column__drop-indicator--source)"
+ );
+}
+
+export default class BoardsCard extends Component {
+ @service currentUser;
+ @service modal;
+ @service siteSettings;
+
+ @tracked dragging = false;
+ dragHideTimer = null;
+ dragImageElement = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ const isActiveDragSource =
+ this.dragging || this.dragHideTimer || this.dragImageElement;
+
+ this.#clearDragHideTimer();
+ this.#cleanupDragImage();
+
+ if (isActiveDragSource) {
+ this.#removeDropIndicators();
+ }
+ }
+
+ get isTopicCard() {
+ return this.args.card.card_type === "topic" && this.args.card.topic;
+ }
+
+ get topic() {
+ return this.args.card.topic;
+ }
+
+ get cardTitle() {
+ return this.args.card.fancyTitle;
+ }
+
+ get renderedTopicTitle() {
+ return trustHTML(emojiUnescape(escapeExpression(this.cardTitle || "")));
+ }
+
+ get inlineOneboxData() {
+ const data = this.args.card.inline_onebox_data;
+ return data?.url && data?.title ? data : null;
+ }
+
+ get columnTagNames() {
+ return new Set(
+ (this.args.columnTags || []).map((tag) => tag.toLowerCase())
+ );
+ }
+
+ get visibleFloaterTags() {
+ const tags = this.args.card.tags || [];
+ if (!tags.length) {
+ return [];
+ }
+
+ return tags.filter((tag) => {
+ const name = typeof tag === "string" ? tag : tag.name;
+ return !this.columnTagNames.has(name?.toLowerCase());
+ });
+ }
+
+ get tagsHtml() {
+ if (this.isTopicCard) {
+ if (!this.args.board.show_tags || !this.topic?.tags) {
+ return null;
+ }
+
+ const filtered = this.topic.tags.filter(
+ (tag) => !this.columnTagNames.has(tag.toLowerCase())
+ );
+
+ return filtered.length ? renderTags(null, { tags: filtered }) : null;
+ }
+
+ const tags = this.visibleFloaterTags;
+ return tags.length ? renderTags(null, { tags }) : null;
+ }
+
+ get category() {
+ if (this.args.allSameCategory || !this.topic?.category_id) {
+ return null;
+ }
+ return Category.findById(this.topic.category_id);
+ }
+
+ get isDetailed() {
+ return this.args.board.card_style === "detailed";
+ }
+
+ get showImage() {
+ return this.args.board.show_topic_thumbnail && this.topic?.image_url;
+ }
+
+ get allAssignedUsers() {
+ if (this.topic?.all_assigned_users?.length) {
+ return this.topic.all_assigned_users;
+ }
+ if (this.topic?.assigned_to_user) {
+ return [this.topic.assigned_to_user];
+ }
+ const floaterAssignment = this.args.card.assigned_to;
+ if (
+ !this.isTopicCard &&
+ this.siteSettings.assign_enabled &&
+ floaterAssignment?.type === "User"
+ ) {
+ return [floaterAssignment];
+ }
+ return [];
+ }
+
+ get assignedUser() {
+ return this.allAssignedUsers[0] ?? null;
+ }
+
+ get assignedGroup() {
+ if (!this.siteSettings.assign_enabled) {
+ return null;
+ }
+ const floaterAssignment = this.args.card.assigned_to;
+ if (!this.isTopicCard && floaterAssignment?.type === "Group") {
+ return floaterAssignment;
+ }
+ return null;
+ }
+
+ get assignedAvatarHtml() {
+ const users = this.allAssignedUsers;
+ if (!users.length) {
+ return null;
+ }
+ return users
+ .map((user) =>
+ renderAvatar(user, {
+ avatarTemplatePath: "avatar_template",
+ usernamePath: "username",
+ imageSize: "tiny",
+ })
+ )
+ .join("");
+ }
+
+ get lastPosterUsername() {
+ if (this.isTopicCard) {
+ return this.topic?.last_poster?.username;
+ }
+ return this.args.card.created_by?.username;
+ }
+
+ get activityDate() {
+ return (
+ this.args.card.recency_at ||
+ (this.isTopicCard ? this.topic?.bumped_at : this.args.card.created_at)
+ );
+ }
+
+ get topicStatusModel() {
+ if (!this.isTopicCard) {
+ return null;
+ }
+ return { closed: this.topic?.closed };
+ }
+
+ get canShowActions() {
+ return this.args.canWrite;
+ }
+
+ get showAssignButton() {
+ if (!this.isTopicCard) {
+ return this.canAssign;
+ }
+
+ return this.canAssign && !this.topicStatusModel?.closed;
+ }
+
+ get canAssign() {
+ return (
+ this.siteSettings.assign_enabled &&
+ this.currentUser?.can_assign &&
+ (this.isTopicCard || this.args.canWrite)
+ );
+ }
+
+ get isAssigned() {
+ return (
+ this.allAssignedUsers.length > 0 ||
+ !!this.topic?.assigned_to_group ||
+ !!this.assignedGroup
+ );
+ }
+
+ get topicAssignments() {
+ return (this.topic?.assignments || []).map((a) => ({
+ ...a,
+ unassignLabel: a.username
+ ? a.target_type === "Post"
+ ? i18n("boards.board.unassign_from_post", {
+ username: a.username,
+ post_number: a.post_number,
+ })
+ : i18n("boards.board.unassign_from_topic", {
+ username: a.username,
+ })
+ : i18n("boards.board.unassign_group_from_topic", {
+ group_name: a.group_name,
+ }),
+ }));
+ }
+
+ get floaterTagsHtml() {
+ const tags = this.args.card.tags;
+ if (this.isTopicCard || !tags?.length) {
+ return null;
+ }
+ return renderTags(null, { tags });
+ }
+
+ @action
+ openDetailModal() {
+ const board = this.args.board;
+ const boardUrl = boardsBoardUrl(board);
+ const cardUrlPath = boardsCardUrl(board, this.args.card.id);
+
+ DiscourseURL.replaceState(cardUrlPath);
+
+ this.modal
+ .show(BoardsCardDetailModal, {
+ model: {
+ card: this.args.card,
+ canWrite: this.args.canWrite,
+ onUpdateCard: this.args.onUpdateCard,
+ },
+ })
+ .finally(() => {
+ if (!this.isDestroying && !this.isDestroyed) {
+ DiscourseURL.replaceState(boardUrl);
+ }
+ });
+ }
+
+ @action
+ openTopicDetailModal() {
+ const board = this.args.board;
+ const boardUrl = boardsBoardUrl(board);
+ const cardUrlPath = boardsCardUrl(board, this.args.card.id);
+ let navigatedAway = false;
+
+ DiscourseURL.replaceState(cardUrlPath);
+
+ this.modal
+ .show(BoardsTopicCardDetailModal, {
+ model: {
+ card: this.args.card,
+ columnTitle: this.args.columnTitle,
+ columnIcon: this.args.columnIcon,
+ columnColor: this.args.columnColor,
+ onNavigateAway: (url) => {
+ navigatedAway = true;
+ DiscourseURL.routeTo(url);
+ },
+ },
+ })
+ .finally(() => {
+ if (!navigatedAway && !this.isDestroying && !this.isDestroyed) {
+ DiscourseURL.replaceState(boardUrl);
+ }
+ });
+ }
+
+ @action
+ handleAssign(event) {
+ event?.stopPropagation();
+ if (this.isTopicCard) {
+ const taskActions = getOwner(this).lookup("service:task-actions");
+ taskActions.showAssignModal(this.topic, {
+ isAssigned: this.isAssigned,
+ targetType: "Topic",
+ onSuccess: () => this.args.onRefreshBoard?.(),
+ });
+ } else {
+ this.#openFloaterAssignModal();
+ }
+ }
+
+ @action
+ editAssignments(close) {
+ close?.();
+ if (this.isTopicCard) {
+ const taskActions = getOwner(this).lookup("service:task-actions");
+ taskActions.showAssignModal(this.topic, {
+ isAssigned: this.isAssigned,
+ targetType: "Topic",
+ onSuccess: () => this.args.onRefreshBoard?.(),
+ });
+ } else {
+ this.#openFloaterAssignModal();
+ }
+ }
+
+ #openFloaterAssignModal() {
+ const assignedTo = this.args.card.assigned_to;
+ this.modal.show(BoardsFloaterAssignModal, {
+ model: {
+ currentAssignee: assignedTo?.username || assignedTo?.name || null,
+ onSave: async (name) => {
+ await this.args.onUpdateCard?.(this.args.card.id, {
+ assigned_to_name: name,
+ });
+ this.args.onRefreshBoard?.();
+ },
+ },
+ });
+ }
+
+ @action
+ async unassignFromMenu(close) {
+ close?.();
+ if (this.isTopicCard) {
+ const taskActions = getOwner(this).lookup("service:task-actions");
+ await taskActions.unassign(this.topic.id, "Topic");
+ } else {
+ await this.args.onUpdateCard?.(this.args.card.id, {
+ assigned_to_name: null,
+ });
+ }
+ this.args.onRefreshBoard?.();
+ }
+
+ @action
+ async unassignTarget(assignment, close) {
+ close?.();
+ const taskActions = getOwner(this).lookup("service:task-actions");
+ await taskActions.unassign(assignment.target_id, assignment.target_type);
+ this.args.onRefreshBoard?.();
+ }
+
+ @action
+ onCardClick(event) {
+ if (
+ event.target.closest(".discourse-boards-card__actions-trigger") ||
+ event.target.closest(".discourse-boards-card__assign-btn") ||
+ event.target.closest("[data-content]") ||
+ event.target.closest("a")
+ ) {
+ return;
+ }
+ if (this.isTopicCard) {
+ this.openTopicDetailModal();
+ } else {
+ this.openDetailModal();
+ }
+ }
+
+ @action
+ onCardKeydown(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ this.onCardClick(event);
+ }
+ }
+
+ @action
+ removeCard() {
+ this.args.onDeleteCard(this.args.card.id);
+ }
+
+ @action
+ dragStart(event) {
+ if (!this.args.canWrite) {
+ event.preventDefault();
+ return;
+ }
+
+ const cardRect = event.currentTarget.getBoundingClientRect();
+ this.#setDragImage(event, event.currentTarget, cardRect);
+
+ this.args.onDragStart({
+ cardId: this.args.card.id,
+ topicId: this.args.card.topic_id,
+ fromColumnId: this.args.card.column_id,
+ cardHeight: cardRect.height,
+ hasPlacedIndicator: false,
+ });
+ event.dataTransfer.effectAllowed = "move";
+ event.stopPropagation();
+
+ this.#scheduleDragSourceHide(event.currentTarget, cardRect.height);
+ }
+
+ @action
+ dragEnd() {
+ this.args.onDragEnd?.(this.args.card.id);
+ this.#clearDragHideTimer();
+ this.#removeDropIndicators();
+ this.dragging = false;
+ this.#cleanupDragImage();
+ }
+
+ #scheduleDragSourceHide(cardElement, cardHeight) {
+ this.#clearDragHideTimer();
+
+ this.dragHideTimer = discourseLater(this, () => {
+ this.dragHideTimer = null;
+
+ if (!this.isDestroying && !this.isDestroyed) {
+ if (shouldInsertSourceDropIndicator()) {
+ this.#insertSourceDropIndicator(cardElement, cardHeight);
+ }
+ this.dragging = true;
+ }
+ });
+ }
+
+ #clearDragHideTimer() {
+ if (this.dragHideTimer) {
+ cancel(this.dragHideTimer);
+ this.dragHideTimer = null;
+ }
+ }
+
+ #setDragImage(event, cardElement, cardRect) {
+ if (!event.dataTransfer?.setDragImage) {
+ return;
+ }
+
+ this.#cleanupDragImage();
+
+ const dragImage = cardElement.cloneNode(true);
+ dragImage.classList.remove("discourse-boards-card--dragging");
+ dragImage.classList.add("discourse-boards-card--drag-image");
+ dragImage.style.width = `${cardRect.width}px`;
+ dragImage.style.height = `${cardRect.height}px`;
+ dragImage.setAttribute("aria-hidden", "true");
+
+ document.body.append(dragImage);
+ this.dragImageElement = dragImage;
+
+ // Fallback for programmatic or test drags where the pointer coordinates are 0.
+ const offsetX =
+ event.clientX > 0 ? Math.max(event.clientX - cardRect.left, 0) : 24;
+ const offsetY =
+ event.clientY > 0 ? Math.max(event.clientY - cardRect.top, 0) : 24;
+
+ event.dataTransfer.setDragImage(dragImage, offsetX, offsetY);
+ }
+
+ #cleanupDragImage() {
+ this.dragImageElement?.remove();
+ this.dragImageElement = null;
+ }
+
+ #insertSourceDropIndicator(cardElement, cardHeight) {
+ const cardsContainer = cardElement.closest(
+ ".discourse-boards-column__cards"
+ );
+ if (!cardsContainer) {
+ return;
+ }
+
+ this.#removeDropIndicators();
+
+ const indicator = document.createElement("div");
+ indicator.className =
+ "discourse-boards-column__drop-indicator discourse-boards-column__drop-indicator--source";
+ indicator.style.height = `${cardHeight}px`;
+
+ cardsContainer.insertBefore(indicator, cardElement);
+ }
+
+ #removeDropIndicators() {
+ document
+ .querySelectorAll(".discourse-boards-column__drop-indicator")
+ .forEach((indicator) => indicator.remove());
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-nested-interactive }}
+ <div
+ class={{dConcatClass
+ "discourse-boards-card"
+ (if this.dragging "discourse-boards-card--dragging")
+ (unless this.isTopicCard "discourse-boards-card--floater")
+ (if @isDropHighlighted "discourse-boards-card--drop-highlighted")
+ (if @isLinkHighlighted "discourse-boards-card--link-highlighted")
+ }}
+ draggable={{if @canWrite "true" "false"}}
+ role="button"
+ tabindex="0"
+ data-card-id={{@card.id}}
+ data-topic-id={{@card.topic_id}}
+ {{on "dragstart" this.dragStart}}
+ {{on "dragend" this.dragEnd}}
+ {{on "click" this.onCardClick}}
+ {{on "keydown" this.onCardKeydown}}
+ >
+ <div class="discourse-boards-card__row discourse-boards-card__title-row">
+
+ {{#if this.isTopicCard}}
+ <span
+ class="discourse-boards-card__title discourse-boards-card__title--topic"
+ >
+ {{#if this.topicStatusModel}}
+ <TopicStatus @topic={{this.topicStatusModel}} />
+ {{/if}}
+ {{this.renderedTopicTitle}}
+ </span>
+ {{else}}
+ <span class="discourse-boards-card__title">
+ {{#if this.inlineOneboxData}}
+ <a
+ href={{this.inlineOneboxData.url}}
+ class={{dConcatClass
+ "inline-onebox"
+ this.inlineOneboxData.css_class
+ }}
+ target="_blank"
+ rel="noopener noreferrer"
+ >{{this.inlineOneboxData.title}}</a>
+ {{else}}
+ <AutoLinkedText @text={{this.cardTitle}} />
+ {{/if}}
+ </span>
+ {{/if}}
+ {{#if this.canShowActions}}
+ <DMenu
+ @identifier="boards-card-actions"
+ @icon="ellipsis"
+ @triggerClass="btn-flat btn-small discourse-boards-card__actions-trigger"
+ >
+ <:content>
+ <DDropdownMenu as |dropdown|>
+ {{#unless this.isTopicCard}}
+ <dropdown.item>
+ <DButton
+ @action={{this.openDetailModal}}
+ @icon="pencil"
+ @label="edit"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{@onPromoteToTopic}}
+ @icon="plus"
+ @label="boards.board.new_topic"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/unless}}
+ <dropdown.item>
+ <DButton
+ @action={{this.removeCard}}
+ @icon="trash-can"
+ @label="boards.board.remove_card"
+ class="btn-transparent btn-danger"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{/if}}
+ {{#unless this.isDetailed}}
+ {{#if this.activityDate}}
+ <span class="discourse-boards-card__date">
+ {{dFormatDate this.activityDate format="tiny" noTitle="true"}}
+ </span>
+ {{/if}}
+ {{/unless}}
+ </div>
+
+ {{#if this.tagsHtml}}
+ <div class="discourse-boards-card__row discourse-boards-card__tags">
+ {{trustHTML this.tagsHtml}}
+ </div>
+ {{/if}}
+
+ <div class="discourse-boards-card__row discourse-boards-card__meta-data">
+ {{#if this.category}}
+ <div
+ class="discourse-boards-card__category discourse-boards-card__row-item"
+ >
+ {{dCategoryBadge this.category}}
+ </div>
+ {{/if}}
+ {{#if this.isDetailed}}
+ <div class="discourse-boards-card__row-item">
+ <div class="discourse-boards-card__last-post-by">
+ {{#if this.activityDate}}
+ {{dFormatDate this.activityDate format="tiny" noTitle="true"}}
+ {{/if}}
+ {{#if this.lastPosterUsername}}
+ ({{this.lastPosterUsername}})
+ {{/if}}
+ </div>
+ {{#if this.showAssignButton}}
+ <div class="discourse-boards-card__assign">
+ {{#if this.isAssigned}}
+ <DMenu
+ @identifier="boards-card-assignment"
+ @triggerClass="discourse-boards-card__assign-trigger"
+ @class="btn-flat"
+ >
+ <:trigger>
+ {{#if this.assignedAvatarHtml}}
+ {{trustHTML this.assignedAvatarHtml}}
+ {{else if this.assignedGroup}}
+ {{dIcon "group"}}
+ {{/if}}
+ </:trigger>
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.isTopicCard}}
+ {{#each this.topicAssignments as |assignment|}}
+ <dropdown.item>
+ <DButton
+ @action={{fn
+ this.unassignTarget
+ assignment
+ args.close
+ }}
+ @translatedLabel={{assignment.unassignLabel}}
+ @icon="user-xmark"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/each}}
+ {{else}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.unassignFromMenu args.close}}
+ @icon="user-xmark"
+ @label="boards.board.unassign"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.editAssignments args.close}}
+ @icon="pencil"
+ @label="boards.board.edit_assignments"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{else}}
+ <DButton
+ @action={{this.handleAssign}}
+ @icon="user-plus"
+ @title="boards.board.assign"
+ class="btn-flat discourse-boards-card__assign-btn"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+
+ </div>
+ {{/if}}
+
+ </div>
+
+ {{#if this.showImage}}
+ <div
+ class="discourse-boards-card__row discourse-boards-card__thumbnail-row"
+ >
+ <img
+ class="discourse-boards-card__thumbnail"
+ src={{this.topic.image_url}}
+ />
+ </div>
+ {{/if}}
+
+ </div>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-column.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-column.gjs
new file mode 100644
index 00000000000..1a72094f52d
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-column.gjs
@@ -0,0 +1,625 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { autoScrollSpeedForPointer } from "../lib/boards-auto-scroll";
+import { isRecencyColumn } from "../lib/boards-card-ordering";
+import {
+ columnColorVariable,
+ hasColumnColor,
+} from "../lib/boards-column-helpers";
+import { animateCardReorder, captureCardRects } from "../lib/boards-motion";
+import BoardsCard from "./boards-card";
+import BoardsAddTopicAsCardModal from "./modal/boards-add-topic-as-card";
+import BoardsCardDetailModal from "./modal/boards-card-detail";
+
+const RECENCY_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
+
+export function recencyTimestamp(card) {
+ const value = Date.parse(card?.recency_at || "");
+ return Number.isFinite(value) ? value : 0;
+}
+
+export function recencyDropIndicatorInsertBefore(
+ cardsContainer,
+ cardElements,
+ draggedCardId
+) {
+ return (
+ cardElements.find((cardEl) => {
+ const elCardId = parseInt(cardEl.dataset.cardId, 10);
+ return elCardId !== draggedCardId;
+ }) || cardsContainer.querySelector(".discourse-boards-column__show-all")
+ );
+}
+
+export function shouldAnimateDropIndicatorPlacement({
+ hadIndicator,
+ columnId,
+ fromColumnId,
+ hasPlacedIndicator,
+}) {
+ return hadIndicator || columnId !== fromColumnId || hasPlacedIndicator;
+}
+
+export default class BoardsColumn extends Component {
+ @service modal;
+
+ @tracked showAllCards = false;
+
+ autoScrollFrame = null;
+ autoScrollSpeed = 0;
+ autoScrollContainer = null;
+ autoScrollHasDocumentListeners = false;
+ stopAutoScroll = () => this.#stopAutoScroll();
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#stopAutoScroll();
+ }
+
+ get cardCount() {
+ return this.args.column.cards?.length || 0;
+ }
+
+ get visibleCards() {
+ const cards = this.args.column.cards || [];
+ if (!this.isRecencySorted || this.showAllCards) {
+ return cards;
+ }
+
+ const cutoff = Date.now() - RECENCY_WINDOW_MS;
+ return cards.filter(
+ (card) =>
+ card.id === this.args.linkedCardId || recencyTimestamp(card) >= cutoff
+ );
+ }
+
+ get hiddenCardCount() {
+ if (!this.isRecencySorted || this.showAllCards) {
+ return 0;
+ }
+
+ return this.cardCount - this.visibleCards.length;
+ }
+
+ get isRecencySorted() {
+ return isRecencyColumn(this.args.column);
+ }
+
+ get columnTags() {
+ const allColumns = this.args.allColumns || [];
+ return allColumns.map((col) => col.tag_name).filter(Boolean);
+ }
+
+ get columnIndex() {
+ const allColumns = this.args.allColumns || [];
+ return allColumns.findIndex((col) => col.id === this.args.column.id);
+ }
+
+ get lastColumnIndex() {
+ return (this.args.allColumns?.length || 0) - 1;
+ }
+
+ @action
+ showAllOlderCards() {
+ this.showAllCards = true;
+ }
+
+ @action
+ async startAddCard(closeMenu) {
+ await closeMenu();
+ this.modal.show(BoardsCardDetailModal, {
+ model: {
+ card: {},
+ isNew: true,
+ canWrite: true,
+ onCreateCard: (data) =>
+ this.args.onAddCard({ ...data, columnId: this.args.column.id }),
+ },
+ });
+ }
+
+ @action
+ async addTopicAsCard(closeMenu) {
+ await closeMenu();
+ this.modal.show(BoardsAddTopicAsCardModal, {
+ model: {
+ onAddTopicAsCard: (data) =>
+ this.args.onAddCard({ ...data, columnId: this.args.column.id }),
+ },
+ });
+ }
+
+ @action
+ editColumn(closeMenu) {
+ closeMenu();
+ this.args.onEditColumn(this.args.column.id);
+ }
+
+ @action
+ moveLeft(closeMenu) {
+ closeMenu();
+ this.args.onMoveColumn(this.args.column.id, -1);
+ }
+
+ @action
+ moveRight(closeMenu) {
+ closeMenu();
+ this.args.onMoveColumn(this.args.column.id, 1);
+ }
+
+ @action
+ clearColumn(closeMenu) {
+ closeMenu();
+ this.args.onClearColumn(this.args.column.id);
+ }
+
+ @action
+ deleteColumn(closeMenu) {
+ closeMenu();
+ this.args.onDeleteColumn(this.args.column);
+ }
+
+ @action
+ dragOver(event) {
+ event.preventDefault();
+ const dragData = this.args.dragData;
+ if (!dragData) {
+ this.#stopAutoScroll();
+ return;
+ }
+
+ event.currentTarget.classList.add("discourse-boards-column--drag-target");
+
+ const cardsContainer = event.currentTarget.querySelector(
+ ".discourse-boards-column__cards"
+ );
+ if (!cardsContainer) {
+ this.#stopAutoScroll();
+ return;
+ }
+
+ this.#updateAutoScroll(cardsContainer, event.clientY);
+
+ if (this.isRecencySorted && dragData.fromColumnId === this.args.column.id) {
+ this.removeDropIndicator(event.currentTarget, { animate: true });
+ return;
+ }
+
+ let indicator = cardsContainer.querySelector(
+ ".discourse-boards-column__drop-indicator"
+ );
+ const hadIndicator = !!indicator;
+ if (!indicator) {
+ indicator = document.createElement("div");
+ indicator.className = "discourse-boards-column__drop-indicator";
+ }
+ indicator.style.height = `${dragData.cardHeight}px`;
+
+ const cardElements = [
+ ...cardsContainer.querySelectorAll(".discourse-boards-card"),
+ ];
+ let insertBefore = null;
+
+ if (this.isRecencySorted) {
+ insertBefore = recencyDropIndicatorInsertBefore(
+ cardsContainer,
+ cardElements,
+ dragData.cardId
+ );
+ } else {
+ for (const cardEl of cardElements) {
+ const elCardId = parseInt(cardEl.dataset.cardId, 10);
+ if (elCardId === dragData.cardId) {
+ continue;
+ }
+ const rect = cardEl.getBoundingClientRect();
+ if (event.clientY <= rect.top + rect.height / 2) {
+ insertBefore = cardEl;
+ break;
+ }
+ }
+ }
+
+ const emptyMsg = cardsContainer.querySelector(
+ ".discourse-boards-column__empty"
+ );
+ if (emptyMsg) {
+ emptyMsg.hidden = true;
+ }
+
+ if (
+ this.#indicatorMatchesPosition(cardsContainer, indicator, insertBefore)
+ ) {
+ return;
+ }
+
+ const shouldAnimate = shouldAnimateDropIndicatorPlacement({
+ hadIndicator,
+ columnId: this.args.column.id,
+ fromColumnId: dragData.fromColumnId,
+ hasPlacedIndicator: dragData.hasPlacedIndicator,
+ });
+
+ const previousRects = shouldAnimate
+ ? captureCardRects(cardsContainer, {
+ skipCardIds: [dragData.cardId],
+ })
+ : null;
+
+ indicator.classList.remove(
+ "discourse-boards-column__drop-indicator--source"
+ );
+
+ if (insertBefore) {
+ cardsContainer.insertBefore(indicator, insertBefore);
+ } else {
+ cardsContainer.appendChild(indicator);
+ }
+
+ if (shouldAnimate) {
+ animateCardReorder(cardsContainer, previousRects, {
+ skipCardIds: [dragData.cardId],
+ });
+ }
+
+ dragData.hasPlacedIndicator = true;
+ }
+
+ @action
+ dragLeave(event) {
+ event.preventDefault();
+ if (!event.currentTarget.contains(event.relatedTarget)) {
+ event.currentTarget.classList.remove(
+ "discourse-boards-column--drag-target"
+ );
+ this.removeDropIndicator(event.currentTarget, { animate: true });
+ this.#stopAutoScroll();
+ }
+ }
+
+ @action
+ drop(event) {
+ event.preventDefault();
+ event.currentTarget.classList.remove(
+ "discourse-boards-column--drag-target"
+ );
+ this.#stopAutoScroll();
+
+ const dragData = this.args.dragData;
+ if (!dragData) {
+ this.removeDropIndicator(event.currentTarget, { animate: false });
+ return;
+ }
+
+ if (this.isRecencySorted && dragData.fromColumnId === this.args.column.id) {
+ this.removeDropIndicator(event.currentTarget, { animate: false });
+ return;
+ }
+
+ const cardsContainer = event.currentTarget.querySelector(
+ ".discourse-boards-column__cards"
+ );
+ let afterCardId = null;
+
+ if (cardsContainer && !this.isRecencySorted) {
+ const cardElements = [
+ ...cardsContainer.querySelectorAll(".discourse-boards-card"),
+ ];
+ for (const cardEl of cardElements) {
+ const elCardId = parseInt(cardEl.dataset.cardId, 10);
+ if (elCardId === dragData.cardId) {
+ continue;
+ }
+ const rect = cardEl.getBoundingClientRect();
+ if (event.clientY > rect.top + rect.height / 2) {
+ afterCardId = elCardId;
+ }
+ }
+ }
+
+ this.removeDropIndicator(event.currentTarget, { animate: false });
+
+ this.args.onDrop(
+ dragData.cardId,
+ this.args.column.id,
+ afterCardId,
+ dragData.fromColumnId
+ );
+ }
+
+ removeDropIndicator(columnEl, { animate = false } = {}) {
+ const cardsContainer = columnEl.querySelector(
+ ".discourse-boards-column__cards"
+ );
+ const indicator = columnEl.querySelector(
+ ".discourse-boards-column__drop-indicator"
+ );
+ const dragData = this.args.dragData;
+
+ if (!indicator) {
+ columnEl
+ .querySelector(".discourse-boards-column__empty")
+ ?.removeAttribute("hidden");
+ return;
+ }
+
+ const previousRects =
+ animate && cardsContainer
+ ? captureCardRects(cardsContainer, {
+ skipCardIds: dragData ? [dragData.cardId] : [],
+ })
+ : null;
+
+ indicator.remove();
+
+ const emptyMsg = columnEl.querySelector(".discourse-boards-column__empty");
+ if (emptyMsg) {
+ emptyMsg.hidden = false;
+ }
+
+ if (cardsContainer && previousRects) {
+ animateCardReorder(cardsContainer, previousRects, {
+ skipCardIds: dragData ? [dragData.cardId] : [],
+ });
+ }
+ }
+
+ #updateAutoScroll(cardsContainer, clientY) {
+ const speed = autoScrollSpeedForPointer(
+ clientY,
+ cardsContainer.getBoundingClientRect()
+ );
+
+ if (
+ (speed < 0 && cardsContainer.scrollTop <= 0) ||
+ (speed > 0 &&
+ cardsContainer.scrollTop + cardsContainer.clientHeight >=
+ cardsContainer.scrollHeight)
+ ) {
+ this.#stopAutoScroll();
+ return;
+ }
+
+ this.autoScrollSpeed = speed;
+ this.autoScrollContainer = cardsContainer;
+ this.#ensureAutoScrollDocumentListeners();
+
+ if (speed === 0) {
+ this.#stopAutoScroll();
+ return;
+ }
+
+ if (!this.autoScrollFrame) {
+ this.#autoScroll();
+ }
+ }
+
+ #autoScroll() {
+ this.autoScrollFrame = requestAnimationFrame(() => {
+ this.autoScrollFrame = null;
+
+ const container = this.autoScrollContainer;
+ if (!container || this.autoScrollSpeed === 0) {
+ return;
+ }
+
+ const previousScrollTop = container.scrollTop;
+ container.scrollTop += this.autoScrollSpeed;
+
+ if (container.scrollTop === previousScrollTop) {
+ this.#stopAutoScroll();
+ return;
+ }
+
+ this.#autoScroll();
+ });
+ }
+
+ #ensureAutoScrollDocumentListeners() {
+ if (this.autoScrollHasDocumentListeners) {
+ return;
+ }
+
+ document.addEventListener("dragend", this.stopAutoScroll, true);
+ document.addEventListener("drop", this.stopAutoScroll, true);
+ this.autoScrollHasDocumentListeners = true;
+ }
+
+ #removeAutoScrollDocumentListeners() {
+ if (!this.autoScrollHasDocumentListeners) {
+ return;
+ }
+
+ document.removeEventListener("dragend", this.stopAutoScroll, true);
+ document.removeEventListener("drop", this.stopAutoScroll, true);
+ this.autoScrollHasDocumentListeners = false;
+ }
+
+ #stopAutoScroll() {
+ if (this.autoScrollFrame) {
+ cancelAnimationFrame(this.autoScrollFrame);
+ this.autoScrollFrame = null;
+ }
+
+ this.autoScrollSpeed = 0;
+ this.autoScrollContainer = null;
+ this.#removeAutoScrollDocumentListeners();
+ }
+
+ #indicatorMatchesPosition(cardsContainer, indicator, insertBefore) {
+ if (indicator.parentElement !== cardsContainer) {
+ return false;
+ }
+
+ if (insertBefore) {
+ return indicator.nextElementSibling === insertBefore;
+ }
+
+ return indicator === cardsContainer.lastElementChild;
+ }
+
+ <template>
+ <div
+ class="discourse-boards-column
+ {{if
+ (hasColumnColor @column.color)
+ 'discourse-boards-column--has-color'
+ }}"
+ data-column-id={{@column.id}}
+ data-default-sort={{@column.default_sort}}
+ style={{columnColorVariable @column.color}}
+ {{on "dragover" this.dragOver}}
+ {{on "dragleave" this.dragLeave}}
+ {{on "drop" this.drop}}
+ >
+ <div class="discourse-boards-column__header">
+ <span class="discourse-boards-column__header-content">
+ <span class="discourse-boards-column__title">
+ {{#if @column.icon}}{{dIcon @column.icon}}{{/if}}
+ {{@column.fancyTitle}}
+ </span>
+ <span class="discourse-boards-column__count">
+ {{this.cardCount}}
+ </span>
+ </span>
+ {{#if @canManage}}
+ <DMenu
+ @identifier="boards-column-controls"
+ @icon="ellipsis"
+ @title="boards.board.column_controls"
+ @triggerClass="btn-flat btn-small discourse-boards-column__menu-trigger"
+ >
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.editColumn args.close}}
+ @icon="pencil"
+ @label="boards.board.edit_column"
+ class="btn-transparent discourse-boards-column__menu-edit"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.moveLeft args.close}}
+ @icon="arrow-left"
+ @label="boards.board.move_left"
+ @disabled={{eq this.columnIndex 0}}
+ class="btn-transparent discourse-boards-column__menu-move-left"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.moveRight args.close}}
+ @icon="arrow-right"
+ @label="boards.board.move_right"
+ @disabled={{eq this.columnIndex this.lastColumnIndex}}
+ class="btn-transparent discourse-boards-column__menu-move-right"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.clearColumn args.close}}
+ @icon="xmark"
+ @label="boards.board.clear_column"
+ @disabled={{eq this.cardCount 0}}
+ class="btn-transparent discourse-boards-column__menu-clear"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.deleteColumn args.close}}
+ @icon="trash-can"
+ @label="boards.board.delete_column"
+ class="btn-transparent btn-danger discourse-boards-column__menu-delete"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{/if}}
+ </div>
+
+ <div class="discourse-boards-column__cards">
+ {{#if this.visibleCards.length}}
+ {{#each this.visibleCards key="id" as |card|}}
+ <BoardsCard
+ @card={{card}}
+ @board={{@board}}
+ @columnTitle={{@column.fancyTitle}}
+ @columnIcon={{@column.icon}}
+ @columnColor={{@column.color}}
+ @canWrite={{@canWrite}}
+ @allSameCategory={{@allSameCategory}}
+ @isDropHighlighted={{eq @dropHighlightCardId card.id}}
+ @isLinkHighlighted={{eq @linkHighlightCardId card.id}}
+ @onDragStart={{@onDragStart}}
+ @onDragEnd={{@onDragEnd}}
+ @onUpdateCard={{@onUpdateCard}}
+ @onDeleteCard={{@onDeleteCard}}
+ @onPromoteToTopic={{fn @onPromoteToTopic card.id}}
+ @onRefreshBoard={{@onRefreshBoard}}
+ @columnTags={{this.columnTags}}
+ />
+ {{/each}}
+ {{else if (eq this.cardCount 0)}}
+ <div class="discourse-boards-column__empty">
+ {{i18n "boards.board.no_cards"}}
+ </div>
+ {{/if}}
+
+ {{#if this.hiddenCardCount}}
+ <button
+ type="button"
+ class="discourse-boards-column__show-all"
+ {{on "click" this.showAllOlderCards}}
+ >
+ {{i18n "boards.board.show_older_cards" count=this.hiddenCardCount}}
+ </button>
+ {{/if}}
+ </div>
+
+ {{#if @canWrite}}
+ <div class="discourse-boards-column__footer">
+ <DMenu
+ @identifier="boards-column-add"
+ @icon="plus"
+ @label={{i18n "boards.board.add_card"}}
+ @triggerClass="discourse-boards-column__add-btn"
+ >
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.startAddCard args.close}}
+ @icon="plus"
+ @label="boards.board.add_card"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.addTopicAsCard args.close}}
+ @icon="link"
+ @label="boards.board.add_topic_as_card"
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-editable-title.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-editable-title.gjs
new file mode 100644
index 00000000000..e5942d650b8
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-editable-title.gjs
@@ -0,0 +1,130 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { trustHTML } from "@ember/template";
+import { isEmpty } from "@ember/utils";
+import { emojiUnescape } from "discourse/lib/text";
+import { escapeExpression } from "discourse/lib/utilities";
+import DButton from "discourse/ui-kit/d-button";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
+
+class BoardsEditableTitleUi extends Component {
+ @tracked isEditing = isEmpty(this.args.field.value);
+
+ get hasValue() {
+ return !isEmpty(this.args.field.value);
+ }
+
+ get displayText() {
+ return trustHTML(
+ emojiUnescape(
+ escapeExpression(this.args.field.value || this.args.placeholder)
+ )
+ );
+ }
+
+ @action
+ startEditing() {
+ if (this.args.field.disabled) {
+ return;
+ }
+ this.isEditing = true;
+ }
+
+ @action
+ onInput(event) {
+ this.args.field.set(event.target.value);
+ }
+
+ @action
+ finishEditing() {
+ const value = this.args.field.value?.trim() ?? "";
+ this.args.field.set(value);
+ this.isEditing = false;
+ }
+
+ @action
+ handleKeydown(event) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.target.blur();
+ } else if (event.key === "Escape") {
+ this.isEditing = false;
+ }
+ }
+
+ <template>
+ {{#if this.isEditing}}
+ <input
+ type="text"
+ value={{@field.value}}
+ placeholder={{@placeholder}}
+ class="discourse-boards-editable-title__input"
+ id={{@field.id}}
+ name={{@field.name}}
+ disabled={{@field.disabled}}
+ aria-invalid={{if @field.error "true"}}
+ aria-describedby={{if @field.error @field.errorId}}
+ {{dAutoFocus selectText=true}}
+ {{on "input" this.onInput}}
+ {{on "blur" this.finishEditing}}
+ {{on "keydown" this.handleKeydown}}
+ />
+ {{else}}
+ {{! eslint-disable ember/template-no-invalid-interactive }}
+ <div
+ class={{dConcatClass
+ "discourse-boards-editable-title__text"
+ (unless this.hasValue "--empty")
+ }}
+ {{on "click" this.startEditing}}
+ >{{this.displayText}}</div>
+ {{/if}}
+ {{#if @showClose}}
+ <DButton
+ @action={{@onClose}}
+ @icon="xmark"
+ @ariaLabel="modal.close"
+ @title="modal.close"
+ class="btn-flat discourse-boards-editable-title__close"
+ />
+ {{/if}}
+ </template>
+}
+
+export default class BoardsEditableTitle extends Component {
+ get validation() {
+ if (this.args.validate) {
+ return null;
+ }
+
+ return this.args.validation || "required:trim";
+ }
+
+ <template>
+ <div class="discourse-boards-editable-title">
+ <@form.Field
+ @name={{@name}}
+ @title={{@title}}
+ @type="custom"
+ @validation={{this.validation}}
+ @showTitle={{false}}
+ @disabled={{@disabled}}
+ @validate={{@validate}}
+ @format="full"
+ as |field|
+ >
+ <field.Control>
+ <BoardsEditableTitleUi
+ @field={{field}}
+ @placeholder={{@placeholder}}
+ @showClose={{@showClose}}
+ @onClose={{@onClose}}
+ />
+ </field.Control>
+ </@form.Field>
+ </div>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-menu.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-menu.gjs
new file mode 100644
index 00000000000..40224257fb4
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-menu.gjs
@@ -0,0 +1,58 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DiscourseURL from "discourse/lib/url";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { columnColorVariable } from "../lib/boards-column-helpers";
+import { membershipCardUrl } from "../lib/boards-topic-pill";
+
+export default class BoardsMenu extends Component {
+ get memberships() {
+ return this.args.data.memberships.map((membership) => ({
+ ...membership,
+ fancyTitle: membership.unicode_board_name || membership.board_name,
+ cards: membership.cards.map((card) => ({
+ ...card,
+ fancyTitle: card.unicode_column_title || card.column_title,
+ })),
+ }));
+ }
+
+ @action
+ goToBoard(membership) {
+ this.args.close();
+ DiscourseURL.routeTo(membershipCardUrl(membership));
+ }
+
+ <template>
+ <DDropdownMenu as |dropdown|>
+ {{#each this.memberships as |membership|}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.goToBoard membership}}
+ class="btn-transparent discourse-boards-boards-menu__item --with-description"
+ >
+ <div class="discourse-boards-boards-menu__item-texts">
+ <span
+ class="discourse-boards-boards-menu__item-label"
+ >{{membership.fancyTitle}}</span>
+ {{#each membership.cards as |card|}}
+ <span
+ class="discourse-boards-boards-menu__column"
+ style={{columnColorVariable card.column_color}}
+ >
+ {{#if card.column_icon}}
+ {{dIcon card.column_icon}}
+ {{/if}}
+ {{card.fancyTitle}}
+ </span>
+ {{/each}}
+ </div>
+ </DButton>
+ </dropdown.item>
+ {{/each}}
+ </DDropdownMenu>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs
new file mode 100644
index 00000000000..5aabcb21d1e
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/boards-page.gjs
@@ -0,0 +1,190 @@
+import Component from "@glimmer/component";
+import { array } from "@ember/helper";
+import { action } from "@ember/object";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import Category from "discourse/models/category";
+import { eq, or } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DFilterControls from "discourse/ui-kit/d-filter-controls";
+import DPageHeader from "discourse/ui-kit/d-page-header";
+import DUserLink from "discourse/ui-kit/d-user-link";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dBoundCategoryLink from "discourse/ui-kit/helpers/d-bound-category-link";
+import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import BoardsBoardSettings from "./modal/boards-board-settings";
+
+function boardCategories(board) {
+ return (board.category_ids || [])
+ .map((id) => Category.findById(id))
+ .filter(Boolean);
+}
+
+export default class BoardsPage extends Component {
+ @service modal;
+ @service router;
+ @service toasts;
+
+ @action
+ openNewBoardModal() {
+ this.modal.show(BoardsBoardSettings, {
+ model: {
+ board: null,
+ isNew: true,
+ onSave: (boardData) => this.createBoard(boardData),
+ onDelete: () => {},
+ },
+ });
+ }
+
+ @action
+ async createBoard(boardData) {
+ const payload = {
+ board: {
+ ...boardData,
+ columns: [],
+ },
+ };
+
+ const result = await ajax("/boards/api/boards", {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify(payload),
+ });
+
+ this.toasts.success({
+ data: { message: i18n("saved") },
+ duration: "short",
+ });
+
+ const savedBoard = result.board;
+ this.router.transitionTo("boardsBoard", savedBoard.slug, savedBoard.id);
+ }
+
+ <template>
+ <div class="discourse-boards-manage">
+ <DPageHeader
+ @titleLabel={{i18n "boards.manage.title"}}
+ @descriptionLabel={{i18n "boards.manage.description"}}
+ @hideTabs={{true}}
+ >
+ <:actions as |actions|>
+ {{#if @canManageBoards}}
+ <actions.Primary
+ @action={{this.openNewBoardModal}}
+ @icon="plus"
+ @label="boards.manage.new"
+ class="btn-primary discourse-boards-manage__new-board"
+ />
+ {{/if}}
+ </:actions>
+ </DPageHeader>
+
+ <DFilterControls
+ @array={{@boards}}
+ @searchableProps={{array "name"}}
+ @textFilterQueryParam="filter"
+ @inputPlaceholder={{i18n "boards.filter_boards"}}
+ @noResultsMessage={{i18n "boards.filter_boards_no_results"}}
+ @showCustomEmptyState={{true}}
+ @minItemsForFilter={{1}}
+ >
+ <:content as |filteredBoards|>
+ <div class="discourse-boards-boards-grid">
+ {{#each filteredBoards as |board|}}
+ <div class="discourse-boards-board-card">
+ <div class="discourse-boards-board-card__header">
+ <LinkTo
+ @route="boardsBoard"
+ @models={{array board.slug board.id}}
+ class="discourse-boards-board-card__name"
+ >
+ {{board.fancyTitle}}
+ </LinkTo>
+ </div>
+
+ {{#if (or board.category_ids.length board.tag_names.length)}}
+ <div class="discourse-boards-board-card__constraints">
+ {{#each (boardCategories board) as |category|}}
+ {{dBoundCategoryLink category link=false}}
+ {{/each}}
+ {{#if board.tag_names.length}}
+ <div class="list-tags">
+ {{dDiscourseTags null tags=board.tag_names}}
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+
+ <div class="discourse-boards-board-card__columns">
+ {{#if board.columns.length}}
+ {{#each board.columns as |column|}}
+ <span class="discourse-boards-column-pill">
+ {{#if column.icon}}
+ {{dIcon column.icon}}
+ {{/if}}
+ {{column.fancyTitle}}
+ </span>
+ {{/each}}
+ {{else}}
+ <span class="discourse-boards-board-card__no-columns">
+ {{i18n "boards.manage.no_columns"}}
+ </span>
+ {{/if}}
+ </div>
+
+ <div class="discourse-boards-board-card__footer">
+ <DUserLink
+ class="discourse-boards-board-card__creator discourse-boards-badge"
+ @user={{board.created_by}}
+ >
+ {{i18n "boards.board.created_by"}}
+ {{dAvatar board.created_by imageSize="micro"}}
+ </DUserLink>
+
+ <span class="discourse-boards-badge">
+ {{i18n
+ "boards.manage.column_count"
+ count=board.columns.length
+ }}
+ </span>
+ {{#if (eq board.card_style "simple")}}
+ <span class="discourse-boards-badge">
+ {{i18n "boards.manage.card_style_simple"}}
+ </span>
+ {{/if}}
+ {{#unless board.anonymous_can_read}}
+ <span
+ class="discourse-boards-badge discourse-boards-badge--restricted"
+ title={{i18n "boards.manage.restricted_access"}}
+ >
+ {{dIcon "lock"}}
+ </span>
+ {{/unless}}
+ </div>
+ </div>
+ {{/each}}
+ </div>
+ </:content>
+ <:customEmptyState>
+ <div class="discourse-boards-boards-empty">
+ {{dIcon "table-columns"}}
+ <h3>{{i18n "boards.manage.empty_title"}}</h3>
+ {{#if @canManageBoards}}
+ <p>{{i18n "boards.manage.get_started"}}</p>
+ <DButton
+ @action={{this.openNewBoardModal}}
+ @icon="plus"
+ @label="boards.manage.new"
+ class="btn-primary"
+ />
+ {{/if}}
+ </div>
+ </:customEmptyState>
+ </DFilterControls>
+ </div>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-add-topic-as-card.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-add-topic-as-card.gjs
new file mode 100644
index 00000000000..ca0b53b2ef5
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-add-topic-as-card.gjs
@@ -0,0 +1,263 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { cancel } from "@ember/runloop";
+import { isEmpty } from "@ember/utils";
+import Form from "discourse/components/form";
+import TopicStatus from "discourse/components/topic-status";
+import discourseDebounce from "discourse/lib/debounce";
+import { withoutPrefix } from "discourse/lib/get-url";
+import { searchForTerm } from "discourse/lib/search";
+import DiscourseURL, { TOPIC_URL_REGEXP } from "discourse/lib/url";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import dCategoryLink from "discourse/ui-kit/helpers/d-category-link";
+import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";
+import dLoadingSpinner from "discourse/ui-kit/helpers/d-loading-spinner";
+import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";
+import { i18n } from "discourse-i18n";
+
+export default class BoardsAddTopicAsCard extends Component {
+ @tracked selectedRow = -1;
+ @tracked searchResults = [];
+ @tracked searchLoading = false;
+ data = { topicSearch: "" };
+ #debounced;
+ #activeSearch;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ cancel(this.#debounced);
+ }
+
+ highlightRow(e, direction) {
+ const index =
+ direction === "down" ? this.selectedRow + 1 : this.selectedRow - 1;
+
+ if (index > -1 && index < this.searchResults.length) {
+ document
+ .querySelectorAll(".internal-link-results .search-link")
+ [index]?.focus();
+ this.selectedRow = index;
+ } else {
+ this.selectedRow = -1;
+ document.querySelector("input.topic-search-input")?.focus();
+ }
+
+ e.preventDefault();
+ }
+
+ selectTopic(el) {
+ const topicId = parseInt(el.dataset.topicId, 10);
+ const title = el.dataset.title;
+ if (topicId) {
+ this.searchResults = [];
+ this.args.model.onAddTopicAsCard({ topicId, title });
+ this.args.closeModal();
+ }
+ }
+
+ #topicIdFromInput(value) {
+ const input = (value ?? "").trim();
+ if (!input || !DiscourseURL.isInternal(input)) {
+ return null;
+ }
+
+ let pathname;
+ try {
+ pathname = new URL(input, DiscourseURL.origin).pathname;
+ } catch {
+ return null;
+ }
+
+ const stripped = withoutPrefix(pathname);
+ const match = TOPIC_URL_REGEXP.exec(stripped);
+ if (!match || match.index !== 0 || match[0].length !== stripped.length) {
+ return null;
+ }
+ return parseInt(match[2], 10);
+ }
+
+ async triggerSearch(value) {
+ const looksLikeUrl = /^(?:https?:)?\/\//i.test(value ?? "");
+ if (!value || value.length < 4 || looksLikeUrl) {
+ this.abortSearch();
+ return;
+ }
+
+ this.searchLoading = true;
+ this.#activeSearch = searchForTerm(value, { typeFilter: "topic" });
+
+ try {
+ const results = await this.#activeSearch;
+ this.searchResults = results?.topics || [];
+ } finally {
+ this.searchLoading = false;
+ this.#activeSearch = null;
+ }
+ }
+
+ abortSearch() {
+ this.#activeSearch?.abort();
+ this.searchResults = [];
+ this.searchLoading = false;
+ }
+
+ @action
+ keyDown(event) {
+ switch (event.key) {
+ case "ArrowDown":
+ this.highlightRow(event, "down");
+ break;
+ case "ArrowUp":
+ this.highlightRow(event, "up");
+ break;
+ case "Enter":
+ if (this.selectedRow > -1) {
+ const selected = document.querySelectorAll(
+ ".internal-link-results .search-link"
+ )[this.selectedRow];
+ if (selected) {
+ this.selectTopic(selected);
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ } else if (event.target.tagName === "INPUT") {
+ this.formApi?.submit();
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ break;
+ case "Escape":
+ if (this.searchResults.length) {
+ this.searchResults = [];
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ break;
+ }
+ }
+
+ @action
+ mouseDown(event) {
+ if (!event.target.closest(".inputs")) {
+ this.searchResults = [];
+ }
+ }
+
+ @action
+ topicClick(event) {
+ if (!event.metaKey && !event.ctrlKey) {
+ event.preventDefault();
+ event.stopPropagation();
+ this.selectTopic(event.target.closest(".search-link"));
+ }
+ }
+
+ @action
+ registerApi(api) {
+ this.formApi = api;
+ }
+
+ @action
+ search(value) {
+ this.formApi.set("topicSearch", value);
+ this.#debounced = discourseDebounce(this, this.triggerSearch, value, 400);
+ }
+
+ @action
+ onFormSubmit(data) {
+ const value = data.topicSearch?.trim();
+ if (isEmpty(value)) {
+ return;
+ }
+
+ const topicId = this.#topicIdFromInput(value);
+ if (topicId) {
+ this.searchResults = [];
+ this.args.model.onAddTopicAsCard({ topicId, title: value });
+ this.args.closeModal();
+ }
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}
+ <DModal
+ {{on "keydown" this.keyDown}}
+ {{on "mousedown" this.mouseDown}}
+ @closeModal={{@closeModal}}
+ @title={{i18n "boards.board.add_topic_as_card"}}
+ @bodyClass="insert-link"
+ class="discourse-boards-add-topic-as-card-modal"
+ >
+ <:body>
+ <div class="inputs">
+ <Form
+ @data={{this.data}}
+ @onSubmit={{this.onFormSubmit}}
+ @onRegisterApi={{this.registerApi}}
+ as |form|
+ >
+ <form.Field
+ @name="topicSearch"
+ @type="input"
+ @title={{i18n "boards.board.topic_search_placeholder"}}
+ @format="full"
+ @onSet={{this.search}}
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n "boards.board.topic_search_placeholder"}}
+ class="topic-search-input"
+ autofocus="autofocus"
+ />
+ </form.Field>
+
+ {{#if this.searchLoading}}
+ {{dLoadingSpinner}}
+ {{/if}}
+
+ {{#if this.searchResults}}
+ <div class="internal-link-results">
+ {{#each this.searchResults as |result|}}
+ <a
+ {{on "click" this.topicClick}}
+ href={{result.url}}
+ data-topic-id={{result.id}}
+ data-title={{result.fancy_title}}
+ class="search-link"
+ >
+ <TopicStatus @topic={{result}} @disableActions={{true}} />
+ {{dReplaceEmoji result.title}}
+ <div class="search-category">
+ {{#if result.category.parentCategory}}
+ {{dCategoryLink result.category.parentCategory}}
+ {{/if}}
+ {{dCategoryLink result.category hideParent=true}}
+ {{dDiscourseTags result}}
+ </div>
+ </a>
+ {{/each}}
+ </div>
+ {{/if}}
+ </Form>
+ </div>
+ </:body>
+
+ <:footer>
+ <DButton
+ @action={{this.formApi.submit}}
+ @label="boards.board.add_topic_as_card"
+ type="submit"
+ class="btn-primary"
+ />
+ <DButton
+ @action={{@closeModal}}
+ @label="cancel"
+ class="btn-transparent"
+ />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs
new file mode 100644
index 00000000000..a1f90a43ca0
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-board-settings.gjs
@@ -0,0 +1,520 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { array, fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { cancel } from "@ember/runloop";
+import { service } from "@ember/service";
+import { isEmpty } from "@ember/utils";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { AUTO_GROUPS } from "discourse/lib/constants";
+import discourseDebounce from "discourse/lib/debounce";
+import { slugify } from "discourse/lib/utilities";
+import CategorySelector from "discourse/select-kit/components/category-selector";
+import { eq, or } from "discourse/truth-helpers";
+import DAccessControlField from "discourse/ui-kit/d-access-control-field";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+import BoardsEditableTitle from "../boards-editable-title";
+
+const CONSTRAINT_TYPE_OPTIONS = [
+ {
+ id: "categories",
+ name: i18n("boards.manage.constraint_categories"),
+ },
+ { id: "tags", name: i18n("boards.manage.constraint_tags") },
+ {
+ id: "categories_and_tags",
+ name: i18n("boards.manage.constraint_categories_and_tags"),
+ },
+];
+
+function inferConstraintType(categoryIds, tagNames) {
+ const hasCats = categoryIds?.length > 0;
+ const hasTags = tagNames?.length > 0;
+ if (hasCats && hasTags) {
+ return "categories_and_tags";
+ } else if (hasCats) {
+ return "categories";
+ } else if (hasTags) {
+ return "tags";
+ }
+ return null;
+}
+
+const CARD_STYLE_OPTIONS = [
+ {
+ id: "detailed",
+ name: i18n("boards.manage.card_style_detailed"),
+ },
+ { id: "simple", name: i18n("boards.manage.card_style_simple") },
+];
+
+export default class BoardsBoardSettings extends Component {
+ @service dialog;
+ @service site;
+ @service siteSettings;
+
+ @tracked showAdvanced = false;
+
+ constraintWarning = null;
+ reloadAfterSave = false;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ cancel(this._constraintCheckTimer);
+ }
+
+ @cached
+ get formData() {
+ const board = this.args.model.board;
+
+ // Existing board
+ if (board) {
+ return {
+ name: board.name || "",
+ slug: board.slug || "",
+ constraint_type: inferConstraintType(
+ board.category_ids,
+ board.tag_names
+ ),
+ category_ids: board.category_ids || [],
+ tag_names: board.tag_names || [],
+ card_style: board.card_style || "detailed",
+ show_tags: board.show_tags ?? false,
+ show_topic_thumbnail: board.show_topic_thumbnail ?? false,
+ require_confirmation: board.require_confirmation ?? false,
+ acl: board.acl,
+ };
+ }
+
+ // New board
+ return {
+ name: "",
+ slug: "",
+ constraint_type: null,
+ category_ids: [],
+ tag_names: [],
+ card_style: "detailed",
+ show_tags: true,
+ show_topic_thumbnail: false,
+ require_confirmation: false,
+ acl: this.#buildDefaultAcl(),
+ };
+ }
+
+ get isNew() {
+ return this.args.model.isNew;
+ }
+
+ get boardsManageBoardAllowedGroupIds() {
+ return this.siteSettings.groupSettingArray(
+ "boards_manage_board_allowed_groups"
+ );
+ }
+
+ get aclTarget() {
+ return {
+ type: "Boards::Board",
+ id: this.args.model.board?.id,
+ name: i18n("boards.manage.board"),
+ };
+ }
+
+ get slugPlaceholder() {
+ const boardName = this.formApi.get("name");
+
+ if (isEmpty(boardName)) {
+ return "";
+ }
+
+ return slugify(boardName);
+ }
+
+ @action
+ toggleAdvanced() {
+ this.showAdvanced = !this.showAdvanced;
+ }
+
+ @action
+ selectedCategories(categoryIds) {
+ return (categoryIds || [])
+ .map((id) => this.site.categories?.find((c) => c.id === id))
+ .filter(Boolean);
+ }
+
+ @action
+ onConstraintTypeChange(type, { set }) {
+ set("constraint_type", type);
+ if (!type) {
+ set("category_ids", []);
+ set("tag_names", []);
+ } else if (type === "categories") {
+ set("tag_names", []);
+ } else if (type === "tags") {
+ set("category_ids", []);
+ }
+ this._checkConstraints(
+ type === "tags" || !type ? [] : null,
+ type === "categories" || !type ? [] : null
+ );
+ }
+
+ @action
+ onCategoriesChange(field, categories) {
+ const ids = categories?.map((c) => c.id) || [];
+ field.set(ids);
+ this._checkConstraints(ids, null);
+ }
+
+ @action
+ onTagsChange(tags, { set }) {
+ const names = tags.map((t) => (typeof t === "string" ? t : t.name));
+ set("tag_names", names);
+ this._checkConstraints(null, names);
+ }
+
+ _checkConstraints(categoryIds, tagNames) {
+ if (this.isNew) {
+ return;
+ }
+ cancel(this._constraintCheckTimer);
+ this._constraintCheckTimer = discourseDebounce(
+ this,
+ this._fetchConstraintPreview,
+ categoryIds,
+ tagNames,
+ 500
+ );
+ }
+
+ async _fetchConstraintPreview(categoryIds, tagNames) {
+ const boardId = this.args.model.board?.id;
+ if (!boardId) {
+ return;
+ }
+
+ try {
+ const result = await ajax(
+ `/boards/api/boards/${boardId}/constraint-preview`,
+ {
+ type: "POST",
+ data: {
+ category_ids: categoryIds ?? this.formApi?.get("category_ids"),
+ tag_names: tagNames ?? this.formApi?.get("tag_names"),
+ },
+ }
+ );
+ this.constraintWarning =
+ result.cards_to_remove > 0
+ ? i18n("boards.manage.constraint_warning", {
+ count: result.cards_to_remove,
+ })
+ : null;
+ } catch {
+ this.constraintWarning = null;
+ }
+ }
+
+ @action
+ onRegisterApi(api) {
+ this.formApi = api;
+ }
+
+ @action
+ async save(data) {
+ if (this.constraintWarning) {
+ this.dialog.confirm({
+ message: this.constraintWarning,
+ didConfirm: () => this._performSave(data),
+ });
+ return;
+ }
+
+ await this._performSave(data);
+ }
+
+ async _performSave(data) {
+ try {
+ await this.args.model.onSave(data);
+ this.args.closeModal({ reloadAfterSave: this.reloadAfterSave });
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ onDelete() {
+ this.args.model.onDelete();
+ this.args.closeModal();
+ }
+
+ @action
+ transformPermissionOptions(options) {
+ const viewOption = options.find((option) => option.id === "view");
+ viewOption.description = i18n(
+ "boards.manage.board_access_permission_viewer_description"
+ );
+
+ const editOption = options.find((option) => option.id === "edit");
+ editOption.description = i18n(
+ "boards.manage.board_access_permission_editor_description"
+ );
+
+ options.push({
+ id: "manage",
+ level: 3,
+ name: i18n("boards.manage.board_access_permission_manager"),
+ description: i18n(
+ "boards.manage.board_access_permission_manager_description"
+ ),
+ });
+
+ return options;
+ }
+
+ @action
+ aclChanged(acl) {
+ this.reloadAfterSave = false;
+ this.formApi.set("acl", acl);
+ }
+
+ @action
+ accessLossConfirmed() {
+ this.reloadAfterSave = true;
+ }
+
+ #buildDefaultAcl() {
+ const defaultAcl = [];
+
+ this.boardsManageBoardAllowedGroupIds.forEach((groupId) => {
+ const group = this.site.groupsById[groupId];
+ if (group) {
+ defaultAcl.push({
+ type: "group",
+ id: group.id,
+ permission: "manage",
+ display_name: group.full_name,
+ });
+ }
+ });
+
+ if (
+ !this.boardsManageBoardAllowedGroupIds.includes(
+ AUTO_GROUPS.logged_in_users.id
+ )
+ ) {
+ defaultAcl.push({
+ type: "group",
+ id: AUTO_GROUPS.logged_in_users.id,
+ permission: "view",
+ display_name: this.site.groupFullName(AUTO_GROUPS.logged_in_users.id),
+ });
+ }
+
+ return defaultAcl;
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @hideHeader={{true}}
+ @inline={{@inline}}
+ class="discourse-boards-board-settings-modal"
+ >
+ <:body>
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{this.save}}
+ @onRegisterApi={{this.onRegisterApi}}
+ as |form data|
+ >
+ <BoardsEditableTitle
+ @form={{form}}
+ @name="name"
+ @title={{i18n "boards.manage.name"}}
+ @placeholder={{i18n "boards.manage.name_placeholder"}}
+ @onClose={{@closeModal}}
+ @showClose={{true}}
+ />
+ <div class="discourse-boards-board-settings-modal__wrapper">
+
+ <form.Section>
+ <form.Field
+ @name="slug"
+ @title={{i18n "boards.manage.slug"}}
+ @format="max"
+ @type="input"
+ @placeholder={{this.slugPlaceholder}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ </form.Section>
+
+ <form.Section>
+ <DAccessControlField
+ @form={{form}}
+ @title={{i18n "boards.manage.board_access"}}
+ @aclTarget={{this.aclTarget}}
+ @description={{i18n "boards.manage.board_access_description"}}
+ @transformPermissionOptions={{this.transformPermissionOptions}}
+ @onChange={{this.aclChanged}}
+ @onAccessLossConfirmed={{this.accessLossConfirmed}}
+ @mustHavePermissions={{array "manage"}}
+ />
+ </form.Section>
+
+ <form.Section>
+ <form.Field
+ @name="constraint_type"
+ @title={{i18n "boards.manage.constrain_board_by"}}
+ @description={{i18n "boards.manage.constraint_help"}}
+ @format="max"
+ @type="select"
+ @onSet={{this.onConstraintTypeChange}}
+ as |field|
+ >
+ <field.Control as |select|>
+ {{#each CONSTRAINT_TYPE_OPTIONS as |option|}}
+ <select.Option
+ @value={{option.id}}
+ >{{option.name}}</select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ {{#if
+ (or
+ (eq data.constraint_type "categories")
+ (eq data.constraint_type "categories_and_tags")
+ )
+ }}
+ <form.Field
+ @name="category_ids"
+ @title={{i18n "boards.manage.board_categories_constraint"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <CategorySelector
+ @categories={{this.selectedCategories data.category_ids}}
+ @onChange={{fn this.onCategoriesChange field}}
+ />
+ </field.Control>
+ </form.Field>
+ {{/if}}
+
+ {{#if
+ (or
+ (eq data.constraint_type "tags")
+ (eq data.constraint_type "categories_and_tags")
+ )
+ }}
+ <form.Field
+ @name="tag_names"
+ @title={{i18n "boards.manage.board_tags_constraint"}}
+ @format="max"
+ @type="tag-chooser"
+ @onSet={{this.onTagsChange}}
+ as |field|
+ >
+ <field.Control
+ @showAllTags={{true}}
+ @excludeSynonyms={{true}}
+ @allowCreate={{true}}
+ />
+ </form.Field>
+ {{/if}}
+
+ {{#if this.constraintWarning}}
+ <form.Alert @type="warning">
+ {{this.constraintWarning}}
+ </form.Alert>
+ {{/if}}
+ </form.Section>
+ <form.Section>
+ <form.Field
+ @name="card_style"
+ @title={{i18n "boards.manage.card_style"}}
+ @description={{i18n "boards.manage.card_style_description"}}
+ @format="max"
+ @type="select"
+ as |field|
+ >
+ <field.Control as |select|>
+ {{#each CARD_STYLE_OPTIONS as |option|}}
+ <select.Option
+ @value={{option.id}}
+ >{{option.name}}</select.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ </form.Section>
+
+ {{#if this.showAdvanced}}
+ <form.Section @title={{i18n "boards.manage.advanced_settings"}}>
+
+ <form.Field
+ @name="show_tags"
+ @title={{i18n "boards.manage.show_tags"}}
+ @type="checkbox"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @name="show_topic_thumbnail"
+ @title={{i18n "boards.manage.show_topic_thumbnail"}}
+ @type="checkbox"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @name="require_confirmation"
+ @title={{i18n "boards.manage.require_confirmation"}}
+ @type="checkbox"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ </form.Section>
+ {{/if}}
+ </div>
+
+ <form.Actions>
+ <form.Submit
+ class="discourse-boards-board-settings-modal__save-board"
+ />
+ {{#unless this.isNew}}
+ <form.Button
+ class="btn-danger discourse-boards-board-settings-modal__delete-board"
+ @action={{this.onDelete}}
+ @label="boards.board.delete_board"
+ />
+ {{/unless}}
+
+ <DButton
+ @action={{this.toggleAdvanced}}
+ @icon="gear"
+ @title={{if
+ this.showAdvanced
+ "boards.manage.columns.hide_advanced"
+ "boards.manage.columns.show_advanced"
+ }}
+ class="btn-default show-advanced"
+ />
+ </form.Actions>
+ </Form>
+
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-card-detail.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-card-detail.gjs
new file mode 100644
index 00000000000..0027f7427a7
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-card-detail.gjs
@@ -0,0 +1,184 @@
+import Component from "@glimmer/component";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { USER_OPTION_COMPOSITION_MODES } from "discourse/lib/constants";
+import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
+import { not } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+import BoardsEditableTitle from "../boards-editable-title";
+
+export default class BoardsCardDetail extends Component {
+ @service siteSettings;
+ @service currentUser;
+
+ get canWrite() {
+ return this.args.model.canWrite;
+ }
+
+ get formData() {
+ const card = this.args.model.card;
+ const assignedTo = card.assigned_to;
+ return {
+ title: card.title || "",
+ notes: card.notes || "",
+ tags: [...(card.tags || [])],
+ assigned_to: assignedTo ? [assignedTo.username || assignedTo.name] : [],
+ };
+ }
+
+ get isNew() {
+ return !!this.args.model.isNew;
+ }
+
+ @action
+ onAssignedChanged(field, value) {
+ field.set(value || []);
+ }
+
+ @action
+ async save(data) {
+ const tagIds = [];
+ const tagNames = [];
+ for (const tag of data.tags || []) {
+ if (Number.isInteger(tag.id) && tag.id > 0) {
+ tagIds.push(tag.id);
+ } else if (typeof tag.id === "string" && tag.id.length > 0) {
+ tagNames.push(tag.id);
+ }
+ }
+
+ const updates = {
+ title: data.title.trim(),
+ notes: data.notes,
+ tag_ids:
+ !this.isNew && !tagIds.length && !tagNames.length ? [""] : tagIds,
+ tag_names: tagNames,
+ assigned_to_name: data.assigned_to[0] || null,
+ };
+ try {
+ if (this.isNew) {
+ await this.args.model.onCreateCard(updates);
+ } else {
+ await this.args.model.onUpdateCard(this.args.model.card.id, updates);
+ }
+ this.args.closeModal();
+ } catch {
+ // modal stays open β€” popupAjaxError already handles the error
+ }
+ }
+
+ @action
+ viewCard() {
+ if (!this.currentUser) {
+ return;
+ }
+
+ if (this.isNew) {
+ return;
+ }
+
+ ajax(
+ `/boards/api/boards/${this.args.model.card.board_id}/cards/${this.args.model.card.id}/view`,
+ { method: "POST" }
+ ).catch(() => {
+ // No error message should be shown if this fails,
+ // it's purely for history logging.
+ });
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @submitOnEnter={{false}}
+ @hideHeader={{true}}
+ class="discourse-boards-card-detail-modal"
+ {{didInsert this.viewCard}}
+ >
+ <:body>
+ <Form @data={{this.formData}} @onSubmit={{this.save}} as |form data|>
+ <BoardsEditableTitle
+ @form={{form}}
+ @name="title"
+ @title={{i18n "boards.board.title"}}
+ @placeholder={{i18n "boards.board.title_placeholder"}}
+ @disabled={{not this.canWrite}}
+ @showClose={{false}}
+ />
+ <form.Section>
+ <form.Field
+ @name="notes"
+ @title={{i18n "boards.board.notes"}}
+ @format="max"
+ @type="composer"
+ @disabled={{not this.canWrite}}
+ as |field|
+ >
+ <field.Control
+ @height={{300}}
+ @forceEditorMode={{USER_OPTION_COMPOSITION_MODES.rich}}
+ />
+ </form.Field>
+ <form.Field
+ @name="tags"
+ @title={{i18n "boards.board.tags"}}
+ @format="max"
+ @type="tag-chooser"
+ @disabled={{not this.canWrite}}
+ as |field|
+ >
+ <field.Control
+ @allowCreate={{true}}
+ @prioritizeRecentTags={{true}}
+ />
+ </form.Field>
+
+ {{#if this.siteSettings.assign_enabled}}
+ <form.Field
+ @name="assigned_to"
+ @title={{i18n "boards.board.assigned_to"}}
+ @format="max"
+ @type="custom"
+ @disabled={{not this.canWrite}}
+ as |field|
+ >
+ <field.Control>
+ <EmailGroupUserChooser
+ @value={{data.assigned_to}}
+ @onChange={{fn this.onAssignedChanged field}}
+ @options={{hash maximum=1 excludeCurrentUser=false}}
+ @disabled={{not this.canWrite}}
+ />
+ </field.Control>
+ </form.Field>
+ {{/if}}
+ </form.Section>
+
+ <form.Actions>
+ {{#if this.canWrite}}
+ <form.Submit />
+ {{/if}}
+ <form.Button
+ class="btn-flat d-modal-cancel"
+ @action={{@closeModal}}
+ @label="cancel"
+ />
+ </form.Actions>
+ </Form>
+
+ <DButton
+ @action={{@closeModal}}
+ @icon="xmark"
+ @ariaLabel="modal.close"
+ @title="modal.close"
+ class="btn-flat discourse-boards-card-detail-modal__close"
+ />
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-column-settings.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-column-settings.gjs
new file mode 100644
index 00000000000..391fef83b9f
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-column-settings.gjs
@@ -0,0 +1,325 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { isEmpty } from "@ember/utils";
+import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import CategoryChooser from "discourse/select-kit/components/category-chooser";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
+import MiniTagChooser from "discourse/select-kit/components/mini-tag-chooser";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+import {
+ ASSIGNED_OPTIONS,
+ assignedMode,
+ assignedUserValue,
+ COLUMN_SORT_OPTIONS,
+ PRESET_COLUMN_COLORS,
+ STATUS_OPTIONS,
+ tagToArray,
+} from "../../lib/boards-column-helpers";
+import BoardsEditableTitle from "../boards-editable-title";
+
+export default class BoardsColumnSettings extends Component {
+ @tracked showAdvanced = false;
+
+ get isNew() {
+ return !this.args.model.column;
+ }
+
+ @cached
+ get formData() {
+ const column = this.args.model.column;
+ if (column) {
+ return {
+ title: column.title || "",
+ icon: column.icon || null,
+ color: column.color || null,
+ default_sort: column.default_sort || "priority",
+ tag_name: column.tag_name || "",
+ move_to_category_id: column.move_to_category_id || null,
+ move_to_assigned: column.move_to_assigned || "",
+ move_to_status: column.move_to_status || "",
+ };
+ }
+ return {
+ title: "",
+ icon: null,
+ color: null,
+ default_sort: "priority",
+ tag_name: "",
+ move_to_category_id: null,
+ move_to_assigned: "",
+ move_to_status: "",
+ };
+ }
+
+ get statusOptions() {
+ return STATUS_OPTIONS;
+ }
+
+ get sortOptions() {
+ return COLUMN_SORT_OPTIONS;
+ }
+
+ get assignedOptions() {
+ return ASSIGNED_OPTIONS;
+ }
+
+ // NOTE: We are aware this is not ideal because a board
+ // can have multiple categories, but we only support one
+ // for now because server-side the tag search is limited
+ // to one category at a time.
+ get tagChooserCategoryId() {
+ return this.args.model.board?.category_ids?.[0] || null;
+ }
+
+ @action
+ onDefaultSortChange(field, value) {
+ field.set(value || "priority");
+ }
+
+ @action
+ onTagChange(field, tags) {
+ const tag = tags?.[0];
+ field.set(typeof tag === "object" ? tag.name : tag || "");
+ }
+
+ @action
+ onCategoryChange(field, value) {
+ field.set(value);
+ }
+
+ @action
+ onAssignedModeChange(field, value) {
+ field.set(value || "");
+ }
+
+ @action
+ onAssignedUserChange(field, users) {
+ field.set(users?.[0] || "_user");
+ }
+
+ @action
+ onStatusChange(field, value) {
+ field.set(value);
+ }
+
+ get showMoveToCategoryField() {
+ const boardCategoryCount = this.args.model.board?.category_ids?.length ?? 0;
+ if (boardCategoryCount === 1) {
+ return !!this.args.model.column?.move_to_category_id;
+ }
+ return true;
+ }
+
+ @action
+ toggleAdvanced() {
+ this.showAdvanced = !this.showAdvanced;
+ }
+
+ @action
+ async save(data) {
+ const columnData = {
+ title: data.title.trim() || data.tag_name.trim(),
+ icon: data.icon,
+ color: data.color || null,
+ default_sort: data.default_sort || "priority",
+ tag_name: data.tag_name || null,
+ move_to_category_id: data.move_to_category_id,
+ move_to_assigned: data.move_to_assigned,
+ move_to_status: data.move_to_status,
+ };
+ try {
+ await this.args.model.onSave(columnData);
+ this.args.closeModal();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ @action
+ validateTitle(name, value, { data, addError }) {
+ if (isEmpty(value) && isEmpty(data.tag_name)) {
+ addError("title", {
+ title: i18n("boards.manage.columns.column_title"),
+ message: i18n("boards.manage.columns.column_title_required"),
+ });
+ }
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @hideHeader={{true}}
+ class="discourse-boards-column-settings-modal"
+ >
+ <:body>
+ <Form @data={{this.formData}} @onSubmit={{this.save}} as |form data|>
+ <BoardsEditableTitle
+ @form={{form}}
+ @name="title"
+ @title={{i18n "boards.manage.columns.column_title"}}
+ @placeholder={{i18n
+ "boards.manage.columns.column_title_placeholder"
+ }}
+ @validate={{this.validateTitle}}
+ @onClose={{@closeModal}}
+ />
+ <div class="discourse-boards-column-settings-modal__wrapper">
+ <form.Section>
+ <form.Field
+ @name="icon"
+ @title={{i18n "boards.manage.columns.icon"}}
+ @format="max"
+ @type="icon"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @name="color"
+ @title={{i18n "boards.manage.columns.color"}}
+ @format="max"
+ @type="color"
+ as |field|
+ >
+ <field.Control @colors={{PRESET_COLUMN_COLORS}} />
+ </form.Field>
+
+ <form.Field
+ @name="default_sort"
+ @title={{i18n "boards.manage.columns.default_sort"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <ComboBox
+ @value={{data.default_sort}}
+ @content={{this.sortOptions}}
+ @onChange={{fn this.onDefaultSortChange field}}
+ />
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @name="tag_name"
+ @title={{i18n "boards.manage.columns.tag"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <MiniTagChooser
+ @value={{tagToArray data.tag_name}}
+ @onChange={{fn this.onTagChange field}}
+ @options={{hash
+ maximum=1
+ allowCreate=true
+ categoryId=this.tagChooserCategoryId
+ }}
+ />
+ <p class="discourse-boards-column-settings__help">
+ {{i18n "boards.manage.columns.tag_help"}}
+ </p>
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @name="move_to_status"
+ @title={{i18n "boards.manage.columns.move_to_status"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <ComboBox
+ @value={{data.move_to_status}}
+ @content={{this.statusOptions}}
+ @onChange={{fn this.onStatusChange field}}
+ @options={{hash
+ clearable=true
+ none="boards.manage.columns.move_to_status_none"
+ }}
+ />
+ </field.Control>
+ </form.Field>
+
+ {{#if this.showAdvanced}}
+ {{#if this.showMoveToCategoryField}}
+ <form.Field
+ @name="move_to_category_id"
+ @title={{i18n "boards.manage.columns.move_to_category"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <CategoryChooser
+ @value={{data.move_to_category_id}}
+ @onChange={{fn this.onCategoryChange field}}
+ @options={{hash clearable=true}}
+ />
+ </field.Control>
+ </form.Field>
+ {{/if}}
+
+ <form.Field
+ @name="move_to_assigned"
+ @title={{i18n "boards.manage.columns.move_to_assigned"}}
+ @format="max"
+ @type="custom"
+ as |field|
+ >
+ <field.Control>
+ <ComboBox
+ @value={{assignedMode data.move_to_assigned}}
+ @content={{this.assignedOptions}}
+ @onChange={{fn this.onAssignedModeChange field}}
+ @options={{hash
+ clearable=true
+ none="boards.manage.columns.move_to_assigned_none"
+ }}
+ />
+ {{#if (eq (assignedMode data.move_to_assigned) "_user")}}
+ <EmailGroupUserChooser
+ @value={{assignedUserValue data.move_to_assigned}}
+ @onChange={{fn this.onAssignedUserChange field}}
+ @options={{hash maximum=1}}
+ />
+ {{/if}}
+ </field.Control>
+ </form.Field>
+ {{/if}}
+ </form.Section>
+ </div>
+
+ <form.Actions>
+ <form.Submit class="discourse-boards-column-settings-modal__save" />
+ <form.Button
+ class="btn-flat d-modal-cancel discourse-boards-column-settings-modal__cancel"
+ @action={{@closeModal}}
+ @label="cancel"
+ />
+ <DButton
+ @action={{this.toggleAdvanced}}
+ @icon="gear"
+ @title={{if
+ this.showAdvanced
+ "boards.manage.columns.hide_advanced"
+ "boards.manage.columns.show_advanced"
+ }}
+ class="btn-default show-advanced"
+ />
+ </form.Actions>
+ </Form>
+ </:body>
+ </DModal>
+ </template>
+}
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.gjs
new file mode 100644
index 00000000000..6c829b62e21
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-constraint-fix.gjs
@@ -0,0 +1,162 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import Category from "discourse/models/category";
+import { eq, not } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+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 categoryOptions() {
+ const { mismatches } = this.args.model;
+ if (!mismatches.needsCategory) {
+ return [];
+ }
+ return mismatches.boardCategoryIds.map((id) => {
+ const cat = Category.findById(id);
+ return { id, name: cat?.name || `Category ${id}` };
+ });
+ }
+
+ get tagOptions() {
+ const { mismatches } = this.args.model;
+ if (!mismatches.needsTags) {
+ return [];
+ }
+ return mismatches.boardTagNames;
+ }
+
+ get canSave() {
+ const { mismatches } = this.args.model;
+ if (mismatches.needsCategory && !this.selectedCategoryId) {
+ return false;
+ }
+ if (mismatches.needsTags && this.selectedTagNames.length === 0) {
+ return false;
+ }
+ return true;
+ }
+
+ @action
+ selectCategory(categoryId) {
+ this.selectedCategoryId = categoryId;
+ }
+
+ @action
+ toggleTag(tagName) {
+ if (this.selectedTagNames.includes(tagName)) {
+ this.selectedTagNames = this.selectedTagNames.filter(
+ (t) => t !== tagName
+ );
+ } else {
+ this.selectedTagNames = [...this.selectedTagNames, tagName];
+ }
+ }
+
+ @action
+ confirm() {
+ const result = {};
+ const { mismatches } = this.args.model;
+
+ if (mismatches.needsCategory) {
+ result.category_id = this.selectedCategoryId;
+ }
+ if (mismatches.needsTags) {
+ result.tag_names = this.selectedTagNames;
+ }
+
+ this.args.model.onConfirm(result);
+ this.args.closeModal();
+ }
+
+ @action
+ cancel() {
+ this.args.model.onCancel?.();
+ this.args.closeModal();
+ }
+
+ <template>
+ <DModal
+ @closeModal={{this.cancel}}
+ @title={{i18n "boards.board.constraint_fix_title"}}
+ class="discourse-boards-constraint-fix-modal"
+ >
+ <:body>
+ <p class="discourse-boards-constraint-fix__description">
+ {{i18n "boards.board.constraint_fix_description"}}
+ </p>
+
+ {{#if @model.mismatches.needsCategory}}
+ <div class="discourse-boards-constraint-fix__field">
+ <label>{{i18n "boards.board.constraint_fix_category"}}</label>
+ <div class="discourse-boards-constraint-fix__options">
+ {{#each this.categoryOptions as |cat|}}
+ <DButton
+ @action={{fn this.selectCategory cat.id}}
+ @translatedLabel={{cat.name}}
+ class={{if
+ (eq this.selectedCategoryId cat.id)
+ "btn-primary discourse-boards-constraint-fix__option--selected"
+ "btn-default"
+ }}
+ data-category-id={{cat.id}}
+ />
+ {{/each}}
+ </div>
+ </div>
+ {{/if}}
+
+ {{#if @model.mismatches.needsTags}}
+ <div class="discourse-boards-constraint-fix__field">
+ <label>{{i18n "boards.board.constraint_fix_tags"}}</label>
+ <div class="discourse-boards-constraint-fix__options">
+ {{#each this.tagOptions as |tagName|}}
+ <DButton
+ @action={{fn this.toggleTag tagName}}
+ @translatedLabel={{tagName}}
+ class={{if
+ (includes this.selectedTagNames tagName)
+ "btn-primary discourse-boards-constraint-fix__option--selected"
+ "btn-default"
+ }}
+ data-tag-name={{tagName}}
+ />
+ {{/each}}
+ </div>
+ </div>
+ {{/if}}
+ </:body>
+ <:footer>
+ <DButton
+ @action={{this.confirm}}
+ @label="boards.board.constraint_fix_confirm"
+ @disabled={{not this.canSave}}
+ class="btn-primary"
+ />
+ <DButton @action={{this.cancel}} @label="cancel" class="btn-flat" />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-floater-assign.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-floater-assign.gjs
new file mode 100644
index 00000000000..cd6cb71faf9
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-floater-assign.gjs
@@ -0,0 +1,45 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+export default class BoardsFloaterAssign extends Component {
+ @tracked
+ assignee = this.args.model.currentAssignee
+ ? [this.args.model.currentAssignee]
+ : [];
+
+ @action
+ onAssigneeChanged(value) {
+ this.assignee = value || [];
+ }
+
+ @action
+ async save() {
+ await this.args.model.onSave(this.assignee[0] || null);
+ this.args.closeModal();
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "boards.board.assign_card"}}
+ class="discourse-boards-floater-assign-modal"
+ >
+ <:body>
+ <EmailGroupUserChooser
+ @value={{this.assignee}}
+ @onChange={{this.onAssigneeChanged}}
+ @options={{hash maximum=1 excludeCurrentUser=false}}
+ />
+ </:body>
+ <:footer>
+ <DButton @action={{this.save}} @label="save" class="btn-primary" />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs b/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs
new file mode 100644
index 00000000000..12335ac7f3c
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/components/modal/boards-topic-card-detail.gjs
@@ -0,0 +1,224 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import { ajax } from "discourse/lib/ajax";
+import renderTags from "discourse/lib/render-tags";
+import { emojiUnescape } from "discourse/lib/text";
+import { escapeExpression } from "discourse/lib/utilities";
+import Category from "discourse/models/category";
+import Topic from "discourse/models/topic";
+import { or } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DDecoratedHtml from "discourse/ui-kit/d-decorated-html";
+import DModal from "discourse/ui-kit/d-modal";
+import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";
+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { columnColorVariable } from "../../lib/boards-column-helpers";
+
+export default class BoardsTopicCardDetail extends Component {
+ @service currentUser;
+
+ @tracked loading = true;
+ @tracked cooked = null;
+ @tracked loadError = false;
+
+ constructor() {
+ super(...arguments);
+ this.loadFirstPost();
+ }
+
+ get topic() {
+ return this.args.model.card.topic;
+ }
+
+ get topicUrl() {
+ return Topic.create(this.topic).lastUnreadUrl;
+ }
+
+ get topicTitle() {
+ return trustHTML(
+ emojiUnescape(escapeExpression(this.args.model.card.fancyTitle || ""))
+ );
+ }
+
+ get category() {
+ if (!this.topic?.category_id) {
+ return null;
+ }
+ return Category.findById(this.topic.category_id);
+ }
+
+ get allAssignedUsers() {
+ if (this.topic?.all_assigned_users?.length) {
+ return this.topic.all_assigned_users;
+ }
+ if (this.topic?.assigned_to_user) {
+ return [this.topic.assigned_to_user];
+ }
+ return [];
+ }
+
+ get assignedGroupName() {
+ return this.topic?.assigned_to_group?.name;
+ }
+
+ get replyCount() {
+ const count = this.topic?.posts_count;
+ return count > 1 ? count - 1 : 0;
+ }
+
+ get lastPoster() {
+ return this.topic?.last_poster;
+ }
+
+ get columnData() {
+ const { columnTitle, columnIcon, columnColor } = this.args.model;
+ if (!columnTitle) {
+ return null;
+ }
+ return { title: columnTitle, icon: columnIcon, color: columnColor };
+ }
+
+ get tagsHtml() {
+ if (!this.topic?.tags?.length) {
+ return null;
+ }
+ return renderTags(null, { tags: this.topic.tags });
+ }
+
+ async loadFirstPost() {
+ try {
+ const post = await ajax(
+ `/posts/by_number/${this.args.model.card.topic_id}/1.json`
+ );
+ this.cooked = post.cooked;
+ } catch {
+ this.loadError = true;
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ viewCard() {
+ if (!this.currentUser) {
+ return;
+ }
+
+ ajax(
+ `/boards/api/boards/${this.args.model.card.board_id}/cards/${this.args.model.card.id}/view`,
+ { method: "POST" }
+ ).catch(() => {
+ // No error message should be shown if this fails,
+ // it's purely for history logging.
+ });
+ }
+
+ <template>
+ <DModal
+ @title={{this.topicTitle}}
+ @closeModal={{@closeModal}}
+ class="discourse-boards-topic-card-detail-modal"
+ {{didInsert this.viewCard}}
+ >
+ <:body>
+
+ {{#if
+ (or
+ this.category
+ this.tagsHtml
+ this.allAssignedUsers.length
+ this.columnData
+ )
+ }}
+ <div class="discourse-boards-topic-card-detail__meta">
+ {{#if this.category}}
+ {{dCategoryBadge this.category link=true}}
+ {{/if}}
+ {{#if this.tagsHtml}}
+ <span class="discourse-boards-topic-card-detail__tags">
+ {{trustHTML this.tagsHtml}}
+ </span>
+ {{/if}}
+ {{#if this.allAssignedUsers.length}}
+ <span class="discourse-boards-topic-card-detail__assigned">
+ {{dIcon "user-plus"}}
+ {{#each this.allAssignedUsers as |user|}}
+ <a
+ href="/u/{{user.username}}/activity/assigned"
+ class="discourse-boards-topic-card-detail__username"
+ >{{user.username}}</a>
+ {{/each}}
+ </span>
+ {{else if this.assignedGroupName}}
+ <span class="discourse-boards-topic-card-detail__assigned">
+ {{dIcon "group-plus"}}
+ <span
+ class="discourse-boards-topic-card-detail__username"
+ >{{this.assignedGroupName}}</span>
+ </span>
+ {{/if}}
+ {{#if this.columnData}}
+ <span
+ class="discourse-boards-column__title"
+ style={{columnColorVariable this.columnData.color}}
+ >
+ {{#if this.columnData.icon}}{{dIcon
+ this.columnData.icon
+ }}{{/if}}
+ {{this.columnData.title}}
+ </span>
+ {{/if}}
+ </div>
+ {{/if}}
+
+ <DConditionalLoadingSpinner @condition={{this.loading}}>
+ {{#if this.loadError}}
+ <div class="discourse-boards-topic-card-detail__error">
+ {{i18n "boards.board.topic_load_error"}}
+ </div>
+ {{else}}
+ <div class="discourse-boards-topic-card-detail__cooked">
+ <DDecoratedHtml
+ @html={{trustHTML this.cooked}}
+ @className="cooked"
+ />
+ </div>
+ {{/if}}
+ </DConditionalLoadingSpinner>
+
+ {{#if this.replyCount}}
+ <div class="discourse-boards-topic-card-detail__stats">
+ {{dIcon "comments"}}
+ {{i18n "boards.board.topic_reply_count" count=this.replyCount}}
+ {{#if this.lastPoster}}
+ <span
+ class="discourse-boards-topic-card-detail__separator"
+ >Β·</span>
+ {{i18n
+ "boards.board.topic_last_reply"
+ username=this.lastPoster.username
+ }}
+ {{dFormatDate this.topic.bumped_at format="medium"}}
+ {{/if}}
+ </div>
+ {{/if}}
+ </:body>
+ <:footer>
+ <DButton
+ @href={{this.topicUrl}}
+ class="btn-primary"
+ @action={{this.viewTopic}}
+ @icon="up-right-from-square"
+ @label="boards.board.view_topic"
+ />
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/boards/assets/javascripts/discourse/controllers/boards-board.js b/plugins/boards/assets/javascripts/discourse/controllers/boards-board.js
new file mode 100644
index 00000000000..5194302bb16
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/controllers/boards-board.js
@@ -0,0 +1,6 @@
+import Controller from "@ember/controller";
+
+export default class BoardsBoardController extends Controller {
+ queryParams = ["card"];
+ card = null;
+}
diff --git a/plugins/boards/assets/javascripts/discourse/initializers/boards-add-from-topic-button.js b/plugins/boards/assets/javascripts/discourse/initializers/boards-add-from-topic-button.js
new file mode 100644
index 00000000000..7169d52ac79
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/initializers/boards-add-from-topic-button.js
@@ -0,0 +1,54 @@
+import { getOwner } from "@ember/owner";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { registerTopicFooterButton } from "discourse/lib/register-topic-footer-button";
+import BoardsAddFromTopicMenu from "../components/boards-add-from-topic-menu.gjs";
+
+const BUTTON_ID = "boards-add-from-topic";
+
+export default {
+ name: "boards-add-from-topic-button",
+
+ initialize() {
+ registerTopicFooterButton({
+ id: BUTTON_ID,
+ icon: "boards",
+ label: "boards.topic_footer.add_to_board",
+ title: "boards.topic_footer.add_to_board",
+ classNames: ["boards-add-from-topic-button"],
+ displayed() {
+ if (!this.currentUser) {
+ return false;
+ }
+
+ if (!this.currentUser.can_edit_any_boards) {
+ return false;
+ }
+
+ return !this.topic?.isPrivateMessage;
+ },
+ action() {
+ const trigger = document.getElementById(
+ `topic-footer-button-${BUTTON_ID}`
+ );
+
+ if (!trigger) {
+ return;
+ }
+
+ getOwner(this)
+ .lookup("service:menu")
+ .show(trigger, {
+ identifier: "discourse-boards-add-from-topic-menu",
+ component: BoardsAddFromTopicMenu,
+ modalForMobile: true,
+ placement: "bottom-start",
+ data: { topic: this.topic },
+ });
+ },
+ });
+
+ withPluginApi((api) => {
+ api.addTrackedTopicProperties("board_memberships");
+ });
+ },
+};
diff --git a/plugins/boards/assets/javascripts/discourse/initializers/boards-keyboard-shortcuts.js b/plugins/boards/assets/javascripts/discourse/initializers/boards-keyboard-shortcuts.js
new file mode 100644
index 00000000000..a58af4755a1
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/initializers/boards-keyboard-shortcuts.js
@@ -0,0 +1,508 @@
+import { ajax } from "discourse/lib/ajax";
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+const SELECTED_CLASS = "discourse-boards-card--kb-selected";
+const BOARD_SELECTED_CLASS = "discourse-boards-board-card--kb-selected";
+
+function getColumns() {
+ return [...document.querySelectorAll(".discourse-boards-column")];
+}
+
+function getCards(columnEl) {
+ return [...columnEl.querySelectorAll(".discourse-boards-card")];
+}
+
+function getBoardCards() {
+ return [...document.querySelectorAll(".discourse-boards-board-card")];
+}
+
+function clearSelection() {
+ document
+ .querySelector(`.${SELECTED_CLASS}`)
+ ?.classList.remove(SELECTED_CLASS);
+ document
+ .querySelector(`.${BOARD_SELECTED_CLASS}`)
+ ?.classList.remove(BOARD_SELECTED_CLASS);
+}
+
+function selectCard(columnEl, cardIdx) {
+ clearSelection();
+ const cards = getCards(columnEl);
+ if (!cards.length) {
+ return;
+ }
+ const clamped = Math.min(cardIdx, cards.length - 1);
+ const card = cards[clamped];
+ card.classList.add(SELECTED_CLASS);
+ card.scrollIntoView({ block: "nearest", behavior: "smooth" });
+}
+
+function getCardDataId(cardEl) {
+ return parseInt(cardEl.dataset.cardId, 10);
+}
+
+function getColumnDataId(columnEl) {
+ const id = columnEl.dataset.columnId;
+ return id ? parseInt(id, 10) : null;
+}
+
+function isRecencyColumnEl(columnEl) {
+ return columnEl?.dataset.defaultSort === "recency";
+}
+
+function moveCard(container, cardId, toColumnId, afterCardId) {
+ const router = container.lookup("service:router");
+ const boardId = router.currentRoute?.params?.id;
+ if (!boardId) {
+ return Promise.reject("No board ID");
+ }
+
+ const messageBus = container.lookup("service:message-bus");
+ const clientId = messageBus?.clientId;
+
+ return ajax(`/boards/api/boards/${boardId}/cards/${cardId}`, {
+ type: "PUT",
+ data: {
+ client_id: clientId,
+ card: {
+ column_id: toColumnId,
+ after_card_id: afterCardId,
+ },
+ },
+ }).then((result) => {
+ if (result?.card) {
+ const boardViewer = document.querySelector(
+ ".discourse-boards-board-viewer"
+ );
+ if (boardViewer) {
+ boardViewer.dispatchEvent(
+ new CustomEvent("boards:card-moved", { detail: result.card })
+ );
+ }
+ }
+ return result;
+ });
+}
+
+const BOARD_CONTEXT = ".discourse-boards-board-viewer";
+const BOARDS_LIST_CONTEXT = ".discourse-boards-boards-grid";
+const SHORTCUT_HELP_CATEGORY = "boards";
+
+function shortcutHelp(name, definition) {
+ return {
+ category: SHORTCUT_HELP_CATEGORY,
+ name: `${SHORTCUT_HELP_CATEGORY}.${name}`,
+ definition,
+ };
+}
+
+export default {
+ name: "boards-keyboard-shortcuts",
+
+ initialize(container) {
+ let colIndex = -1;
+ let cardIndex = -1;
+ let boardIndex = -1;
+ let moving = false;
+
+ function resetCursor() {
+ colIndex = -1;
+ cardIndex = -1;
+ boardIndex = -1;
+ clearSelection();
+ }
+
+ function ensureCursor() {
+ if (colIndex === -1) {
+ colIndex = 0;
+ cardIndex = 0;
+ return true;
+ }
+ return false;
+ }
+
+ const router = container.lookup("service:router");
+ router.on("routeDidChange", resetCursor);
+
+ withPluginApi((api) => {
+ // Board list: h/l navigate between board cards
+
+ api.addKeyboardShortcut(
+ "h",
+ () => {
+ const boards = getBoardCards();
+ if (!boards.length) {
+ return;
+ }
+ if (boardIndex === -1) {
+ boardIndex = 0;
+ } else if (boardIndex > 0) {
+ boardIndex--;
+ }
+ clearSelection();
+ boards[boardIndex].classList.add(BOARD_SELECTED_CLASS);
+ boards[boardIndex].scrollIntoView({
+ block: "nearest",
+ behavior: "smooth",
+ });
+ },
+ {
+ context: BOARDS_LIST_CONTEXT,
+ help: shortcutHelp("navigate_boards_columns", {
+ keys1: ["h"],
+ keys2: ["l"],
+ shortcutsDelimiter: "slash",
+ }),
+ }
+ );
+
+ api.addKeyboardShortcut(
+ "l",
+ () => {
+ const boards = getBoardCards();
+ if (!boards.length) {
+ return;
+ }
+ if (boardIndex === -1) {
+ boardIndex = 0;
+ } else if (boardIndex < boards.length - 1) {
+ boardIndex++;
+ }
+ clearSelection();
+ boards[boardIndex].classList.add(BOARD_SELECTED_CLASS);
+ boards[boardIndex].scrollIntoView({
+ block: "nearest",
+ behavior: "smooth",
+ });
+ },
+ { context: BOARDS_LIST_CONTEXT }
+ );
+
+ api.addKeyboardShortcut(
+ "enter",
+ () => {
+ document
+ .querySelector(
+ `.${BOARD_SELECTED_CLASS} a.discourse-boards-board-card__name`
+ )
+ ?.click();
+ },
+ {
+ context: BOARDS_LIST_CONTEXT,
+ }
+ );
+
+ // Board viewer: h/l move between columns, j/k move within column
+
+ api.addKeyboardShortcut(
+ "h",
+ () => {
+ const columns = getColumns();
+ if (!columns.length) {
+ return;
+ }
+ if (!ensureCursor() && colIndex > 0) {
+ colIndex--;
+ const cards = getCards(columns[colIndex]);
+ cardIndex = Math.min(cardIndex, Math.max(0, cards.length - 1));
+ }
+ selectCard(columns[colIndex], cardIndex);
+ },
+ { context: BOARD_CONTEXT }
+ );
+
+ api.addKeyboardShortcut(
+ "l",
+ () => {
+ const columns = getColumns();
+ if (!columns.length) {
+ return;
+ }
+ if (!ensureCursor() && colIndex < columns.length - 1) {
+ colIndex++;
+ const cards = getCards(columns[colIndex]);
+ cardIndex = Math.min(cardIndex, Math.max(0, cards.length - 1));
+ }
+ selectCard(columns[colIndex], cardIndex);
+ },
+ { context: BOARD_CONTEXT }
+ );
+
+ api.addKeyboardShortcut(
+ "j",
+ () => {
+ const columns = getColumns();
+ if (!columns.length) {
+ return;
+ }
+ if (!ensureCursor()) {
+ const cards = getCards(columns[colIndex]);
+ if (cardIndex < cards.length - 1) {
+ cardIndex++;
+ }
+ }
+ selectCard(columns[colIndex], cardIndex);
+ },
+ {
+ context: BOARD_CONTEXT,
+ help: shortcutHelp("navigate_cards", {
+ keys1: ["j"],
+ keys2: ["k"],
+ shortcutsDelimiter: "slash",
+ }),
+ }
+ );
+
+ api.addKeyboardShortcut(
+ "k",
+ () => {
+ const columns = getColumns();
+ if (!columns.length) {
+ return;
+ }
+ if (!ensureCursor() && cardIndex > 0) {
+ cardIndex--;
+ }
+ selectCard(columns[colIndex], cardIndex);
+ },
+ { context: BOARD_CONTEXT }
+ );
+
+ api.addKeyboardShortcut(
+ "enter",
+ () => {
+ const selected = document.querySelector(`.${SELECTED_CLASS}`);
+ if (!selected) {
+ return;
+ }
+ const link = selected.querySelector("a.discourse-boards-card__title");
+ if (link) {
+ link.click();
+ return;
+ }
+ selected.click();
+ },
+ {
+ context: BOARD_CONTEXT,
+ }
+ );
+
+ // Escape: clear selection
+ api.addKeyboardShortcut(
+ "escape",
+ () => {
+ if (
+ document.querySelector(`.${SELECTED_CLASS}`) ||
+ document.querySelector(`.${BOARD_SELECTED_CLASS}`)
+ ) {
+ resetCursor();
+ }
+ },
+ { context: BOARD_CONTEXT }
+ );
+
+ api.addKeyboardShortcut(
+ "escape",
+ () => {
+ if (document.querySelector(`.${BOARD_SELECTED_CLASS}`)) {
+ resetCursor();
+ }
+ },
+ { context: BOARDS_LIST_CONTEXT }
+ );
+
+ // Shift+h/l: move card between columns
+ // Shift+j/k: reorder card within column
+
+ function afterMove(newColIndex, newCardIndex) {
+ colIndex = newColIndex;
+ cardIndex = newCardIndex;
+ moving = false;
+
+ // Wait for Ember to re-render after the board viewer processes
+ // the boards:card-moved event before re-selecting the card.
+ setTimeout(() => {
+ const cols = getColumns();
+ if (cols[colIndex]) {
+ const cards = getCards(cols[colIndex]);
+ cardIndex = Math.min(cardIndex, Math.max(0, cards.length - 1));
+ selectCard(cols[colIndex], cardIndex);
+ }
+ }, 300);
+ }
+
+ api.addKeyboardShortcut(
+ "shift+l",
+ () => {
+ if (moving) {
+ return;
+ }
+ const columns = getColumns();
+ if (colIndex === -1 || colIndex >= columns.length - 1) {
+ return;
+ }
+ const cards = getCards(columns[colIndex]);
+ if (!cards.length || cardIndex >= cards.length) {
+ return;
+ }
+
+ const cardId = getCardDataId(cards[cardIndex]);
+ const targetColumn = columns[colIndex + 1];
+ const toColumnId = getColumnDataId(targetColumn);
+ if (!toColumnId) {
+ return;
+ }
+
+ const targetIsRecency = isRecencyColumnEl(targetColumn);
+ const targetCards = getCards(targetColumn);
+ let afterCardId = null;
+ if (!targetIsRecency) {
+ const targetIdx = Math.min(cardIndex, targetCards.length) - 1;
+ if (targetIdx >= 0) {
+ afterCardId = getCardDataId(targetCards[targetIdx]);
+ }
+ }
+
+ const newCardIndex = targetIsRecency ? 0 : cardIndex;
+ moving = true;
+ moveCard(container, cardId, toColumnId, afterCardId).then(
+ () => afterMove(colIndex + 1, newCardIndex),
+ () => {
+ moving = false;
+ }
+ );
+ },
+ {
+ context: BOARD_CONTEXT,
+ help: shortcutHelp("move_card_column", {
+ keys1: ["shift", "h"],
+ keys2: ["shift", "l"],
+ shortcutsDelimiter: "slash",
+ }),
+ }
+ );
+
+ api.addKeyboardShortcut(
+ "shift+h",
+ () => {
+ if (moving) {
+ return;
+ }
+ const columns = getColumns();
+ if (colIndex <= 0) {
+ return;
+ }
+ const cards = getCards(columns[colIndex]);
+ if (!cards.length || cardIndex >= cards.length) {
+ return;
+ }
+
+ const cardId = getCardDataId(cards[cardIndex]);
+ const targetColumn = columns[colIndex - 1];
+ const toColumnId = getColumnDataId(targetColumn);
+ if (!toColumnId) {
+ return;
+ }
+
+ const targetIsRecency = isRecencyColumnEl(targetColumn);
+ const targetCards = getCards(targetColumn);
+ let afterCardId = null;
+ if (!targetIsRecency) {
+ const targetIdx = Math.min(cardIndex, targetCards.length) - 1;
+ if (targetIdx >= 0) {
+ afterCardId = getCardDataId(targetCards[targetIdx]);
+ }
+ }
+
+ const newCardIndex = targetIsRecency ? 0 : cardIndex;
+ moving = true;
+ moveCard(container, cardId, toColumnId, afterCardId).then(
+ () => afterMove(colIndex - 1, newCardIndex),
+ () => {
+ moving = false;
+ }
+ );
+ },
+ { context: BOARD_CONTEXT }
+ );
+
+ api.addKeyboardShortcut(
+ "shift+j",
+ () => {
+ if (moving) {
+ return;
+ }
+ const columns = getColumns();
+ if (colIndex === -1 || isRecencyColumnEl(columns[colIndex])) {
+ return;
+ }
+ const cards = getCards(columns[colIndex]);
+ if (cardIndex >= cards.length - 1) {
+ return;
+ }
+
+ const cardId = getCardDataId(cards[cardIndex]);
+ const columnId = getColumnDataId(columns[colIndex]);
+ if (!columnId) {
+ return;
+ }
+
+ const afterCardId = getCardDataId(cards[cardIndex + 1]);
+
+ moving = true;
+ moveCard(container, cardId, columnId, afterCardId).then(
+ () => afterMove(colIndex, cardIndex + 1),
+ () => {
+ moving = false;
+ }
+ );
+ },
+ {
+ context: BOARD_CONTEXT,
+ help: shortcutHelp("move_card_position", {
+ keys1: ["shift", "j"],
+ keys2: ["shift", "k"],
+ shortcutsDelimiter: "slash",
+ }),
+ }
+ );
+
+ api.addKeyboardShortcut(
+ "shift+k",
+ () => {
+ if (moving) {
+ return;
+ }
+ const columns = getColumns();
+ if (
+ colIndex === -1 ||
+ cardIndex <= 0 ||
+ isRecencyColumnEl(columns[colIndex])
+ ) {
+ return;
+ }
+ const cards = getCards(columns[colIndex]);
+ const cardId = getCardDataId(cards[cardIndex]);
+ const columnId = getColumnDataId(columns[colIndex]);
+ if (!columnId) {
+ return;
+ }
+
+ let afterCardId = null;
+ if (cardIndex >= 2) {
+ afterCardId = getCardDataId(cards[cardIndex - 2]);
+ }
+
+ moving = true;
+ moveCard(container, cardId, columnId, afterCardId).then(
+ () => afterMove(colIndex, cardIndex - 1),
+ () => {
+ moving = false;
+ }
+ );
+ },
+ { context: BOARD_CONTEXT }
+ );
+ });
+ },
+};
diff --git a/plugins/boards/assets/javascripts/discourse/initializers/boards-onebox-relative-dates.js b/plugins/boards/assets/javascripts/discourse/initializers/boards-onebox-relative-dates.js
new file mode 100644
index 00000000000..3f28bc297b7
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/initializers/boards-onebox-relative-dates.js
@@ -0,0 +1,29 @@
+import { longDate, updateRelativeAge } from "discourse/lib/formatter";
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+export default {
+ name: "boards-onebox-relative-dates",
+
+ initialize() {
+ withPluginApi((api) => {
+ api.decorateCookedElement((elem) => {
+ const dates = elem.querySelectorAll(
+ ".discourse-boards-onebox__updated-at.relative-date[data-time]"
+ );
+
+ if (!dates.length) {
+ return;
+ }
+
+ dates.forEach((el) => {
+ const ts = parseInt(el.dataset.time, 10);
+ if (ts) {
+ el.title = longDate(new Date(ts));
+ }
+ });
+
+ updateRelativeAge(dates);
+ });
+ });
+ },
+};
diff --git a/plugins/boards/assets/javascripts/discourse/initializers/boards-topic-pill.js b/plugins/boards/assets/javascripts/discourse/initializers/boards-topic-pill.js
new file mode 100644
index 00000000000..5994c84b219
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/initializers/boards-topic-pill.js
@@ -0,0 +1,93 @@
+import { setOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { bind } from "discourse/lib/decorators";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import BoardsMenu from "../components/boards-menu";
+import {
+ boardsTagsHtml,
+ membershipsFor,
+ MULTI_BOARD_TRIGGER_SELECTOR,
+} from "../lib/boards-topic-pill";
+
+/**
+ * Topic pills are rendered as tags, as raw HTML, so there is no component to
+ * hang a click handler on. Boards are delegated from the app root the way
+ * discourse-local-dates opens its date popover.
+ */
+class BoardsTopicPills {
+ @service menu;
+
+ // keyed by the trigger, so a menu is built once per pill and goes away with it
+ #menus = new WeakMap();
+
+ constructor(owner) {
+ setOwner(this, owner);
+
+ withPluginApi((api) => api.addTagsHtmlCallback(boardsTagsHtml));
+
+ this.rootElement = document.querySelector(owner.rootElement);
+ this.rootElement?.addEventListener("click", this.onClick);
+ this.rootElement?.addEventListener("keydown", this.onKeydown);
+ }
+
+ @bind
+ onClick(event) {
+ return this.#toggleMenu(event);
+ }
+
+ @bind
+ onKeydown(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ return this.#toggleMenu(event);
+ }
+ }
+
+ teardown() {
+ this.rootElement?.removeEventListener("click", this.onClick);
+ this.rootElement?.removeEventListener("keydown", this.onKeydown);
+ this.rootElement = null;
+ }
+
+ #toggleMenu(event) {
+ const trigger = event.target.closest(MULTI_BOARD_TRIGGER_SELECTOR);
+ if (!trigger) {
+ return;
+ }
+
+ event.preventDefault();
+
+ const instance = this.#menuFor(trigger);
+ return instance.expanded ? instance.close() : instance.show();
+ }
+
+ #menuFor(trigger) {
+ let instance = this.#menus.get(trigger);
+
+ if (!instance) {
+ instance = this.menu.newInstance(trigger, {
+ identifier: "discourse-boards-topic-pill",
+ component: BoardsMenu,
+ modalForMobile: true,
+ data: { memberships: membershipsFor(trigger) },
+ onShow: () => trigger.setAttribute("aria-expanded", "true"),
+ onClose: () => trigger.setAttribute("aria-expanded", "false"),
+ });
+ this.#menus.set(trigger, instance);
+ }
+
+ return instance;
+ }
+}
+
+export default {
+ name: "discourse-boards-topic-pill",
+
+ initialize(_container, owner) {
+ this.instance = new BoardsTopicPills(owner);
+ },
+
+ teardown() {
+ this.instance?.teardown();
+ this.instance = null;
+ },
+};
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-auto-scroll.js b/plugins/boards/assets/javascripts/discourse/lib/boards-auto-scroll.js
new file mode 100644
index 00000000000..e87a2deb4d1
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-auto-scroll.js
@@ -0,0 +1,227 @@
+import { modifier } from "ember-modifier";
+
+const AUTO_SCROLL_EDGE_SIZE = 72;
+const AUTO_SCROLL_MAX_SPEED = 10;
+
+export function autoScrollSpeedForPointer(pointerPosition, rect, axis = "y") {
+ if (!rect) {
+ return 0;
+ }
+
+ const startEdge = axis === "x" ? rect.left : rect.top;
+ const endEdge = axis === "x" ? rect.right : rect.bottom;
+
+ const startDistance = pointerPosition - startEdge;
+ if (startDistance < AUTO_SCROLL_EDGE_SIZE) {
+ return -Math.ceil(
+ ((AUTO_SCROLL_EDGE_SIZE - Math.max(startDistance, 0)) /
+ AUTO_SCROLL_EDGE_SIZE) *
+ AUTO_SCROLL_MAX_SPEED
+ );
+ }
+
+ const endDistance = endEdge - pointerPosition;
+ if (endDistance < AUTO_SCROLL_EDGE_SIZE) {
+ return Math.ceil(
+ ((AUTO_SCROLL_EDGE_SIZE - Math.max(endDistance, 0)) /
+ AUTO_SCROLL_EDGE_SIZE) *
+ AUTO_SCROLL_MAX_SPEED
+ );
+ }
+
+ return 0;
+}
+
+const DRAG_SCROLL_SKIP_SELECTOR =
+ ".discourse-boards-card, button, a, input, textarea, select, [contenteditable=''], [contenteditable='true']";
+
+const DRAG_SCROLL_MOMENTUM_FRICTION = 0.92;
+const DRAG_SCROLL_MOMENTUM_MAX_PX_PER_FRAME = 4;
+const DRAG_SCROLL_MOMENTUM_MIN_PX_PER_FRAME = 0.5;
+const DRAG_SCROLL_VELOCITY_WINDOW_MS = 80;
+const DRAG_SCROLL_MS_PER_FRAME = 1000 / 60;
+
+export const dragToScroll = modifier((element) => {
+ let activePointerId = null;
+ let startX = 0;
+ let startScrollLeft = 0;
+ let dragStarted = false;
+ let velocitySamples = [];
+ let momentumFrame = null;
+ let pendingMoveFrame = null;
+ let latestClientX = 0;
+
+ const cancelMomentum = () => {
+ if (momentumFrame) {
+ cancelAnimationFrame(momentumFrame);
+ momentumFrame = null;
+ }
+ };
+
+ const cancelPendingMove = () => {
+ if (pendingMoveFrame) {
+ cancelAnimationFrame(pendingMoveFrame);
+ pendingMoveFrame = null;
+ }
+ };
+
+ const pruneVelocitySamples = (now) => {
+ const cutoff = now - DRAG_SCROLL_VELOCITY_WINDOW_MS;
+ while (velocitySamples.length > 1 && velocitySamples[0].time < cutoff) {
+ velocitySamples.shift();
+ }
+ };
+
+ const recordSample = (event) => {
+ velocitySamples.push({ time: event.timeStamp, x: event.clientX });
+ pruneVelocitySamples(event.timeStamp);
+ };
+
+ const startMomentum = (endTime) => {
+ pruneVelocitySamples(endTime);
+ if (velocitySamples.length < 2) {
+ return;
+ }
+
+ const oldest = velocitySamples[0];
+ const newest = velocitySamples[velocitySamples.length - 1];
+ const dt = newest.time - oldest.time;
+ if (dt <= 0) {
+ return;
+ }
+
+ const pointerVelocityPerMs = (newest.x - oldest.x) / dt;
+ let velocity = -pointerVelocityPerMs * DRAG_SCROLL_MS_PER_FRAME;
+ velocity = Math.max(
+ Math.min(velocity, DRAG_SCROLL_MOMENTUM_MAX_PX_PER_FRAME),
+ -DRAG_SCROLL_MOMENTUM_MAX_PX_PER_FRAME
+ );
+
+ if (Math.abs(velocity) < DRAG_SCROLL_MOMENTUM_MIN_PX_PER_FRAME) {
+ return;
+ }
+
+ const step = () => {
+ const previous = element.scrollLeft;
+ element.scrollLeft = previous + velocity;
+ if (element.scrollLeft === previous) {
+ momentumFrame = null;
+ return;
+ }
+
+ velocity *= DRAG_SCROLL_MOMENTUM_FRICTION;
+ if (Math.abs(velocity) < DRAG_SCROLL_MOMENTUM_MIN_PX_PER_FRAME) {
+ momentumFrame = null;
+ return;
+ }
+ momentumFrame = requestAnimationFrame(step);
+ };
+
+ momentumFrame = requestAnimationFrame(step);
+ };
+
+ const onPointerDown = (event) => {
+ cancelMomentum();
+
+ if (event.button !== 0 || event.pointerType === "touch") {
+ return;
+ }
+ if (event.target.closest(DRAG_SCROLL_SKIP_SELECTOR)) {
+ return;
+ }
+ if (element.scrollWidth <= element.clientWidth) {
+ return;
+ }
+
+ activePointerId = event.pointerId;
+ startX = event.clientX;
+ startScrollLeft = element.scrollLeft;
+ dragStarted = false;
+ velocitySamples = [{ time: event.timeStamp, x: event.clientX }];
+ };
+
+ const onPointerMove = (event) => {
+ if (event.pointerId !== activePointerId) {
+ return;
+ }
+
+ const dx = event.clientX - startX;
+ if (!dragStarted) {
+ if (Math.abs(dx) < 4) {
+ return;
+ }
+ dragStarted = true;
+ element.classList.add("discourse-boards-board-container--drag-scrolling");
+ try {
+ element.setPointerCapture(activePointerId);
+ } catch {
+ // pointer capture is best-effort
+ }
+ }
+
+ event.preventDefault();
+ latestClientX = event.clientX;
+ recordSample(event);
+
+ if (pendingMoveFrame === null) {
+ pendingMoveFrame = requestAnimationFrame(() => {
+ pendingMoveFrame = null;
+ element.scrollLeft = startScrollLeft - (latestClientX - startX);
+ });
+ }
+ };
+
+ const stopDrag = (event) => {
+ if (event.pointerId !== activePointerId) {
+ return;
+ }
+
+ cancelPendingMove();
+
+ const wasDragging = dragStarted;
+ if (dragStarted) {
+ try {
+ element.releasePointerCapture(activePointerId);
+ } catch {
+ // pointer capture release is best-effort
+ }
+ element.classList.remove(
+ "discourse-boards-board-container--drag-scrolling"
+ );
+ }
+
+ activePointerId = null;
+ dragStarted = false;
+
+ if (wasDragging && event.type === "pointerup") {
+ startMomentum(event.timeStamp);
+ }
+ };
+
+ const onClickCapture = (event) => {
+ if (dragStarted) {
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ };
+
+ const onWheel = () => cancelMomentum();
+
+ element.addEventListener("pointerdown", onPointerDown);
+ element.addEventListener("pointermove", onPointerMove);
+ element.addEventListener("pointerup", stopDrag);
+ element.addEventListener("pointercancel", stopDrag);
+ element.addEventListener("click", onClickCapture, true);
+ element.addEventListener("wheel", onWheel, { passive: true });
+
+ return () => {
+ cancelMomentum();
+ cancelPendingMove();
+ element.removeEventListener("pointerdown", onPointerDown);
+ element.removeEventListener("pointermove", onPointerMove);
+ element.removeEventListener("pointerup", stopDrag);
+ element.removeEventListener("pointercancel", stopDrag);
+ element.removeEventListener("click", onClickCapture, true);
+ element.removeEventListener("wheel", onWheel);
+ };
+});
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-card-ordering.js b/plugins/boards/assets/javascripts/discourse/lib/boards-card-ordering.js
new file mode 100644
index 00000000000..908cd7bc586
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-card-ordering.js
@@ -0,0 +1,34 @@
+export const COLUMN_SORT_PRIORITY = "priority";
+export const COLUMN_SORT_RECENCY = "recency";
+
+export function isRecencyColumn(column) {
+ return column?.default_sort === COLUMN_SORT_RECENCY;
+}
+
+export function cardRecencyValue(card) {
+ const value = Date.parse(
+ card?.recency_at ||
+ card?.column_changed_at ||
+ card?.updated_at ||
+ card?.topic?.bumped_at ||
+ card?.created_at ||
+ ""
+ );
+
+ return Number.isFinite(value) ? value : 0;
+}
+
+export function sortCardsForColumn(column, cards = []) {
+ const sorted = [...cards];
+
+ if (isRecencyColumn(column)) {
+ return sorted.sort(
+ (a, b) =>
+ cardRecencyValue(b) - cardRecencyValue(a) || (b.id || 0) - (a.id || 0)
+ );
+ }
+
+ return sorted.sort(
+ (a, b) => (a.position || 0) - (b.position || 0) || (a.id || 0) - (b.id || 0)
+ );
+}
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-column-helpers.js b/plugins/boards/assets/javascripts/discourse/lib/boards-column-helpers.js
new file mode 100644
index 00000000000..3d3abb398ac
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-column-helpers.js
@@ -0,0 +1,108 @@
+import { trustHTML } from "@ember/template";
+import { isValidHex, normalizeHex } from "discourse/lib/color-transformations";
+import { i18n } from "discourse-i18n";
+
+export const COLUMN_SORT_OPTIONS = [
+ {
+ id: "priority",
+ name: i18n("boards.manage.columns.default_sort_priority"),
+ },
+ {
+ id: "recency",
+ name: i18n("boards.manage.columns.default_sort_recency"),
+ },
+];
+
+export const STATUS_OPTIONS = [
+ {
+ id: "open",
+ name: i18n("boards.manage.columns.move_to_status_open"),
+ },
+ {
+ id: "closed",
+ name: i18n("boards.manage.columns.move_to_status_closed"),
+ },
+];
+
+// Suggested palette fed to the FormKit color control as @colors. Values are
+// bare 6-digit hexes (no leading "#"), matching how core stores category colors.
+// The control also accepts any custom hex.
+export const PRESET_COLUMN_COLORS = [
+ "C97CF4",
+ "FCA700",
+ "669DF1",
+ "F87168",
+ "94C748",
+ "4BCE97",
+ "E774BB",
+ "DDB30E",
+ "6CC3E0",
+];
+
+// True when a stored color is a usable hex; drives the discourse-boards-column--has-color modifier.
+export function hasColumnColor(color) {
+ return !!isValidHex(color);
+}
+
+// Relative luminance of a 6-digit hex (0–1), used to pick contrasting text.
+function luminance(hex) {
+ const r = parseInt(hex.slice(0, 2), 16);
+ const g = parseInt(hex.slice(2, 4), 16);
+ const b = parseInt(hex.slice(4, 6), 16);
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+}
+
+// Mirrors core's categoryColorVariable: turns a stored hex into inline custom
+// properties β€” the fill plus a contrasting title text color so the header
+// stays readable for any color, preset or custom. The title sits on a chip
+// that darkens the fill by ~30%, so its text color is judged against that
+// darker background. The header text (count included) stays a tint of the
+// fill's own hue, with its lightness handled scheme-side in SCSS.
+export function columnColorVariable(color) {
+ if (!isValidHex(color)) {
+ // Colorless columns fill with the scheme's --primary-500; --secondary is
+ // core's text-on-filled-control color and tracks scheme switches live,
+ // so no contrast math is needed here.
+ return trustHTML(
+ "--discourse-boards-column-color: var(--primary-500); --discourse-boards-column-title-text-color: var(--secondary);"
+ );
+ }
+ const hex = normalizeHex(color);
+ const lum = luminance(hex);
+ const titleText = lum * 0.7 > 0.5 ? "#000000" : "#ffffff";
+ return trustHTML(
+ `--discourse-boards-column-color: #${hex}; --discourse-boards-column-title-text-color: ${titleText};`
+ );
+}
+
+export const ASSIGNED_OPTIONS = [
+ {
+ id: "nobody",
+ name: i18n("boards.manage.columns.move_to_assigned_unassign"),
+ },
+ {
+ id: "_user",
+ name: i18n("boards.manage.columns.move_to_assigned_user"),
+ },
+];
+
+export function tagToArray(tag) {
+ return tag ? [tag] : [];
+}
+
+export function assignedMode(value) {
+ if (!value) {
+ return "";
+ }
+ if (value === "nobody") {
+ return "nobody";
+ }
+ return "_user";
+}
+
+export function assignedUserValue(value) {
+ if (!value || value === "nobody" || value === "_user") {
+ return [];
+ }
+ return [value];
+}
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-motion.js b/plugins/boards/assets/javascripts/discourse/lib/boards-motion.js
new file mode 100644
index 00000000000..527c5871c9e
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-motion.js
@@ -0,0 +1,105 @@
+const REORDER_ANIMATION = Symbol("boards-reorder-animation");
+
+// Keep in sync with the matching CSS vars in boards-board.scss.
+export const KANBAN_REORDER_DURATION = 180;
+export const KANBAN_MOTION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";
+
+export function boardsMotionEnabled() {
+ if (typeof window === "undefined") {
+ return false;
+ }
+
+ return !window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;
+}
+
+export function captureCardRects(container, { skipCardIds = [] } = {}) {
+ const rects = new Map();
+ if (!container) {
+ return rects;
+ }
+
+ const skipIds = new Set(skipCardIds.map(String));
+
+ container
+ .querySelectorAll(".discourse-boards-card")
+ .forEach((cardElement) => {
+ const cardId = cardElement.dataset.cardId;
+ if (!cardId || skipIds.has(cardId)) {
+ return;
+ }
+
+ const rect = cardElement.getBoundingClientRect();
+ rects.set(cardId, {
+ top: rect.top,
+ left: rect.left,
+ });
+ });
+
+ return rects;
+}
+
+export function animateCardReorder(
+ container,
+ previousRects,
+ { skipCardIds = [] } = {}
+) {
+ if (!boardsMotionEnabled() || !container || !previousRects?.size) {
+ return;
+ }
+
+ const skipIds = new Set(skipCardIds.map(String));
+
+ container
+ .querySelectorAll(".discourse-boards-card")
+ .forEach((cardElement) => {
+ const cardId = cardElement.dataset.cardId;
+ if (!cardId || skipIds.has(cardId)) {
+ return;
+ }
+
+ const previousRect = previousRects.get(cardId);
+ if (!previousRect) {
+ return;
+ }
+
+ const currentRect = cardElement.getBoundingClientRect();
+ const deltaX = previousRect.left - currentRect.left;
+ const deltaY = previousRect.top - currentRect.top;
+
+ if (Math.abs(deltaX) < 1 && Math.abs(deltaY) < 1) {
+ return;
+ }
+
+ if (!cardElement.animate) {
+ return;
+ }
+
+ cardElement[REORDER_ANIMATION]?.cancel();
+
+ const animation = cardElement.animate(
+ [
+ {
+ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)`,
+ },
+ {
+ transform: "translate3d(0, 0, 0)",
+ },
+ ],
+ {
+ duration: KANBAN_REORDER_DURATION,
+ easing: KANBAN_MOTION_EASING,
+ }
+ );
+
+ cardElement[REORDER_ANIMATION] = animation;
+
+ const clearAnimation = () => {
+ if (cardElement[REORDER_ANIMATION] === animation) {
+ cardElement[REORDER_ANIMATION] = null;
+ }
+ };
+
+ animation.onfinish = clearAnimation;
+ animation.oncancel = clearAnimation;
+ });
+}
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-topic-pill.js b/plugins/boards/assets/javascripts/discourse/lib/boards-topic-pill.js
new file mode 100644
index 00000000000..81b01727e7a
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-topic-pill.js
@@ -0,0 +1,186 @@
+import { iconHTML } from "discourse/lib/icon-library";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import { escapeExpression } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+import { boardsBoardUrl } from "./boards-urls";
+
+export const MULTI_BOARD_TRIGGER_SELECTOR =
+ ".discourse-boards-topic-pill--multiple";
+
+// Fields written per card, and read back by `membershipsFor`
+const CARD_FIELDS = [
+ "board-id",
+ "board-name",
+ "board-slug",
+ "card-id",
+ "column-title",
+ "column-color",
+ "column-icon",
+];
+
+export function membershipCardUrl(membership) {
+ const boardUrl = boardsBoardUrl({
+ slug: membership.board_slug,
+ id: membership.board_id,
+ });
+ return `${boardUrl}?card=${membership.cards[0].card_id}`;
+}
+
+export function membershipTitle(membership) {
+ const boardName = membership.unicode_board_name || membership.board_name;
+
+ if (membership.cards.length > 1) {
+ return i18n("boards.topic_pill.title_multiple_columns", {
+ board: boardName,
+ count: membership.cards.length,
+ });
+ }
+
+ return i18n("boards.topic_pill.title", {
+ board: boardName,
+ column:
+ membership.cards[0].unicode_column_title ||
+ membership.cards[0].column_title,
+ });
+}
+
+/** Regroups what `boardData` wrote out, for the menu the pill opens. */
+export function membershipsFor(trigger) {
+ const boards = new Map();
+ const count = Number(trigger.dataset.cardCount);
+
+ for (let index = 0; index < count; index++) {
+ // absent attributes stay undefined, so an uncoloured or iconless column
+ // reads back the way the serializer sent it
+ const field = (name) =>
+ trigger.getAttribute(`data-card-${index}-${name}`) ?? undefined;
+
+ const boardId = field("board-id");
+ let board = boards.get(boardId);
+
+ if (!board) {
+ board = {
+ board_id: Number(boardId),
+ board_name: field("board-name"),
+ board_slug: field("board-slug"),
+ cards: [],
+ };
+ boards.set(boardId, board);
+ }
+
+ board.cards.push({
+ card_id: Number(field("card-id")),
+ column_title: field("column-title"),
+ column_color: field("column-color"),
+ column_icon: field("column-icon"),
+ });
+ }
+
+ return [...boards.values()];
+}
+
+function attrs(attributes) {
+ return Object.entries(attributes)
+ .filter(([, value]) => value !== undefined && value !== null)
+ .map(([name, value]) => ` ${name}="${escapeExpression(value)}"`)
+ .join("");
+}
+
+function pill(tagName, { extraClass, label, ...attributes }) {
+ const className = [
+ "discourse-boards-topic-pill",
+ "discourse-tag",
+ "simple",
+ extraClass,
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ return (
+ `<${tagName}${attrs({ class: className, ...attributes })}>` +
+ iconHTML("table-columns") +
+ `<span class="discourse-boards-topic-pill__label">${escapeExpression(label)}</span>` +
+ `</${tagName}>`
+ );
+}
+
+function boardPill(membership, tagName) {
+ const link =
+ tagName === "a"
+ ? { href: membershipCardUrl(membership), "data-auto-route": "true" }
+ : {};
+
+ return pill(tagName, {
+ label: membership.unicode_board_name || membership.board_name,
+ title: membershipTitle(membership),
+ ...link,
+ });
+}
+
+// The menu is opened by a delegated listener, which has only the element to go
+// on, so the boards ride along in data attributes the way discourse-local-dates
+// carries its date config.
+function boardData(memberships) {
+ const cards = memberships.flatMap((membership) =>
+ membership.cards.map((card) => ({
+ "board-id": membership.board_id,
+ "board-name": membership.unicode_board_name || membership.board_name,
+ "board-slug": membership.board_slug,
+ "card-id": card.card_id,
+ "column-title": card.unicode_column_title || card.column_title,
+ "column-color": card.column_color,
+ "column-icon": card.column_icon,
+ }))
+ );
+
+ return Object.fromEntries([
+ ["data-card-count", cards.length],
+ ...cards.flatMap((card, index) =>
+ CARD_FIELDS.map((name) => [`data-card-${index}-${name}`, card[name]])
+ ),
+ ]);
+}
+
+function multiBoardPill(memberships) {
+ return pill("a", {
+ extraClass: "discourse-boards-topic-pill--multiple",
+ label: i18n("boards.topic_pill.multiple", {
+ count: memberships.length,
+ }),
+ title: i18n("boards.topic_pill.multiple_title"),
+ role: "button",
+ tabindex: "0",
+ "aria-haspopup": "true",
+ "aria-expanded": "false",
+ ...boardData(memberships),
+ });
+}
+
+export function boardsTagsHtml(topic, params) {
+ const memberships = topic.board_memberships;
+ if (!memberships?.length) {
+ return;
+ }
+
+ const tagName = params?.tagName || "a";
+
+ if (memberships.length > 1 && tagName === "a") {
+ return multiBoardPill(memberships);
+ }
+
+ return memberships
+ .map((membership, index) => {
+ let html = boardPill(membership, tagName);
+
+ if (index < memberships.length - 1) {
+ const separator = applyValueTransformer("tag-separator", ",", {
+ topic,
+ index,
+ });
+ html += `<span class="discourse-tags__tag-separator">${separator}</span>`;
+ }
+
+ return html;
+ })
+ .join("");
+}
diff --git a/plugins/boards/assets/javascripts/discourse/lib/boards-urls.js b/plugins/boards/assets/javascripts/discourse/lib/boards-urls.js
new file mode 100644
index 00000000000..509720e1d88
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/boards-urls.js
@@ -0,0 +1,11 @@
+export function boardsBoardUrl(board) {
+ return `/boards/${board.slug}/${board.id}`;
+}
+
+export function boardsBoardConfigureUrl(board) {
+ return `${boardsBoardUrl(board)}/configure`;
+}
+
+export function boardsCardUrl(board, cardId) {
+ return `${boardsBoardUrl(board)}/cards/${cardId}`;
+}
diff --git a/plugins/boards/assets/javascripts/discourse/lib/fabricators.js b/plugins/boards/assets/javascripts/discourse/lib/fabricators.js
new file mode 100644
index 00000000000..426aee7ad31
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/lib/fabricators.js
@@ -0,0 +1,66 @@
+/*
+Fabricators are used to create fake data for testing purposes.
+The following fabricators are available in lib folder to allow
+styleguide to use them, and eventually to generate dummy data
+in a placeholder component. It should not be used for any other case.
+*/
+import ApplicationInstance from "@ember/application/instance";
+import { setOwner } from "@ember/owner";
+import CoreFabricators, { incrementSequence } from "discourse/lib/fabricators";
+import Board from "../models/board";
+import Card from "../models/card";
+import Column from "../models/column";
+
+export default class BoardsFabricators {
+ constructor(owner) {
+ if (owner && !(owner instanceof ApplicationInstance)) {
+ throw new Error(
+ "First argument of BoardsFabricators constructor must be the owning ApplicationInstance"
+ );
+ }
+ setOwner(this, owner);
+ this.coreFabricators = new CoreFabricators(owner);
+ }
+
+ card(args = {}) {
+ return Card.create({
+ id: args.id || incrementSequence(),
+ title: args.title || "Test Card",
+ unicode_title: args.unicode_title,
+ card_type: args.card_type || (args.topic ? "topic" : "floater"),
+ notes: args.notes || "This is a test card",
+ created_at: args.created_at || moment(),
+ created_by: args.created_by || this.coreFabricators.user(),
+ board_id: args.board_id,
+ column_id: args.column_id,
+ // TODO: Add assign fabricator with avatar_template, type, and username
+ assigned_to: args.assigned_to,
+ inline_onebox_data: args.inline_onebox_data,
+ tags: args.tags || [],
+ tag_ids: args.tag_ids || [],
+ topic_id: args.topic?.id || null,
+ topic: args.topic || null,
+ });
+ }
+
+ board(args = {}) {
+ return Board.create({
+ id: args.id || incrementSequence(),
+ name: args.name || "Test Board",
+ unicode_name: args.unicode_name,
+ slug: args.slug || "test-board",
+ columns: args.columns || [],
+ can_write: args.can_write ?? true,
+ can_manage: args.can_manage ?? true,
+ });
+ }
+
+ column(args = {}) {
+ return Column.create({
+ id: args.id || incrementSequence(),
+ title: args.title || "Test Column",
+ unicode_title: args.unicode_title,
+ position: args.position || 0,
+ });
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/models/board.js b/plugins/boards/assets/javascripts/discourse/models/board.js
new file mode 100644
index 00000000000..abb01c37918
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/models/board.js
@@ -0,0 +1,44 @@
+import { tracked } from "@glimmer/tracking";
+import Column from "./column";
+
+export default class Board {
+ static createPayload(data) {
+ return {
+ ...data,
+ board: Board.create(data.board),
+ columns: (data.columns || []).map((column) => Column.create(column)),
+ };
+ }
+
+ static create(args = {}) {
+ if (args instanceof Board) {
+ return args;
+ }
+ return new Board(args);
+ }
+
+ @tracked anonymous_can_read;
+ @tracked can_manage;
+ @tracked can_write;
+ @tracked card_style;
+ @tracked category_ids;
+ @tracked columns;
+ @tracked id;
+ @tracked name;
+ @tracked require_confirmation;
+ @tracked show_tags;
+ @tracked show_topic_thumbnail;
+ @tracked slug;
+ @tracked tag_ids;
+ @tracked tag_names;
+ @tracked unicode_name;
+
+ constructor(args = {}) {
+ Object.assign(this, args);
+ this.columns = (args.columns || []).map((column) => Column.create(column));
+ }
+
+ get fancyTitle() {
+ return this.unicode_name || this.name;
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/models/card.js b/plugins/boards/assets/javascripts/discourse/models/card.js
new file mode 100644
index 00000000000..8755cf8c0a9
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/models/card.js
@@ -0,0 +1,65 @@
+import { tracked } from "@glimmer/tracking";
+
+export default class Card {
+ static create(args = {}) {
+ if (args instanceof Card) {
+ return args;
+ }
+ return new Card(args);
+ }
+
+ @tracked assigned_to;
+ @tracked board_id;
+ @tracked card_type;
+ @tracked column_id;
+ @tracked created_at;
+ @tracked column_changed_at;
+ @tracked created_by;
+ @tracked id;
+ @tracked inline_onebox_data;
+ @tracked notes;
+ @tracked position;
+ @tracked recency_at;
+ @tracked tag_ids;
+ @tracked tags;
+ @tracked title;
+ @tracked topic;
+ @tracked topic_id;
+ @tracked unicode_title;
+ @tracked updated_at;
+
+ constructor(args = {}) {
+ Object.assign(this, args);
+ }
+
+ copy(overrides = {}) {
+ return new Card({
+ assigned_to: this.assigned_to,
+ board_id: this.board_id,
+ card_type: this.card_type,
+ column_changed_at: this.column_changed_at,
+ column_id: this.column_id,
+ created_at: this.created_at,
+ created_by: this.created_by,
+ id: this.id,
+ inline_onebox_data: this.inline_onebox_data,
+ notes: this.notes,
+ position: this.position,
+ recency_at: this.recency_at,
+ tag_ids: this.tag_ids,
+ tags: this.tags,
+ title: this.title,
+ topic: this.topic,
+ topic_id: this.topic_id,
+ unicode_title: this.unicode_title,
+ updated_at: this.updated_at,
+ ...overrides,
+ });
+ }
+
+ get fancyTitle() {
+ const titleSource =
+ this.card_type === "topic" && this.topic ? this.topic : this;
+ return titleSource.unicode_title || titleSource.title;
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/models/column.js b/plugins/boards/assets/javascripts/discourse/models/column.js
new file mode 100644
index 00000000000..365fbad63d6
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/models/column.js
@@ -0,0 +1,53 @@
+import { tracked } from "@glimmer/tracking";
+import Card from "./card";
+
+export default class Column {
+ static create(args = {}) {
+ if (args instanceof Column) {
+ return args;
+ }
+ return new Column(args);
+ }
+
+ @tracked cards;
+ @tracked color;
+ @tracked default_sort;
+ @tracked icon;
+ @tracked id;
+ @tracked move_to_assigned;
+ @tracked move_to_category_id;
+ @tracked move_to_status;
+ @tracked position;
+ @tracked tag_id;
+ @tracked tag_name;
+ @tracked title;
+ @tracked unicode_title;
+
+ constructor(args = {}) {
+ Object.assign(this, args);
+ this.cards = (args.cards || []).map((card) => Card.create(card));
+ }
+
+ copy(overrides = {}) {
+ return new Column({
+ cards: this.cards,
+ color: this.color,
+ default_sort: this.default_sort,
+ icon: this.icon,
+ id: this.id,
+ move_to_assigned: this.move_to_assigned,
+ move_to_category_id: this.move_to_category_id,
+ move_to_status: this.move_to_status,
+ position: this.position,
+ tag_id: this.tag_id,
+ tag_name: this.tag_name,
+ title: this.title,
+ unicode_title: this.unicode_title,
+ ...overrides,
+ });
+ }
+
+ get fancyTitle() {
+ return this.unicode_title || this.title;
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/routes/boards-board-card.js b/plugins/boards/assets/javascripts/discourse/routes/boards-board-card.js
new file mode 100644
index 00000000000..d51556810eb
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/routes/boards-board-card.js
@@ -0,0 +1,33 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+import Board from "../models/board";
+
+export default class BoardsBoardCardRoute extends DiscourseRoute {
+ @service router;
+
+ titleToken() {
+ return this.controller?.model?.board?.fancyTitle;
+ }
+
+ model(params) {
+ return ajax(`/boards/api/boards/${params.id}.json`).then((data) =>
+ Board.createPayload({
+ ...data,
+ initialCardId: parseInt(params.card_id, 10),
+ })
+ );
+ }
+
+ afterModel(model, transition) {
+ const board = model.board;
+ if (board?.slug && transition.to.params.slug !== board.slug) {
+ this.router.replaceWith(
+ "boardsBoardCard",
+ board.slug,
+ board.id,
+ transition.to.params.card_id
+ );
+ }
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/routes/boards-board-configure.js b/plugins/boards/assets/javascripts/discourse/routes/boards-board-configure.js
new file mode 100644
index 00000000000..15bcbd367dc
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/routes/boards-board-configure.js
@@ -0,0 +1,31 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+import Board from "../models/board";
+
+export default class BoardsBoardConfigureRoute extends DiscourseRoute {
+ @service router;
+
+ titleToken() {
+ return this.controller?.model?.board?.fancyTitle;
+ }
+
+ model(params) {
+ return ajax(`/boards/api/boards/${params.id}.json`).then((data) =>
+ Board.createPayload({ ...data, openBoardSettings: true })
+ );
+ }
+
+ afterModel(model, transition) {
+ const board = model.board;
+
+ if (board && !board.can_manage) {
+ this.router.replaceWith("boardsBoard", board.slug, board.id);
+ return;
+ }
+
+ if (board?.slug && transition.to.params.slug !== board.slug) {
+ this.router.replaceWith("boardsBoardConfigure", board.slug, board.id);
+ }
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/routes/boards-board.js b/plugins/boards/assets/javascripts/discourse/routes/boards-board.js
new file mode 100644
index 00000000000..ea80ede7480
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/routes/boards-board.js
@@ -0,0 +1,40 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+import { sortCardsForColumn } from "../lib/boards-card-ordering";
+import Board from "../models/board";
+
+export default class BoardsBoardRoute extends DiscourseRoute {
+ @service router;
+
+ queryParams = {
+ card: { refreshModel: true },
+ };
+
+ titleToken() {
+ return this.controller?.model?.board?.fancyTitle;
+ }
+
+ model(params, transition) {
+ return ajax(`/boards/api/boards/${params.id}.json`).then((data) =>
+ Board.createPayload({
+ ...data,
+ highlightCardId: parseInt(transition.to.queryParams.card, 10) || null,
+ })
+ );
+ }
+
+ afterModel(model, transition) {
+ const board = model.board;
+ if (board?.slug && transition.to.params.slug !== board.slug) {
+ this.router.replaceWith("boardsBoard", board.slug, board.id, {
+ queryParams: { card: transition.to.queryParams.card },
+ });
+ }
+
+ model.board.columns = model.board.columns.map((col) => {
+ col.cards = sortCardsForColumn(col, col.cards || []);
+ return col;
+ });
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/routes/boards.js b/plugins/boards/assets/javascripts/discourse/routes/boards.js
new file mode 100644
index 00000000000..5578bc743a1
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/routes/boards.js
@@ -0,0 +1,15 @@
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+import { i18n } from "discourse-i18n";
+import Board from "../models/board";
+
+export default class BoardsRoute extends DiscourseRoute {
+ titleToken() {
+ return i18n("boards.manage.title");
+ }
+
+ async model() {
+ const data = await ajax("/boards/api/boards.json");
+ return data.boards.map((board) => Board.create(board));
+ }
+}
diff --git a/plugins/boards/assets/javascripts/discourse/templates/boards-board-card.gjs b/plugins/boards/assets/javascripts/discourse/templates/boards-board-card.gjs
new file mode 100644
index 00000000000..81a3055cc18
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/templates/boards-board-card.gjs
@@ -0,0 +1,13 @@
+import { array } from "@ember/helper";
+import bodyClass from "discourse/helpers/body-class";
+import BoardsBoardViewer from "../components/boards-board-viewer";
+
+export default <template>
+ {{bodyClass "discourse-boards-board"}}
+ {{#each (array @controller.model) as |model|}}
+ <BoardsBoardViewer
+ @model={{model}}
+ @initialCardId={{model.initialCardId}}
+ />
+ {{/each}}
+</template>
diff --git a/plugins/boards/assets/javascripts/discourse/templates/boards-board-configure.gjs b/plugins/boards/assets/javascripts/discourse/templates/boards-board-configure.gjs
new file mode 100644
index 00000000000..73d59223d3e
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/templates/boards-board-configure.gjs
@@ -0,0 +1,13 @@
+import { array } from "@ember/helper";
+import bodyClass from "discourse/helpers/body-class";
+import BoardsBoardViewer from "../components/boards-board-viewer";
+
+export default <template>
+ {{bodyClass "discourse-boards-board"}}
+ {{#each (array @controller.model) as |model|}}
+ <BoardsBoardViewer
+ @model={{model}}
+ @openBoardSettings={{model.openBoardSettings}}
+ />
+ {{/each}}
+</template>
diff --git a/plugins/boards/assets/javascripts/discourse/templates/boards-board.gjs b/plugins/boards/assets/javascripts/discourse/templates/boards-board.gjs
new file mode 100644
index 00000000000..61aee1347fe
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/templates/boards-board.gjs
@@ -0,0 +1,13 @@
+import { array } from "@ember/helper";
+import bodyClass from "discourse/helpers/body-class";
+import BoardsBoardViewer from "../components/boards-board-viewer";
+
+export default <template>
+ {{bodyClass "discourse-boards-board"}}
+ {{#each (array @controller.model) as |model|}}
+ <BoardsBoardViewer
+ @model={{model}}
+ @highlightCardId={{model.highlightCardId}}
+ />
+ {{/each}}
+</template>
diff --git a/plugins/boards/assets/javascripts/discourse/templates/boards.gjs b/plugins/boards/assets/javascripts/discourse/templates/boards.gjs
new file mode 100644
index 00000000000..d90a7ee2a0d
--- /dev/null
+++ b/plugins/boards/assets/javascripts/discourse/templates/boards.gjs
@@ -0,0 +1,8 @@
+import BoardsPage from "../components/boards-page";
+
+export default <template>
+ <BoardsPage
+ @boards={{@controller.model}}
+ @canManageBoards={{@controller.currentUser.can_manage_boards}}
+ />
+</template>
diff --git a/plugins/boards/assets/stylesheets/boards-add-from-topic-menu.scss b/plugins/boards/assets/stylesheets/boards-add-from-topic-menu.scss
new file mode 100644
index 00000000000..1613527770a
--- /dev/null
+++ b/plugins/boards/assets/stylesheets/boards-add-from-topic-menu.scss
@@ -0,0 +1,89 @@
+.discourse-boards-add-from-topic-menu {
+ max-height: 50vh;
+
+ &__board.btn {
+ width: 100%;
+ justify-content: flex-start;
+
+ .d-button-label {
+ flex: 1;
+ text-align: left;
+ }
+ }
+
+ &__empty {
+ padding: var(--space-2) var(--space-3);
+ color: var(--primary-medium);
+ }
+
+ &__skeleton {
+ display: flex;
+ align-items: center;
+ gap: var(--space-4);
+ min-width: 12rem;
+ padding: var(--space-2) var(--space-3);
+ pointer-events: none;
+ }
+
+ &__skeleton-label,
+ &__skeleton-icon {
+ position: relative;
+ overflow: hidden;
+ height: 0.75rem;
+ background: var(--primary-low);
+ border-radius: var(--d-border-radius);
+
+ &::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ transform: translateX(-100%);
+ background: linear-gradient(
+ 90deg,
+ rgb(var(--skeleton-shimmer-rgb), 0) 0,
+ rgb(var(--skeleton-shimmer-rgb), 0.3) 50%,
+ rgb(var(--skeleton-shimmer-rgb), 0.5) 100%
+ );
+
+ @media (prefers-reduced-motion: no-preference) {
+ animation: discourse-boards-add-from-topic-shimmer 1.25s infinite;
+ }
+ }
+ }
+
+ &__skeleton-label {
+ width: 8rem;
+ }
+
+ &__skeleton-icon {
+ width: 0.75rem;
+ margin-left: auto;
+ }
+
+ .dropdown-menu__subheader {
+ text-transform: uppercase;
+ font-size: var(--font-down-2);
+ }
+}
+
+.discourse-boards-add-from-topic-column-menu {
+ .dropdown-menu__subheader {
+ text-transform: uppercase;
+ font-size: var(--font-down-2);
+ }
+
+ &__column.btn {
+ width: 100%;
+ justify-content: flex-start;
+
+ > .d-icon {
+ color: var(--discourse-boards-column-icon-color);
+ }
+ }
+}
+
+@keyframes discourse-boards-add-from-topic-shimmer {
+ 100% {
+ transform: translateX(100%);
+ }
+}
diff --git a/plugins/boards/assets/stylesheets/boards-board.scss b/plugins/boards/assets/stylesheets/boards-board.scss
new file mode 100644
index 00000000000..13cba3331a4
--- /dev/null
+++ b/plugins/boards/assets/stylesheets/boards-board.scss
@@ -0,0 +1,966 @@
+@use "lib/viewport";
+
+html:has(body.discourse-boards-board) {
+ overflow-y: hidden;
+}
+
+body.discourse-boards-board {
+ --d-border-radius-small: calc(var(--d-border-radius) / 2);
+ --discourse-boards-column-header-height: 25px;
+ --discourse-boards-column-card-gap: var(--space-2);
+ --discourse-boards-column-padding: var(--space-2);
+
+ // Keep in sync with the matching JS constants in boards-motion.js.
+ --discourse-boards-card-reorder-duration: 180ms;
+ --discourse-boards-card-motion-easing: cubic-bezier(0.4, 0, 0.2, 1);
+
+ #main-outlet {
+ padding-bottom: 0;
+ }
+
+ --d-max-width: none;
+
+ .powered-by-discourse {
+ display: none;
+ }
+
+ &.has-sidebar-page #main-outlet-wrapper {
+ --d-main-content-gap: var(--space-2);
+ grid-template-columns: var(--d-sidebar-width) minmax(0, 1fr);
+ gap: 0;
+ padding-right: 0;
+
+ @include viewport.until(md) {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ }
+
+ &:not(.has-sidebar-page) #main-outlet-wrapper {
+ --d-max-width: none;
+ grid-template-columns: 0 minmax(0, 1fr);
+
+ @include viewport.until(md) {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ }
+}
+
+.discourse-boards-board-viewer {
+ height: var(--discourse-boards-available-height, 500px);
+ display: flex;
+ flex-direction: column;
+
+ &__title-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+
+ .back-button {
+ justify-content: left;
+ margin: 0;
+ }
+ }
+
+ &__header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ margin-bottom: var(--space-4);
+ z-index: 1;
+ padding-inline: var(--space-4);
+ }
+
+ &__title {
+ font-weight: bold;
+ margin: 0;
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__metadata {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__creator {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+ font-size: var(--font-down-2-rem);
+ color: var(--primary-medium);
+ font-weight: normal;
+
+ .avatar {
+ width: 15px;
+ height: 15px;
+ }
+
+ &:hover {
+ color: var(--primary);
+ }
+ }
+
+ &__creator-username {
+ color: var(--primary-800);
+ font-weight: 600;
+ }
+
+ &__constraint {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-1);
+ font-size: var(--font-down-1);
+
+ .fk-d-tooltip__trigger {
+ display: inline-flex;
+ align-items: center;
+ cursor: pointer;
+ color: var(--primary-medium);
+
+ .d-icon {
+ font-size: var(--font-down-1);
+ }
+ }
+ }
+
+ &__controls {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+
+ &__empty {
+ padding-inline: var(--space-4);
+ flex: 1;
+ min-height: 0;
+ }
+
+ &__empty-column {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ width: 16.5rem;
+ height: 50%;
+ padding: 2em 1em;
+ border: 1px dashed var(--primary-300);
+ border-radius: var(--d-border-radius);
+ background: var(--primary-50);
+ text-align: center;
+
+ > .d-icon {
+ font-size: 2em;
+ color: var(--primary-medium);
+ margin-bottom: 0.4em;
+ }
+
+ h3 {
+ margin: 0 0 0.25em;
+ font-size: var(--font-0);
+ }
+
+ p {
+ color: var(--primary-medium);
+ margin: 0 0 1em;
+ font-size: var(--font-down-1);
+ }
+ }
+
+ &.discourse-boards-board-viewer--fullscreen {
+ position: fixed;
+ inset: 0;
+ z-index: z("fullscreen");
+ background: var(--secondary);
+ height: 100%;
+ padding: 10px 0;
+ overflow-x: auto;
+ }
+}
+
+body.discourse-boards-fullscreen .fk-d-menu[data-identifier^="boards-"] {
+ z-index: z("fullscreen") + 1;
+}
+
+.discourse-boards-board-container {
+ display: flex;
+ align-items: flex-start;
+ gap: 0 var(--space-2);
+ flex: 1;
+ min-height: 0;
+ padding-inline: var(--space-4);
+ max-width: 100%;
+ overflow-x: auto;
+ overflow-y: hidden;
+
+ &.discourse-boards-board-container--drag-scrolling {
+ cursor: grabbing;
+ user-select: none;
+
+ * {
+ pointer-events: none;
+ }
+ }
+
+ &__add-column {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 2.5rem;
+ border: 1px dashed var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: transparent;
+ color: var(--primary-low-mid);
+ cursor: pointer;
+ opacity: 0;
+ transition:
+ opacity 0.15s ease,
+ border-color 0.15s ease,
+ color 0.15s ease;
+
+ .d-icon {
+ font-size: var(--font-up-1);
+ }
+
+ &:hover {
+ opacity: 1;
+ border-color: var(--primary-300);
+ color: var(--primary-high);
+ background: var(--primary-50);
+ }
+ }
+
+ &:hover &__add-column {
+ opacity: 0.5;
+ }
+}
+
+.discourse-boards-column {
+ width: 16.5rem;
+ max-height: calc(100% - var(--space-8));
+ flex-shrink: 0;
+ background: light-dark(
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h /
+ 0.125
+ ),
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h / 0.05
+ )
+ );
+ display: flex;
+ flex-direction: column;
+ transition: border-color 0.15s ease;
+ border-radius: var(--d-border-radius);
+ border: 1px solid
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h /
+ 0.125
+ );
+
+ &.discourse-boards-column--drag-target {
+ border-color: var(--discourse-boards-column-color);
+ }
+
+ &__header {
+ display: flex;
+ align-items: center;
+ height: var(--discourse-boards-column-header-height);
+ justify-content: space-between;
+ border-top-right-radius: var(--d-border-radius-small);
+ border-top-left-radius: var(--d-border-radius-small);
+ color: var(--primary);
+ padding: var(--space-2);
+ }
+
+ &__header-content {
+ display: flex;
+ gap: var(--space-2);
+ align-items: center;
+ }
+
+ &__title {
+ text-transform: uppercase;
+ font-size: var(--font-down-2);
+ font-weight: 500;
+ padding: var(--space-1) var(--space-2);
+ background: var(--discourse-boards-column-color, var(--primary-500));
+ border-radius: var(--d-border-radius);
+ max-width: 25ch;
+
+ @include ellipsis;
+
+ .d-icon {
+ margin-right: 0.25em;
+ }
+ }
+
+ &__count {
+ font-size: var(--font-down-1);
+ }
+
+ // Header text (count included) and the menu icon keep the fill's hue, but
+ // they sit on the column body β€” a faint tint of the fill over the page
+ // background β€” so their lightness is capped against the scheme, not the
+ // fill: darkened on light schemes, lightened on dark.
+ --discourse-boards-column-header-tint: light-dark(
+ oklch(from var(--discourse-boards-column-color) min(l, 0.5) c h),
+ oklch(from var(--discourse-boards-column-color) max(l, 0.75) c h)
+ );
+
+ &.discourse-boards-column--has-color &__count {
+ color: var(--discourse-boards-column-header-tint);
+ }
+
+ // The title's chip darkens the fill, so it uses its own contrast color.
+ &__title {
+ color: var(--discourse-boards-column-title-text-color);
+ }
+
+ &__menu-trigger {
+ --d-button-flat-bg-color: transparent;
+ --d-button-flat-icon-color: var(--discourse-boards-column-header-tint);
+ --d-button-flat-bg-color--hover: transparent;
+ --d-button-flat-icon-color--hover: var(--primary);
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ padding: 2px 4px;
+ }
+
+ &:hover &__menu-trigger,
+ &__menu-trigger[aria-expanded="true"] {
+ opacity: 1;
+ }
+
+ &__cards {
+ display: flex;
+ flex-direction: column;
+ overflow-y: auto;
+ flex: 1;
+ min-height: 0;
+ gap: var(--discourse-boards-column-card-gap);
+ -webkit-overflow-scrolling: touch;
+ transform: translate3d(0, 0, 0);
+ scrollbar-width: thin;
+ scrollbar-color: oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h/0.5
+ )
+ transparent;
+ padding: var(--discourse-boards-column-padding);
+ }
+
+ &__drop-indicator {
+ flex-shrink: 0;
+ border: 1px solid var(--discourse-boards-column-color, var(--primary-500));
+ border-radius: var(--d-border-radius);
+ background: oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h/0.25
+ );
+ box-sizing: border-box;
+ opacity: 0.9;
+ transition:
+ opacity var(--discourse-boards-card-reorder-duration)
+ var(--discourse-boards-card-motion-easing),
+ box-shadow var(--discourse-boards-card-reorder-duration)
+ var(--discourse-boards-card-motion-easing);
+ }
+
+ &__drop-indicator--source {
+ border-color: transparent;
+ background: transparent;
+ box-shadow: none;
+ opacity: 0;
+ transition: none;
+ }
+
+ &__empty {
+ width: 100%;
+ text-align: center;
+ margin-top: var(--space-12);
+ min-height: 4rem;
+ color: var(--discourse-boards-column-header-tint);
+ }
+
+ &__show-all {
+ align-self: center;
+ border: 0;
+ background: transparent;
+ color: var(--tertiary);
+ cursor: pointer;
+ font-size: var(--font-down-1);
+ padding: var(--space-2);
+
+ &:hover,
+ &:focus {
+ color: var(--tertiary-hover);
+ text-decoration: underline;
+ }
+ }
+
+ &__add-btn {
+ --d-button-default-text-color: var(--discourse-boards-column-header-tint);
+ --d-button-default-icon-color: var(--discourse-boards-column-header-tint);
+ --d-button-default-bg-color: transparent;
+ --d-button-default-bg-color--hover: var(
+ --discourse-boards-column-color,
+ var(--primary-500)
+ );
+ --d-button-default-text-color--hover: var(
+ --discourse-boards-column-title-text-color
+ );
+ --d-button-default-icon-color--hover: var(
+ --discourse-boards-column-title-text-color
+ );
+ --d-button-default-border--hover: 1px solid transparent;
+ width: 100%;
+ justify-content: flex-start;
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+ }
+
+ &__add-card-form {
+ .choose-topic {
+ label span {
+ font-weight: bold;
+ font-size: $font-down-1;
+ }
+
+ input[type="text"] {
+ width: 100%;
+ margin: var(--space-2) 0;
+ }
+
+ .choose-topic__search-results {
+ max-height: 200px;
+ overflow-y: auto;
+ }
+
+ .choose-topic-list .controls {
+ padding: var(--space-2) 0;
+
+ label {
+ display: flex;
+ align-items: baseline;
+ gap: var(--space-2);
+ cursor: pointer;
+
+ .topic-title {
+ font-size: var(--font-down-1);
+ }
+ }
+ }
+ }
+ }
+
+ &__card-title-input {
+ width: 100%;
+ min-height: 60px;
+ resize: vertical;
+ margin-bottom: var(--space-2);
+ border-radius: var(--d-border-radius);
+ }
+
+ &__add-card-actions {
+ display: flex;
+ gap: var(--space-2);
+ align-items: center;
+
+ .discourse-boards-column__cancel-add {
+ margin-left: auto;
+ }
+ }
+
+ &__footer {
+ padding: var(--space-2);
+ }
+}
+
+.discourse-boards-card {
+ display: block;
+ position: relative;
+ color: var(--primary);
+ background: light-dark(
+ var(--secondary),
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h /
+ 0.125
+ )
+ );
+ border: 1px solid
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h/0.25
+ );
+ padding: var(--space-2);
+ border-radius: var(--d-border-radius-small);
+ cursor: grab;
+
+ &--floater {
+ border-left: 2px solid var(--discourse-boards-column-color);
+ }
+
+ &[draggable="false"] {
+ cursor: default;
+ }
+
+ &--dragging {
+ position: absolute;
+ max-height: 0;
+ min-height: 0;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ overflow: hidden;
+ background: transparent;
+ box-shadow: none;
+ pointer-events: none;
+
+ > * {
+ visibility: hidden;
+ }
+ }
+
+ &--drop-highlighted {
+ animation: discourse-boards-card-drop-highlight 1.5s ease-in-out;
+ }
+
+ &--link-highlighted {
+ border: 1px solid var(--discourse-boards-column-color, var(--primary-500));
+ box-shadow: 0 0 0 3px
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h /
+ 0.25
+ );
+ animation: discourse-boards-card-link-highlight-pulse 3s ease-in-out
+ forwards;
+ }
+
+ &--kb-selected {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ background: var(--tertiary-very-low);
+ }
+
+ &__row {
+ display: flex;
+ align-items: baseline;
+
+ * {
+ flex-grow: 0;
+ }
+ }
+
+ &__title-row {
+ .topic-statuses {
+ flex-shrink: 0;
+ }
+
+ .relative-date {
+ font-size: var(--font-down-2);
+ }
+ }
+
+ &__actions-trigger {
+ flex-shrink: 0;
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ padding: var(--space-1) var(--space-2);
+ margin-left: auto;
+ }
+
+ &:hover &__actions-trigger,
+ &__actions-trigger[aria-expanded="true"] {
+ opacity: 1;
+ }
+
+ &__title {
+ flex-grow: 1;
+ overflow-wrap: break-word;
+ overflow: hidden;
+ color: var(--primary);
+ font-weight: 500;
+ line-height: 1.2;
+ }
+
+ &__date {
+ flex-shrink: 0;
+ margin-left: 5px;
+ }
+
+ &__tags {
+ font-size: $font-down-1;
+ }
+
+ &__category {
+ flex-grow: 1;
+ }
+
+ &__assignments {
+ text-align: right;
+ }
+
+ &__assigned-to {
+ margin-top: auto;
+ margin-bottom: auto;
+ font-size: $font-down-1;
+
+ a {
+ color: var(--primary-medium);
+ }
+
+ .d-icon {
+ margin-right: 0.15em;
+ }
+ }
+
+ &__detail-row {
+ min-height: 24px;
+ align-items: center;
+ margin-top: 5px;
+ display: flex;
+ flex-direction: row;
+ }
+
+ &__last-post-by {
+ flex-grow: 1;
+ text-align: left;
+ font-size: $font-down-2;
+ color: var(--primary-medium);
+ overflow-wrap: break-word;
+ overflow: hidden;
+ }
+
+ &__assign-btn {
+ display: block;
+ margin-left: auto;
+ }
+
+ &__assign-btn .avatar {
+ width: 18px;
+ height: 18px;
+ }
+
+ &__assign-btn .avatar + .avatar {
+ margin-left: calc(var(--space-half) * -1);
+ outline: 2px solid var(--secondary);
+ }
+
+ &__meta-data {
+ display: flex;
+ flex-direction: column;
+ }
+
+ &__row-item {
+ display: flex;
+ width: 100%;
+ align-items: center;
+ }
+
+ &__assign-btn:hover .avatar + .avatar {
+ outline-color: var(--d-button-flat-bg-color--hover);
+ }
+
+ &__thumbnail-row {
+ margin-top: 5px;
+ }
+
+ &__thumbnail {
+ overflow: hidden;
+ width: 100%;
+ }
+
+ &__indicators {
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-top: 6px;
+ }
+
+ &__label {
+ display: inline-block;
+ padding: 1px 6px;
+ background: var(--primary-very-low);
+ border-radius: var(--d-border-radius);
+ font-size: $font-down-2;
+ color: var(--primary-high);
+ }
+}
+
+.onebox .discourse-boards-card {
+ &__title {
+ font-size: var(--font-up-1);
+ font-weight: 700;
+ }
+
+ &__row {
+ align-items: center;
+ gap: var(--space-2);
+ margin-bottom: var(--space-2);
+ }
+
+ &__row .discourse-boards-board-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3em;
+ padding: 0.15em 0.5em;
+ background: var(--primary-very-low);
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-2);
+ color: var(--primary-high);
+
+ &:hover {
+ background: var(--primary-low);
+ }
+ }
+}
+
+.discourse-boards-card--drag-image {
+ position: fixed;
+ box-sizing: border-box;
+ top: -9999px;
+ left: -9999px;
+ margin: 0;
+ pointer-events: none;
+ box-shadow: var(--shadow-card);
+ cursor: grabbing;
+}
+
+@keyframes discourse-boards-card-drop-highlight {
+ 0% {
+ border-color: var(--discourse-boards-column-color, var(--primary-500));
+ }
+
+ 100% {
+ border-color: oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h/0.25
+ );
+ }
+}
+
+@keyframes discourse-boards-card-link-highlight-pulse {
+ 0% {
+ box-shadow: 0 0 0 2px
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h /
+ 0.25
+ );
+ }
+
+ 50% {
+ border-color: var(--discourse-boards-column-color, var(--primary-500));
+ box-shadow: 0 0 0 4px
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h /
+ 0.25
+ );
+ }
+
+ 100% {
+ border-color: oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h / 0.25
+ );
+ box-shadow: 0 0 0 4px
+ oklch(
+ from var(--discourse-boards-column-color, var(--primary-500)) l c h / 0
+ );
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .discourse-boards-card--drop-highlighted {
+ animation: none;
+ border-color: var(--tertiary);
+ }
+
+ .discourse-boards-card--link-highlighted {
+ animation: none;
+ }
+
+ .discourse-boards-column__drop-indicator {
+ transition: none;
+ }
+}
+
+.discourse-boards-card-detail-modal {
+ .discourse-boards-card-detail__field {
+ margin-bottom: 1em;
+
+ label {
+ display: block;
+ font-weight: 600;
+ font-size: $font-down-1;
+ margin-bottom: 0.25em;
+ }
+
+ input[type="text"],
+ textarea {
+ width: 100%;
+ margin: 0;
+ }
+
+ textarea {
+ min-height: 80px;
+ resize: vertical;
+ }
+ }
+}
+
+.discourse-boards-topic-card-detail-modal {
+ .d-modal__container {
+ max-width: 720px;
+ width: 90vw;
+ }
+
+ .discourse-boards-topic-card-detail__meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5em;
+ margin-bottom: 1em;
+ padding-bottom: 0.75em;
+ border-bottom: 1px solid var(--primary-low);
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+
+ .badge-category__wrapper {
+ font-size: inherit;
+
+ &:focus-visible {
+ outline: none;
+ }
+ }
+ }
+
+ .discourse-boards-topic-card-detail__cooked .cooked {
+ img:not(.emoji) {
+ max-width: 100%;
+ height: auto;
+ }
+ }
+
+ .discourse-boards-topic-card-detail__stats {
+ display: flex;
+ align-items: center;
+ gap: 0.35em;
+ margin-top: 1em;
+ padding-top: 0.75em;
+ border-top: 1px solid var(--primary-low);
+ color: var(--primary-medium);
+ font-size: $font-down-1;
+
+ .d-icon {
+ font-size: $font-down-1;
+ }
+ }
+
+ .discourse-boards-topic-card-detail__separator {
+ margin: 0 0.1em;
+ }
+
+ .discourse-boards-topic-card-detail__assigned {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35em;
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+
+ .discourse-boards-topic-card-detail__username {
+ font-weight: 600;
+ color: var(--primary-medium);
+ }
+
+ .discourse-boards-topic-card-detail__error {
+ padding: 1em;
+ text-align: center;
+ color: var(--primary-medium);
+ }
+}
+
+.discourse-boards-card__title--topic {
+ cursor: pointer;
+}
+
+.select-kit.multi-select.form-kit__control-tag-chooser {
+ width: 100%;
+}
+
+.d-modal.discourse-boards-add-topic-as-card-modal {
+ .insert-link {
+ overflow-y: visible;
+
+ input {
+ min-width: 300px;
+ }
+
+ .inputs {
+ position: relative;
+
+ .spinner {
+ position: absolute;
+ right: 8px;
+ top: -15px;
+ width: 10px;
+ height: 10px;
+ }
+
+ .internal-link-results {
+ position: absolute;
+ top: 4rem;
+ padding: 5px 10px;
+ box-shadow: var(--shadow-card);
+ z-index: 5;
+ background-color: var(--secondary);
+ max-height: 10rem;
+ width: 90%;
+ overflow-y: auto;
+
+ > .search-link {
+ padding: 6px;
+ border-bottom: 1px solid var(--content-border-color);
+ cursor: pointer;
+ display: block;
+
+ &:hover,
+ &:focus {
+ background-color: var(--highlight-bg);
+ }
+
+ .search-category {
+ display: flex;
+ align-items: center;
+ }
+
+ .discourse-tags {
+ font-size: var(--font-down-1);
+ }
+ }
+ }
+ }
+ }
+}
+
+.discourse-boards-board-settings-modal {
+ .show-advanced {
+ margin-left: auto;
+ margin-right: 0;
+ }
+}
+
+.discourse-boards-column-settings-modal {
+ .show-advanced {
+ margin-left: auto;
+ margin-right: 0;
+ }
+
+ .discourse-boards-column-settings__help {
+ margin-top: 0.35em;
+ margin-bottom: 0;
+ color: var(--primary-medium);
+ font-size: $font-down-2;
+ }
+}
diff --git a/plugins/boards/assets/stylesheets/boards-manage.scss b/plugins/boards/assets/stylesheets/boards-manage.scss
new file mode 100644
index 00000000000..f3638359b06
--- /dev/null
+++ b/plugins/boards/assets/stylesheets/boards-manage.scss
@@ -0,0 +1,297 @@
+.discourse-boards-editable-title {
+ display: flex;
+ align-items: center;
+ box-sizing: border-box;
+ padding: var(--space-2) var(--space-4);
+ border-bottom: 1px solid var(--primary-low);
+ gap: var(--space-1);
+ width: 100%;
+
+ .form-kit__field-custom.--full {
+ width: 100% !important;
+ }
+
+ .form-kit__field-custom .form-kit__control-custom {
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: var(--space-1);
+ min-width: 0;
+ width: 100%;
+
+ > * {
+ width: auto !important;
+ }
+ }
+
+ &__text {
+ height: min-content !important;
+ }
+
+ &__text,
+ &__input {
+ flex: 1;
+ font-size: var(--font-up-1);
+ font-weight: 700;
+ font-family: inherit;
+ padding: var(--space-1) var(--space-2);
+ border: 1px solid transparent;
+ border-radius: var(--d-border-radius);
+ line-height: 1.5;
+ box-sizing: border-box;
+ margin: 0 !important;
+ }
+
+ &__text {
+ cursor: pointer;
+
+ &:hover {
+ background: var(--primary-very-low);
+ }
+
+ &.--empty {
+ color: var(--primary-medium);
+ font-weight: 400;
+ background: var(--primary-very-low);
+ }
+ }
+
+ &__input {
+ outline: none !important;
+ box-shadow: none !important;
+ border-color: var(--tertiary) !important;
+ background: var(--primary-very-low);
+ }
+
+ &__close {
+ flex-shrink: 0;
+ }
+}
+
+.discourse-boards-board-settings-modal,
+.discourse-boards-card-detail-modal,
+.discourse-boards-column-settings-modal {
+ .d-modal__body {
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ min-height: 0;
+
+ .form-kit__errors-summary {
+ width: 95%;
+ max-width: var(--form-kit-max-input);
+ margin: var(--space-4) auto;
+ }
+ }
+
+ .form-kit__section {
+ padding: var(--space-4);
+ width: calc(100% - var(--space-8));
+ }
+
+ .form-kit__actions {
+ border-top: 1px solid var(--content-border-color);
+ }
+
+ .form-kit {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ gap: 0;
+ }
+
+ &__wrapper {
+ flex: 1;
+ width: 100%;
+ overflow-y: auto;
+ }
+}
+
+.discourse-boards-board-settings-modal {
+ .discourse-boards-editable-title {
+ padding-right: var(--space-9);
+ }
+}
+
+.discourse-boards-card-detail-modal {
+ --modal-max-width: 50ch;
+
+ .d-modal__body {
+ position: relative;
+ }
+
+ .discourse-boards-editable-title {
+ padding-right: calc(var(--space-9) + var(--space-2));
+ }
+
+ &__close {
+ position: absolute;
+ top: var(--space-2);
+ right: var(--space-3);
+ z-index: 1;
+ }
+
+ .form-kit__field-textarea .form-kit__container-content,
+ .form-kit__field-composer .form-kit__container-content {
+ width: 100% !important;
+ }
+}
+
+.discourse-boards-column-settings-modal {
+ --modal-max-width: 50ch;
+}
+
+.discourse-boards-manage {
+ .discourse-boards-boards-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 1em;
+ }
+
+ .discourse-boards-boards-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 3em 1em;
+ border: 1px solid var(--content-border-color);
+ border-radius: var(--d-border-radius);
+ text-align: center;
+
+ > .d-icon {
+ font-size: 2.5em;
+ color: var(--primary-medium);
+ margin-bottom: 0.4em;
+ }
+
+ h3 {
+ margin: 0 0 0.25em;
+ }
+
+ p {
+ color: var(--primary-medium);
+ margin: 0 0 1em;
+ }
+ }
+}
+
+.discourse-boards-board-card {
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--content-border-color);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ padding: 1em;
+ transition: box-shadow 0.15s ease;
+
+ &:hover {
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.08);
+ }
+
+ &--kb-selected {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ background: var(--tertiary-very-low);
+ }
+
+ &__header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: var(--space-1);
+ }
+
+ &__name {
+ font-size: var(--font-up-1);
+ font-weight: 700;
+
+ &,
+ &:visited {
+ color: var(--primary);
+ }
+
+ &:hover {
+ color: var(--tertiary);
+ }
+ }
+
+ &__constraints {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.25em;
+ margin-bottom: 0.75em;
+ font-size: var(--font-down-1);
+ }
+
+ &__columns {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.35em;
+ margin-bottom: 0.75em;
+ }
+
+ &__no-columns {
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ &__footer {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.35em;
+ align-items: center;
+ margin-top: auto;
+ padding-top: 0.5em;
+ border-top: 1px solid var(--content-border-color);
+ }
+}
+
+.onebox .discourse-boards-board-card {
+ &__header {
+ margin-bottom: var(--space-2);
+ }
+
+ &__name {
+ color: var(--tertiary);
+ }
+}
+
+.discourse-boards-column-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3em;
+ padding: 0.15em 0.5em;
+ background: var(--primary-very-low);
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-2);
+ color: var(--primary-high);
+
+ .d-icon {
+ font-size: 0.85em;
+ color: var(--primary-medium);
+ }
+}
+
+.discourse-boards-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25em;
+ padding: 0.15em 0.5em;
+ background: var(--tertiary-very-low);
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-2);
+ line-height: var(--line-height-large);
+ min-height: calc(var(--line-height-large) * 1em + 0.3em);
+ color: var(--primary-high);
+
+ &--restricted {
+ justify-content: center;
+ }
+
+ &--restricted .d-icon {
+ color: var(--primary-medium);
+ }
+}
diff --git a/plugins/boards/assets/stylesheets/boards-oneboxes.scss b/plugins/boards/assets/stylesheets/boards-oneboxes.scss
new file mode 100644
index 00000000000..8682bd3057d
--- /dev/null
+++ b/plugins/boards/assets/stylesheets/boards-oneboxes.scss
@@ -0,0 +1,55 @@
+.discourse-boards-onebox.discourse-boards-board-onebox,
+.discourse-boards-onebox.discourse-boards-card-onebox {
+ .discourse-boards-onebox__title {
+ display: flex;
+ flex-direction: column;
+ margin-bottom: var(--space-2);
+
+ .discourse-boards-onebox__type {
+ margin-top: var(--space-1);
+ font-size: var(--font-down-3);
+ font-weight: 400;
+ color: var(--primary-medium);
+ }
+ }
+
+ .discourse-boards-onebox__columns {
+ margin-top: var(--space-2);
+ }
+
+ .discourse-boards-onebox__meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+ align-items: center;
+ margin-top: var(--space-2);
+ }
+
+ .discourse-boards-onebox__card-board-info {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+
+ .discourse-boards-onebox__card-board-link {
+ font-size: var(--font-down-2);
+ }
+ }
+
+ .discourse-boards-onebox__tags,
+ .discourse-boards-onebox__categories,
+ .discourse-boards-onebox__column-title {
+ .hashtag-cooked {
+ color: var(--tag-text-color);
+ font-size: var(--font-down-2);
+ font-weight: 400;
+
+ &:visited {
+ color: var(--tag-text-color);
+ }
+ }
+ }
+
+ .discourse-boards-onebox__notes {
+ margin-top: var(--space-2);
+ }
+}
diff --git a/plugins/boards/assets/stylesheets/boards-topic-pill.scss b/plugins/boards/assets/stylesheets/boards-topic-pill.scss
new file mode 100644
index 00000000000..4b32b4d0829
--- /dev/null
+++ b/plugins/boards/assets/stylesheets/boards-topic-pill.scss
@@ -0,0 +1,82 @@
+.discourse-boards-topic-pill {
+ .d-icon {
+ margin-right: 0.25em;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+
+ .title-wrapper & {
+ vertical-align: center;
+ }
+ }
+
+ &__label::first-letter {
+ text-transform: uppercase;
+ }
+
+ &--multiple {
+ cursor: pointer;
+ }
+}
+
+// Menu listing each board a topic is on, matching core's
+// .notifications-tracking-btn / .composer-actions-btn pattern
+.discourse-boards-boards-menu__item.btn {
+ display: flex;
+ flex: 1 0 auto;
+ box-sizing: border-box;
+ align-items: center;
+
+ .discourse-boards-boards-menu__item-texts {
+ line-height: var(--line-height-medium);
+ flex: 1 1 0%;
+ align-items: flex-start;
+ display: flex;
+ flex-wrap: wrap;
+ flex-direction: column;
+ gap: var(--space-1);
+ }
+
+ .discourse-boards-boards-menu__item-label {
+ flex: 1 1 auto;
+ font-weight: bold;
+ font-size: var(--font-0);
+ color: var(--primary);
+ max-width: 100%;
+
+ @include ellipsis;
+
+ &::first-letter {
+ text-transform: uppercase;
+ }
+ }
+
+ // mirrors the board's column chip (.discourse-boards-column__title),
+ // on its own line below the board name
+ .discourse-boards-boards-menu__column {
+ text-transform: uppercase;
+ font-size: var(--font-down-2);
+ font-weight: 500;
+ padding: var(--space-half) var(--space-1);
+ background: light-dark(
+ oklch(from var(--discourse-boards-column-color) 97% calc(c * 0.3) h),
+ oklch(from var(--discourse-boards-column-color) 45% calc(c * 0.5) h)
+ );
+ border-radius: var(--d-border-radius);
+ color: light-dark(
+ oklch(from var(--discourse-boards-column-color) 20% calc(c * 1) h),
+ oklch(from var(--discourse-boards-column-color) 100% calc(c * 0.9) h)
+ );
+ max-width: 25ch;
+
+ .d-icon {
+ color: currentcolor;
+ font-size: 0.9em;
+ width: auto;
+ }
+ }
+}
+
+.discourse-no-touch .discourse-boards-boards-menu__item.btn:hover,
+.discourse-boards-boards-menu__item.btn:focus-visible {
+ background: var(--d-hover);
+}
diff --git a/plugins/boards/config/locales/client.en.yml b/plugins/boards/config/locales/client.en.yml
new file mode 100644
index 00000000000..6f304f3d7b0
--- /dev/null
+++ b/plugins/boards/config/locales/client.en.yml
@@ -0,0 +1,168 @@
+en:
+ js:
+ boards:
+ filter_boards: "Filter boards"
+ filter_boards_no_results: "No boards match your search"
+ topic_footer:
+ add_to_board: "Add to board"
+ already_added: "Already added"
+ no_boards: "No boards available"
+ topic_pill:
+ title: "This topic is in the %{column} column of the %{board} board"
+ title_multiple_columns:
+ one: "This topic is in %{count} column of the %{board} board"
+ other: "This topic is in %{count} columns of the %{board} board"
+ multiple:
+ one: "%{count} board"
+ other: "%{count} boards"
+ multiple_title: "This topic is on multiple boards"
+ board:
+ added_topic_to_board: "Added topic to '%{boardName}' board in '%{columnName}' column"
+ removed_topic_from_board: "Removed topic from '%{boardName}' board and '%{columnName}' column"
+ empty_board: "This board has no columns yet"
+ empty_board_cta: "Add your first column to get started"
+ no_cards: "No cards in this column"
+ move_confirm: "Move \"%{topic_title}\" to \"%{column_title}\"?"
+ move_failed: "Card could not be moved"
+ add_card: "Add card"
+ add_topic_as_card: "Add topic as card"
+ topic_search_placeholder: "Search topics or paste a topic URL"
+ card_title_placeholder: "Card title or topic URL..."
+ controls: "Board controls"
+ all_boards: "All boards"
+ fullscreen: "Fullscreen"
+ exit_fullscreen: "Exit fullscreen"
+ add_column: "Add column"
+ edit_column: "Edit column"
+ clear_column: "Clear column"
+ confirm_clear_column:
+ one: "Remove %{count} card from \"%{column_title}\"?"
+ other: "Remove %{count} cards from \"%{column_title}\"?"
+ delete_column: "Delete column"
+ move_left: "Move left"
+ move_right: "Move right"
+ column_controls: "Column controls"
+ board_settings: "Board settings"
+ confirm_delete_column: "Are you sure you want to delete this column? All cards in this column will be deleted and cannot be recovered. The underlying topics for topic cards will not be deleted."
+ confirm_delete_column_with_cards: "Are you sure you want to delete this column? All %{count} cards in this column will be deleted and cannot be recovered. The underlying topics for topic cards will not be deleted."
+ column_settings_title: "Column settings"
+ new_column_title: "New column"
+ new_board: "New board"
+ delete_board: "Delete board"
+ remove_card: "Remove"
+ new_topic: "New topic..."
+ card_detail: "Card details"
+ title: "Title"
+ title_placeholder: "Card title..."
+ notes: "Notes"
+ notes_placeholder: "Add notes..."
+ tags: "Tags"
+ assigned_to: "Assigned to"
+ view_topic: "View topic"
+ topic_load_error: "Could not load topic content"
+ topic_reply_count:
+ one: "%{count} reply"
+ other: "%{count} replies"
+ topic_last_reply: "Last by %{username}"
+ assign: "Assign"
+ assign_card: "Assign Card"
+ reassign: "Reassign"
+ unassign: "Unassign"
+ unassign_from_topic: "Unassign @%{username} from topic"
+ unassign_from_post: "Unassign @%{username} from #%{post_number}"
+ unassign_group_from_topic: "Unassign %{group_name} from topic"
+ edit_assignments: "Edit assignments..."
+ constraint_fix_title: "Topic doesn't match board constraints"
+ constraint_fix_description: "This topic needs changes before it can be placed on this board"
+ constraint_fix_category: "Change category to"
+ constraint_fix_tags: "Add a board tag"
+ constraint_fix_confirm: "Move and update"
+ constraint_tooltip: "Only topics with these categories and tags are allowed on this board."
+ created_by: "Created by"
+ show_older_cards: "Show %{count} older cards"
+ errors:
+ acl_update_failed: "Failed to update board permissions."
+ acl_create_failed: "Failed to create board permissions."
+ manage:
+ board: "board"
+ title: "Boards"
+ description: "Create and manage boards with columns."
+ new: "New board"
+ save: "Save board"
+ delete: "Delete board"
+ confirm_delete: "Are you sure you want to delete this board? This cannot be undone."
+ name: "Name"
+ name_placeholder: "Input board title"
+ slug: "Slug"
+ constrain_board_by: "Constrain board by"
+ constraint_categories: "Categories"
+ constraint_tags: "Tags"
+ constraint_categories_and_tags: "Categories and Tags"
+ constraint_help: "Only topics matching one or more of these constraints will be allowed on this board."
+ board_categories_constraint: "Categories constraint"
+ board_tags_constraint: "Tags constraint"
+ advanced_settings: "Advanced settings"
+ card_style_description: "Detailed card style shows more information about the card, such as the last activity date and the last reply for topic cards."
+ card_style: "Card style"
+ card_style_detailed: "Detailed"
+ card_style_simple: "Simple"
+ show_tags: "Show tags"
+ show_topic_thumbnail: "Show topic thumbnail"
+ require_confirmation: "Require confirmation on moves"
+ board_access: "Who can access this board?"
+ board_access_description: "Only groups or users added here can view, manage, or edit this board."
+ board_access_requires_manager: "Select at least one group or user that can manage this board."
+ board_access_permission_manager: "Manager"
+ board_access_permission_manager_description: "Can manage board settings, edit columns, add, remove, and edit cards"
+ board_access_permission_editor_description: "Can add, remove, and edit cards"
+ board_access_permission_viewer_description: "Can read all cards on the board but cannot move or edit them"
+ constraint_warning:
+ one: "Warning: %{count} card will be removed because it no longer matches the board constraints"
+ other: "Warning: %{count} cards will be removed because they no longer match the board constraints"
+ get_started: "No boards yet. Create your first board."
+ no_columns: "No columns configured"
+ empty_title: "No boards yet"
+ restricted_access: "This board has restricted access"
+ column_count:
+ one: "%{count} column"
+ other: "%{count} columns"
+ all_boards: "All boards"
+ view_board: "View board"
+ columns:
+ title: "Columns"
+ column_number: "Column #%{number}"
+ add: "Add column"
+ remove: "Remove"
+ column_title: "Title"
+ column_title_placeholder: "Column title (leave blank to use tag name)..."
+ column_title_required: "Column title or tag name is required"
+ icon: "Icon"
+ color: "Color"
+ default_sort: "Default sort"
+ default_sort_priority: "Priority"
+ default_sort_recency: "Recency"
+ tag: "Tag"
+ tag_help: "Topics with this tag appear in this column. Moving a topic here applies this tag."
+ move_to_category: "Move to category"
+ move_to_assigned: "Move to assigned"
+ move_to_assigned_none: "Don't change"
+ move_to_assigned_unassign: "Unassign"
+ move_to_assigned_user: "Assign to user/group"
+ move_to_status: "Move to status"
+ move_to_status_none: "Don't change"
+ move_to_status_open: "Open"
+ move_to_status_closed: "Closed"
+ show_advanced: "Show advanced options"
+ hide_advanced: "Hide advanced options"
+ keyboard_shortcuts_help:
+ boards:
+ title: "Boards"
+ navigate_boards_columns: "Navigate boards / columns"
+ navigate_cards: "Navigate between cards"
+ move_card_column: "Move selected card to an adjacent column"
+ move_card_position: "Reorder selected card within a manually sorted column"
+ admin_js:
+ admin:
+ site_settings:
+ categories:
+ boards: "Boards"
diff --git a/plugins/boards/config/locales/server.en.yml b/plugins/boards/config/locales/server.en.yml
new file mode 100644
index 00000000000..42665b3db64
--- /dev/null
+++ b/plugins/boards/config/locales/server.en.yml
@@ -0,0 +1,43 @@
+en:
+ site_settings:
+ boards_enabled: "Organize topics, and lightweight standalone β€œfloater” cards, into configurable, drag-and-drop kanban-style boards, all with a purpose-built management UI and per-board access control"
+ boards_manage_board_allowed_groups: "Groups allowed to create and configure boards."
+ access_control_list:
+ errors:
+ "Boards::Board_user_will_lose_permission": "You will lose permissions to manage this board if you make this change. Continue?"
+ "Boards::Board_user_will_lose_permission_on_create": "If you create this board with these permissions, you will not be able to manage it. Continue?"
+ boards:
+ errors:
+ board_not_found: "Board not found"
+ board_read_forbidden: "You do not have permission to view this board"
+ board_write_forbidden: "You do not have permission to modify this board"
+ board_manage_forbidden: "You do not have permission to manage this board"
+ column_not_found: "Column not found"
+ column_move_out_of_bounds: "Column cannot be moved further in that direction"
+ card_not_found: "Card not found"
+ invalid_card_type: "Invalid card type"
+ unknown_group_ids: "Unknown group ids: %{group_ids}"
+ unknown_category_ids: "Unknown category ids: %{category_ids}"
+ unknown_tag_ids: "Unknown tag ids: %{tag_ids}"
+ topic_covered_by_filter: "This is the only card for this topic on the board and it matches the board's filters, so it cannot be removed."
+ category_definition_topic: "Category definition topics cannot be added to a board."
+ topic_already_in_column: "This topic already has a card in that column."
+ invalid_assignee: "Could not find user or group named '%{name}'."
+ topic_does_not_match_constraints: "This topic does not match the board's category and tag constraints."
+ unknown_tag_name: "Unknown tag name: '%{tag_name}'"
+ unknown_tag_names: "Unknown tag names: %{tag_names}"
+ cannot_assign: "You do not have permission to assign."
+ assignment_carry_over_failed: "Could not carry the card's assignment to the topic."
+ cannot_use_same_tag_multiple_times: "You cannot use the same tag (%{tag_name}) multiple times for columns in the same board."
+ cannot_reorder_recency_column: "Cards in recency-sorted columns cannot be reordered."
+ invalid_column_sort: "Invalid column sort: %{sort}"
+ onebox:
+ inline_to_card: "Card '%{card_name}' on board '%{board_name}'"
+ inline_to_board: "Board '%{board_name}'"
+ created_by: "Created by %{username}"
+ column_count:
+ one: "%{count} column"
+ other: "%{count} columns"
+ board: "Board"
+ card: "Board card"
+ updated_by: "Updated by %{username}"
diff --git a/plugins/boards/config/routes.rb b/plugins/boards/config/routes.rb
new file mode 100644
index 00000000000..6106985781b
--- /dev/null
+++ b/plugins/boards/config/routes.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+Boards::Engine.routes.draw do
+ namespace :api, defaults: { format: :json } do
+ get "/boards" => "boards#index"
+ get "/boards/available" => "boards#available"
+ get "/boards/:id" => "boards#show"
+ post "/boards" => "boards#create"
+ put "/boards/:id" => "boards#update"
+ delete "/boards/:id" => "boards#destroy"
+ post "/boards/:id/move-column" => "boards#move_column"
+ post "/boards/:id/constraint-preview" => "boards#constraint_preview"
+ put "/boards/:id/check-constraint-mismatches" => "boards#check_constraint_mismatches"
+
+ post "/boards/:board_id/columns" => "columns#create"
+ put "/boards/:board_id/columns/:id" => "columns#update"
+ delete "/boards/:board_id/columns/:id" => "columns#destroy"
+ delete "/boards/:board_id/columns/:column_id/cards" => "cards#clear"
+
+ post "/boards/:board_id/cards" => "cards#create"
+ put "/boards/:board_id/cards/:id" => "cards#update"
+ post "/boards/:board_id/cards/:id/view" => "cards#view"
+ delete "/boards/:board_id/cards/:id" => "cards#destroy"
+
+ post "/boards/:board_id/topic-moves" => "topic_moves#create"
+ end
+
+ get "/" => "boards#respond"
+ get "/:slug/:id/configure" => "boards#respond"
+ get "/:slug/:id/cards/:card_id" => "boards#respond"
+ get "/:slug/:id" => "boards#respond"
+end
+
+Discourse::Application.routes.draw { mount ::Boards::Engine, at: "/boards" }
diff --git a/plugins/boards/config/settings.yml b/plugins/boards/config/settings.yml
new file mode 100644
index 00000000000..c15cc3469a2
--- /dev/null
+++ b/plugins/boards/config/settings.yml
@@ -0,0 +1,20 @@
+boards:
+ boards_enabled:
+ default: false
+ client: true
+ hidden: true
+ upcoming_change:
+ status: "experimental"
+ impact: "feature,all_members"
+ allow_enabled_for:
+ - "everyone"
+ learn_more_url: "https://meta.discourse.org/t/-/411418"
+ requires_plugin_enabled: false
+ permanent_warning: false
+ boards_manage_board_allowed_groups:
+ type: group_list
+ list_type: compact
+ default: "1|2" # admins and moderators by default
+ allow_any: false
+ client: true
+ mandatory_values: "1" # auto group admins
diff --git a/plugins/boards/db/migrate/20260218044500_create_discourse_kanban_tables.rb b/plugins/boards/db/migrate/20260218044500_create_discourse_kanban_tables.rb
new file mode 100644
index 00000000000..33b9dac7a74
--- /dev/null
+++ b/plugins/boards/db/migrate/20260218044500_create_discourse_kanban_tables.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+class CreateDiscourseKanbanTables < ActiveRecord::Migration[7.2]
+ def change
+ create_table :discourse_kanban_boards do |t|
+ t.string :name, null: false
+ t.string :slug, null: false
+ t.text :base_filter_query
+
+ t.integer :allow_read_group_ids, array: true, null: false, default: []
+ t.integer :allow_write_group_ids, array: true, null: false, default: []
+
+ t.boolean :require_confirmation, null: false, default: true
+ t.boolean :show_tags, null: false, default: false
+ t.integer :card_style, null: false, default: 0
+ t.boolean :show_topic_thumbnail, null: false, default: false
+ t.boolean :show_activity_indicators, null: false, default: false
+
+ t.bigint :created_by_id
+ t.bigint :updated_by_id
+
+ t.timestamps
+ end
+
+ add_index :discourse_kanban_boards, :slug, unique: true
+ add_index :discourse_kanban_boards, :created_by_id
+
+ create_table :discourse_kanban_columns do |t|
+ t.references :board,
+ null: false,
+ foreign_key: {
+ to_table: :discourse_kanban_boards,
+ on_delete: :cascade,
+ },
+ index: {
+ name: "idx_kanban_columns_board_id",
+ }
+
+ t.string :title, null: false
+ t.string :icon
+ t.integer :position, null: false, default: 0
+
+ t.text :filter_query
+ t.string :move_to_tag
+ t.bigint :move_to_category_id
+ t.string :move_to_assigned
+ t.string :move_to_status
+
+ t.timestamps
+ end
+
+ add_index :discourse_kanban_columns,
+ %i[board_id position],
+ name: "idx_kanban_columns_board_position"
+ add_foreign_key :discourse_kanban_columns,
+ :categories,
+ column: :move_to_category_id,
+ on_delete: :nullify
+
+ create_table :discourse_kanban_cards do |t|
+ t.references :board,
+ null: false,
+ foreign_key: {
+ to_table: :discourse_kanban_boards,
+ on_delete: :cascade,
+ },
+ index: {
+ name: "idx_kanban_cards_board_id",
+ }
+
+ t.references :column,
+ null: true,
+ foreign_key: {
+ to_table: :discourse_kanban_columns,
+ on_delete: :nullify,
+ },
+ index: {
+ name: "idx_kanban_cards_column_id",
+ }
+
+ t.references :topic,
+ null: true,
+ foreign_key: {
+ to_table: :topics,
+ on_delete: :cascade,
+ },
+ index: {
+ name: "idx_kanban_cards_topic_id",
+ }
+
+ t.integer :card_type, null: false, default: 0
+ t.integer :membership_mode, null: false, default: 1
+
+ t.string :title
+ t.text :notes
+ t.text :labels, array: true, null: false, default: []
+ t.datetime :due_at
+
+ t.integer :position, null: false, default: 0
+
+ t.bigint :created_by_id
+ t.bigint :updated_by_id
+
+ t.timestamps
+ end
+
+ add_index :discourse_kanban_cards,
+ %i[board_id column_id position],
+ name: "idx_kanban_cards_board_column_position"
+
+ execute <<~SQL
+ CREATE UNIQUE INDEX idx_kanban_cards_unique_topic_per_board
+ ON discourse_kanban_cards (board_id, topic_id)
+ WHERE topic_id IS NOT NULL
+ SQL
+ end
+end
diff --git a/plugins/boards/db/migrate/20260226020000_allow_topic_in_multiple_columns.rb b/plugins/boards/db/migrate/20260226020000_allow_topic_in_multiple_columns.rb
new file mode 100644
index 00000000000..7308196d676
--- /dev/null
+++ b/plugins/boards/db/migrate/20260226020000_allow_topic_in_multiple_columns.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+class AllowTopicInMultipleColumns < ActiveRecord::Migration[7.2]
+ def up
+ remove_index :discourse_kanban_cards, name: :idx_kanban_cards_unique_topic_per_board
+
+ execute <<~SQL
+ CREATE UNIQUE INDEX idx_kanban_cards_unique_topic_per_column
+ ON discourse_kanban_cards (board_id, column_id, topic_id)
+ WHERE topic_id IS NOT NULL AND column_id IS NOT NULL
+ SQL
+ end
+
+ def down
+ remove_index :discourse_kanban_cards, name: :idx_kanban_cards_unique_topic_per_column
+
+ # De-duplicate: keep the best card per (board_id, topic_id).
+ # Priority: manual_in (visible) > auto (visible) > manual_out (hidden),
+ # then prefer cards with a column, then lowest id as tiebreaker.
+ execute <<~SQL
+ DELETE FROM discourse_kanban_cards
+ WHERE topic_id IS NOT NULL
+ AND id NOT IN (
+ SELECT DISTINCT ON (board_id, topic_id) id
+ FROM discourse_kanban_cards
+ WHERE topic_id IS NOT NULL
+ ORDER BY board_id, topic_id,
+ CASE membership_mode
+ WHEN 1 THEN 0
+ WHEN 0 THEN 1
+ WHEN 2 THEN 2
+ ELSE 3
+ END,
+ (column_id IS NULL)::int,
+ id
+ )
+ SQL
+
+ execute <<~SQL
+ CREATE UNIQUE INDEX idx_kanban_cards_unique_topic_per_board
+ ON discourse_kanban_cards (board_id, topic_id)
+ WHERE topic_id IS NOT NULL
+ SQL
+ end
+end
diff --git a/plugins/boards/db/migrate/20260226060000_add_wip_limit_to_kanban_columns.rb b/plugins/boards/db/migrate/20260226060000_add_wip_limit_to_kanban_columns.rb
new file mode 100644
index 00000000000..c4eae4da8a2
--- /dev/null
+++ b/plugins/boards/db/migrate/20260226060000_add_wip_limit_to_kanban_columns.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddWipLimitToKanbanColumns < ActiveRecord::Migration[7.2]
+ def change
+ add_column :discourse_kanban_columns, :wip_limit, :integer, null: true
+ end
+end
diff --git a/plugins/boards/db/migrate/20260227010000_change_kanban_card_position_to_bigint.rb b/plugins/boards/db/migrate/20260227010000_change_kanban_card_position_to_bigint.rb
new file mode 100644
index 00000000000..d340eca7bca
--- /dev/null
+++ b/plugins/boards/db/migrate/20260227010000_change_kanban_card_position_to_bigint.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class ChangeKanbanCardPositionToBigint < ActiveRecord::Migration[7.2]
+ def up
+ change_column :discourse_kanban_cards, :position, :bigint, null: false, default: 0
+ end
+
+ def down
+ change_column :discourse_kanban_cards, :position, :integer, null: false, default: 0
+ end
+end
diff --git a/plugins/boards/db/migrate/20260303033335_add_assigned_to_to_kanban_cards.rb b/plugins/boards/db/migrate/20260303033335_add_assigned_to_to_kanban_cards.rb
new file mode 100644
index 00000000000..2643942df74
--- /dev/null
+++ b/plugins/boards/db/migrate/20260303033335_add_assigned_to_to_kanban_cards.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+class AddAssignedToToKanbanCards < ActiveRecord::Migration[7.2]
+ def change
+ add_column :discourse_kanban_cards, :assigned_to_id, :bigint, null: true
+ add_column :discourse_kanban_cards, :assigned_to_type, :string, null: true
+
+ add_index :discourse_kanban_cards,
+ %i[assigned_to_type assigned_to_id],
+ name: "idx_kanban_cards_assigned_to"
+ end
+end
diff --git a/plugins/boards/db/migrate/20260402052139_simplify_kanban_filters.rb b/plugins/boards/db/migrate/20260402052139_simplify_kanban_filters.rb
new file mode 100644
index 00000000000..d3bef454dd9
--- /dev/null
+++ b/plugins/boards/db/migrate/20260402052139_simplify_kanban_filters.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+class SimplifyKanbanFilters < ActiveRecord::Migration[8.0]
+ def up
+ add_column :discourse_kanban_boards,
+ :category_ids,
+ :integer,
+ array: true,
+ null: false,
+ default: []
+ add_column :discourse_kanban_boards, :tag_ids, :integer, array: true, null: false, default: []
+ add_column :discourse_kanban_columns, :tag_id, :integer, null: true
+
+ # Best-effort data migration: parse base_filter_query for simple category:/tags: patterns
+ execute <<~SQL
+ UPDATE discourse_kanban_boards
+ SET category_ids = COALESCE((
+ SELECT array_agg(c.id)
+ FROM categories c
+ JOIN LATERAL regexp_matches(base_filter_query, 'category:([^\s]+)', 'g') AS m(captures) ON TRUE
+ WHERE c.slug = m.captures[1]
+ ), '{}'),
+ tag_ids = COALESCE((
+ SELECT array_agg(t.id)
+ FROM tags t
+ JOIN LATERAL regexp_matches(base_filter_query, 'tags:([^\s]+)', 'g') AS m(captures) ON TRUE
+ WHERE t.name = m.captures[1]
+ ), '{}')
+ WHERE base_filter_query IS NOT NULL AND base_filter_query != ''
+ SQL
+
+ # Migrate column move_to_tag β†’ tag_id
+ execute <<~SQL
+ UPDATE discourse_kanban_columns
+ SET tag_id = t.id
+ FROM tags t
+ WHERE discourse_kanban_columns.move_to_tag IS NOT NULL
+ AND discourse_kanban_columns.move_to_tag != ''
+ AND t.name = discourse_kanban_columns.move_to_tag
+ SQL
+ end
+
+ def down
+ remove_column :discourse_kanban_boards, :category_ids
+ remove_column :discourse_kanban_boards, :tag_ids
+ remove_column :discourse_kanban_columns, :tag_id
+ end
+end
diff --git a/plugins/boards/db/migrate/20260407065612_add_kanban_sync_indexes.rb b/plugins/boards/db/migrate/20260407065612_add_kanban_sync_indexes.rb
new file mode 100644
index 00000000000..ddf17c00531
--- /dev/null
+++ b/plugins/boards/db/migrate/20260407065612_add_kanban_sync_indexes.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+class AddKanbanSyncIndexes < ActiveRecord::Migration[8.0]
+ def change
+ add_index :discourse_kanban_boards,
+ :category_ids,
+ using: :gin,
+ name: "idx_kanban_boards_category_ids"
+ add_index :discourse_kanban_boards, :tag_ids, using: :gin, name: "idx_kanban_boards_tag_ids"
+ add_index :discourse_kanban_columns, :tag_id, name: "idx_kanban_columns_tag_id"
+ end
+end
diff --git a/plugins/boards/db/migrate/20260410040217_add_tag_ids_to_kanban_cards.rb b/plugins/boards/db/migrate/20260410040217_add_tag_ids_to_kanban_cards.rb
new file mode 100644
index 00000000000..5489ef69c35
--- /dev/null
+++ b/plugins/boards/db/migrate/20260410040217_add_tag_ids_to_kanban_cards.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+class AddTagIdsToKanbanCards < ActiveRecord::Migration[8.0]
+ def up
+ add_column :discourse_kanban_cards, :tag_ids, :integer, array: true, null: false, default: []
+
+ execute <<~SQL
+ WITH normalized_labels AS (
+ SELECT DISTINCT ON (lower(trim(label)))
+ trim(label) AS name,
+ lower(trim(label)) AS lower_name
+ FROM discourse_kanban_cards
+ CROSS JOIN LATERAL unnest(labels) AS labels(label)
+ WHERE trim(COALESCE(label, '')) <> ''
+ ORDER BY lower(trim(label)), trim(label)
+ )
+ INSERT INTO tags (name, slug, created_at, updated_at)
+ SELECT normalized_labels.name, '', NOW(), NOW()
+ FROM normalized_labels
+ LEFT JOIN tags ON lower(tags.name) = normalized_labels.lower_name
+ WHERE tags.id IS NULL
+ SQL
+
+ execute <<~SQL
+ WITH normalized_labels AS (
+ SELECT
+ discourse_kanban_cards.id AS card_id,
+ lower(trim(label)) AS lower_name,
+ ord,
+ ROW_NUMBER() OVER (
+ PARTITION BY discourse_kanban_cards.id, lower(trim(label))
+ ORDER BY ord
+ ) AS row_number
+ FROM discourse_kanban_cards
+ CROSS JOIN LATERAL unnest(labels) WITH ORDINALITY AS labels(label, ord)
+ WHERE trim(COALESCE(label, '')) <> ''
+ ),
+ resolved_tag_ids AS (
+ SELECT
+ normalized_labels.card_id,
+ array_agg(tags.id ORDER BY normalized_labels.ord) AS tag_ids
+ FROM normalized_labels
+ INNER JOIN tags ON lower(tags.name) = normalized_labels.lower_name
+ WHERE normalized_labels.row_number = 1
+ GROUP BY normalized_labels.card_id
+ )
+ UPDATE discourse_kanban_cards
+ SET tag_ids = COALESCE(resolved_tag_ids.tag_ids, '{}')
+ FROM resolved_tag_ids
+ WHERE discourse_kanban_cards.id = resolved_tag_ids.card_id
+ SQL
+ end
+
+ def down
+ remove_column :discourse_kanban_cards, :tag_ids
+ end
+end
diff --git a/plugins/boards/db/migrate/20260424060304_add_recency_sort_to_kanban.rb b/plugins/boards/db/migrate/20260424060304_add_recency_sort_to_kanban.rb
new file mode 100644
index 00000000000..1949152db89
--- /dev/null
+++ b/plugins/boards/db/migrate/20260424060304_add_recency_sort_to_kanban.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+class AddRecencySortToKanban < ActiveRecord::Migration[8.0]
+ def up
+ add_column :discourse_kanban_columns, :default_sort, :integer, null: false, default: 0
+ add_column :discourse_kanban_cards, :column_changed_at, :datetime
+
+ execute <<~SQL
+ UPDATE discourse_kanban_cards
+ SET column_changed_at = COALESCE(updated_at, created_at, NOW())
+ WHERE column_changed_at IS NULL
+ SQL
+
+ change_column_null :discourse_kanban_cards, :column_changed_at, false
+ end
+
+ def down
+ remove_column :discourse_kanban_cards, :column_changed_at
+ remove_column :discourse_kanban_columns, :default_sort
+ end
+end
diff --git a/plugins/boards/db/migrate/20260427025159_fix_blank_write_groups_kanban.rb b/plugins/boards/db/migrate/20260427025159_fix_blank_write_groups_kanban.rb
new file mode 100644
index 00000000000..bab066842a1
--- /dev/null
+++ b/plugins/boards/db/migrate/20260427025159_fix_blank_write_groups_kanban.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+class FixBlankWriteGroupsKanban < ActiveRecord::Migration[8.0]
+ def up
+ discourse_kanban_manage_board_allowed_groups =
+ DB.query_single(
+ "SELECT value FROM site_settings WHERE name = 'discourse_kanban_manage_board_allowed_groups'",
+ ).first
+
+ if discourse_kanban_manage_board_allowed_groups.blank?
+ discourse_kanban_manage_board_allowed_groups = "3" # site setting default
+ end
+
+ group_ids = discourse_kanban_manage_board_allowed_groups.split("|").map(&:to_i)
+
+ execute <<~SQL
+ UPDATE discourse_kanban_boards
+ SET allow_write_group_ids = ARRAY[#{group_ids.join(",")}]::integer[]
+ WHERE allow_write_group_ids IS NULL OR allow_write_group_ids = '{}'::integer[]
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/boards/db/migrate/20260429052246_create_kanban_board_histories.rb b/plugins/boards/db/migrate/20260429052246_create_kanban_board_histories.rb
new file mode 100644
index 00000000000..ea522e64a6f
--- /dev/null
+++ b/plugins/boards/db/migrate/20260429052246_create_kanban_board_histories.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+class CreateKanbanBoardHistories < ActiveRecord::Migration[8.0]
+ def change
+ create_table :discourse_kanban_board_histories do |t|
+ t.bigint :acting_user_id, null: false
+ t.integer :action, null: false
+ t.bigint :board_id, null: false
+ t.bigint :column_id
+ t.jsonb :details
+ t.timestamps
+ end
+
+ add_index :discourse_kanban_board_histories, :acting_user_id
+ add_index :discourse_kanban_board_histories, :board_id
+ add_index :discourse_kanban_board_histories, :column_id
+ end
+end
diff --git a/plugins/boards/db/migrate/20260603055342_create_kanban_card_histories.rb b/plugins/boards/db/migrate/20260603055342_create_kanban_card_histories.rb
new file mode 100644
index 00000000000..47d6a56eba1
--- /dev/null
+++ b/plugins/boards/db/migrate/20260603055342_create_kanban_card_histories.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+class CreateKanbanCardHistories < ActiveRecord::Migration[8.0]
+ def change
+ create_table :discourse_kanban_card_histories do |t|
+ t.bigint :acting_user_id, null: false
+ t.integer :action, null: false
+ t.bigint :board_id, null: false
+ t.bigint :card_id, null: false
+ t.jsonb :details
+ t.timestamps
+ end
+
+ add_index :discourse_kanban_card_histories, :acting_user_id
+ add_index :discourse_kanban_card_histories, %i[board_id card_id]
+ add_index :discourse_kanban_card_histories,
+ "board_id, card_id, acting_user_id, (created_at::date)",
+ unique: true,
+ where: "action = 7", # card_viewed
+ name: "index_discourse_kanban_card_histories_one_view_per_user_day"
+ end
+end
diff --git a/plugins/boards/db/migrate/20260605051007_add_board_view_unique_index.rb b/plugins/boards/db/migrate/20260605051007_add_board_view_unique_index.rb
new file mode 100644
index 00000000000..f84a615561c
--- /dev/null
+++ b/plugins/boards/db/migrate/20260605051007_add_board_view_unique_index.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+class AddBoardViewUniqueIndex < ActiveRecord::Migration[8.0]
+ def change
+ add_index :discourse_kanban_board_histories,
+ "board_id, acting_user_id, (created_at::date)",
+ unique: true,
+ where: "action = 7", # board_viewed
+ name: "index_discourse_kanban_board_histories_one_view_per_user_day"
+ end
+end
diff --git a/plugins/boards/db/migrate/20260618203643_add_color_to_kanban_columns.rb b/plugins/boards/db/migrate/20260618203643_add_color_to_kanban_columns.rb
new file mode 100644
index 00000000000..0d938c651be
--- /dev/null
+++ b/plugins/boards/db/migrate/20260618203643_add_color_to_kanban_columns.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddColorToKanbanColumns < ActiveRecord::Migration[8.0]
+ def change
+ add_column :discourse_kanban_columns, :color, :string
+ end
+end
diff --git a/plugins/boards/db/migrate/20260623042355_move_board_permissions_to_acls.rb b/plugins/boards/db/migrate/20260623042355_move_board_permissions_to_acls.rb
new file mode 100644
index 00000000000..54e2c478e13
--- /dev/null
+++ b/plugins/boards/db/migrate/20260623042355_move_board_permissions_to_acls.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+class MoveBoardPermissionsToAcls < ActiveRecord::Migration[8.0]
+ def up
+ original_board_permissions = DB.query(<<~SQL)
+ SELECT id, allow_read_group_ids, allow_write_group_ids
+ FROM discourse_kanban_boards
+ SQL
+
+ kanban_manage_group_ids = DB.query_single(<<~SQL).first
+ SELECT value FROM site_settings WHERE name = 'discourse_kanban_manage_board_allowed_groups'
+ SQL
+
+ if kanban_manage_group_ids.blank?
+ kanban_manage_group_ids = [1] # admins only by default/mandatory
+ else
+ kanban_manage_group_ids = (kanban_manage_group_ids.split("|").map(&:to_i) + [1]).uniq # ensure admins are always included
+ end
+
+ target_type = "DiscourseKanban::Board"
+ owner = "discourse-kanban"
+ now = Time.zone.now
+ logged_in_users_group_id = 5 # Group::AUTO_GROUPS[:logged_in_users]
+
+ rows = []
+ original_board_permissions.each do |bp|
+ # Previously empty read groups meant "public", but for this migration we
+ # want to err on the side of caution and grant logged in users only when
+ # none were specified. Board owners can add the anonymous users group back
+ # later if they need to.
+ read_group_ids = bp.allow_read_group_ids.presence || [logged_in_users_group_id]
+ rows << { target_id: bp.id, permission: "view", group_ids: read_group_ids }
+
+ if bp.allow_write_group_ids.present?
+ rows << { target_id: bp.id, permission: "edit", group_ids: bp.allow_write_group_ids }
+ end
+
+ rows << { target_id: bp.id, permission: "manage", group_ids: kanban_manage_group_ids }
+ end
+
+ return if rows.empty?
+
+ DB.exec(
+ <<~SQL,
+ INSERT INTO access_control_lists
+ (target_id, target_type, owner, permission, allowed_group_ids, created_at, updated_at)
+ SELECT t.target_id, :target_type, :owner, t.permission, t.group_ids::bigint[], :now, :now
+ FROM unnest(
+ ARRAY[:target_ids]::bigint[],
+ ARRAY[:permissions]::text[],
+ ARRAY[:group_ids]::text[]
+ ) AS t(target_id, permission, group_ids)
+ ON CONFLICT (target_id, target_type, permission) DO NOTHING
+ SQL
+ target_ids: rows.map { |r| r[:target_id] },
+ permissions: rows.map { |r| r[:permission] },
+ group_ids: rows.map { |r| "{#{r[:group_ids].join(",")}}" },
+ target_type: target_type,
+ owner: owner,
+ now: now,
+ )
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/boards/db/migrate/20260813000000_add_inline_onebox_data_to_kanban_cards.rb b/plugins/boards/db/migrate/20260813000000_add_inline_onebox_data_to_kanban_cards.rb
new file mode 100644
index 00000000000..0f83e464921
--- /dev/null
+++ b/plugins/boards/db/migrate/20260813000000_add_inline_onebox_data_to_kanban_cards.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddInlineOneboxDataToKanbanCards < ActiveRecord::Migration[8.0]
+ def change
+ add_column :discourse_kanban_cards, :inline_onebox_data, :jsonb
+ end
+end
diff --git a/plugins/boards/db/migrate/20260901020329_migrate_discourse_kanban_to_boards.rb b/plugins/boards/db/migrate/20260901020329_migrate_discourse_kanban_to_boards.rb
new file mode 100644
index 00000000000..a7b5be2c405
--- /dev/null
+++ b/plugins/boards/db/migrate/20260901020329_migrate_discourse_kanban_to_boards.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+class MigrateDiscourseKanbanToBoards < ActiveRecord::Migration[8.0]
+ SITE_SETTING_NAMES = {
+ "discourse_kanban_enabled" => "boards_enabled",
+ "discourse_kanban_manage_board_allowed_groups" => "boards_manage_board_allowed_groups",
+ }.freeze
+
+ def up
+ copy_site_settings if Migration::Helpers.existing_site?
+ copy_access_control_lists
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+
+ private
+
+ def copy_site_settings
+ SITE_SETTING_NAMES.each { |old_name, new_name| DB.exec(<<~SQL, old_name:, new_name:) }
+ INSERT INTO site_settings (name, data_type, value, created_at, updated_at)
+ SELECT :new_name, data_type, value, created_at, updated_at
+ FROM site_settings
+ WHERE name = :old_name
+ ON CONFLICT (name) DO NOTHING
+ SQL
+ end
+
+ def copy_access_control_lists
+ execute <<~SQL
+ INSERT INTO access_control_lists (
+ target_type,
+ target_id,
+ owner,
+ permission,
+ allowed_user_ids,
+ allowed_group_ids,
+ created_at,
+ updated_at
+ )
+ SELECT
+ 'Boards::Board',
+ target_id,
+ CASE
+ WHEN owner = 'discourse-kanban' THEN 'boards'
+ ELSE owner
+ END,
+ permission,
+ allowed_user_ids,
+ allowed_group_ids,
+ created_at,
+ updated_at
+ FROM access_control_lists AS legacy_acl
+ WHERE legacy_acl.target_type = 'DiscourseKanban::Board'
+ AND NOT EXISTS (
+ SELECT 1
+ FROM access_control_lists AS boards_acl
+ WHERE boards_acl.target_type = 'Boards::Board'
+ AND boards_acl.target_id = legacy_acl.target_id
+ AND boards_acl.permission = legacy_acl.permission
+ )
+ ON CONFLICT DO NOTHING
+ SQL
+ end
+end
diff --git a/plugins/boards/db/post_migrate/20260304212353_remove_wip_limit_from_kanban_columns.rb b/plugins/boards/db/post_migrate/20260304212353_remove_wip_limit_from_kanban_columns.rb
new file mode 100644
index 00000000000..8c6f95f5857
--- /dev/null
+++ b/plugins/boards/db/post_migrate/20260304212353_remove_wip_limit_from_kanban_columns.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+class RemoveWipLimitFromKanbanColumns < ActiveRecord::Migration[8.0]
+ DROPPED_COLUMNS = { discourse_kanban_columns: %i[wip_limit] }
+
+ def up
+ DROPPED_COLUMNS.each { |table, columns| Migration::ColumnDropper.execute_drop(table, columns) }
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/boards/db/post_migrate/20260402053105_drop_old_kanban_filter_columns.rb b/plugins/boards/db/post_migrate/20260402053105_drop_old_kanban_filter_columns.rb
new file mode 100644
index 00000000000..6e5d42e31f3
--- /dev/null
+++ b/plugins/boards/db/post_migrate/20260402053105_drop_old_kanban_filter_columns.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+class DropOldKanbanFilterColumns < ActiveRecord::Migration[8.0]
+ DROPPED_COLUMNS = {
+ discourse_kanban_boards: %i[base_filter_query],
+ discourse_kanban_columns: %i[filter_query move_to_tag],
+ }
+
+ def up
+ DROPPED_COLUMNS.each { |table, columns| Migration::ColumnDropper.execute_drop(table, columns) }
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/boards/db/post_migrate/20260402064240_drop_kanban_card_membership_mode.rb b/plugins/boards/db/post_migrate/20260402064240_drop_kanban_card_membership_mode.rb
new file mode 100644
index 00000000000..f1ea0f662b6
--- /dev/null
+++ b/plugins/boards/db/post_migrate/20260402064240_drop_kanban_card_membership_mode.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+class DropKanbanCardMembershipMode < ActiveRecord::Migration[8.0]
+ def up
+ # Delete orphaned cards with no column (manual_out markers)
+ execute <<~SQL
+ DELETE FROM discourse_kanban_cards WHERE column_id IS NULL
+ SQL
+
+ # Remove the membership_mode column
+ remove_column :discourse_kanban_cards, :membership_mode
+ end
+
+ def down
+ add_column :discourse_kanban_cards, :membership_mode, :integer, default: 1, null: false
+ end
+end
diff --git a/plugins/boards/db/post_migrate/20260410040858_drop_labels_from_kanban_cards.rb b/plugins/boards/db/post_migrate/20260410040858_drop_labels_from_kanban_cards.rb
new file mode 100644
index 00000000000..4580ff7b05f
--- /dev/null
+++ b/plugins/boards/db/post_migrate/20260410040858_drop_labels_from_kanban_cards.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class DropLabelsFromKanbanCards < ActiveRecord::Migration[8.0]
+ def up
+ Migration::ColumnDropper.execute_drop(:discourse_kanban_cards, %i[labels])
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/boards/db/post_migrate/20260602233501_drop_show_activity_indicators_from_boards.rb b/plugins/boards/db/post_migrate/20260602233501_drop_show_activity_indicators_from_boards.rb
new file mode 100644
index 00000000000..20edd8d8719
--- /dev/null
+++ b/plugins/boards/db/post_migrate/20260602233501_drop_show_activity_indicators_from_boards.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+class DropShowActivityIndicatorsFromBoards < ActiveRecord::Migration[8.0]
+ DROPPED_COLUMNS = { discourse_kanban_boards: %i[show_activity_indicators] }
+
+ def up
+ DROPPED_COLUMNS.each { |table, columns| Migration::ColumnDropper.execute_drop(table, columns) }
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/boards/lib/boards/engine.rb b/plugins/boards/lib/boards/engine.rb
new file mode 100644
index 00000000000..afb48323e09
--- /dev/null
+++ b/plugins/boards/lib/boards/engine.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module ::Boards
+ class Engine < ::Rails::Engine
+ engine_name PLUGIN_NAME
+ isolate_namespace Boards
+ config.autoload_paths << File.join(config.root, "lib")
+ end
+
+ def self.card_onebox_template
+ path = Rails.root.join("plugins/boards/lib/onebox/templates/boards_card.mustache")
+ return File.read(path) if Rails.env.development?
+
+ @card_onebox_template ||= File.read(path)
+ end
+
+ def self.board_onebox_template
+ path = Rails.root.join("plugins/boards/lib/onebox/templates/boards_board.mustache")
+ return File.read(path) if Rails.env.development?
+
+ @board_onebox_template ||= File.read(path)
+ end
+end
diff --git a/plugins/boards/lib/boards/guardian_extensions.rb b/plugins/boards/lib/boards/guardian_extensions.rb
new file mode 100644
index 00000000000..42d570fa59c
--- /dev/null
+++ b/plugins/boards/lib/boards/guardian_extensions.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module Boards
+ module GuardianExtensions
+ def can_manage_boards?
+ in_any_groups?(SiteSetting.boards_manage_board_allowed_groups_map)
+ end
+
+ def can_create_boards_board?
+ can_manage_boards?
+ end
+
+ def can_destroy_boards_board?(board)
+ can_manage_boards? && has_acl_permission?(board, "manage")
+ end
+
+ def can_manage_boards_board?(board)
+ can_manage_boards? && has_acl_permission?(board, "manage")
+ end
+
+ def can_read_boards_board?(board)
+ return true if board.anonymous_can_read?
+ return true if can_write_boards_board?(board)
+
+ has_acl_permission?(board, "view")
+ end
+
+ def can_write_boards_board?(board)
+ has_any_acl_permission?(board, %w[edit manage])
+ end
+
+ def can_view_boards_card?(card)
+ can_read_boards_board?(card.board)
+ end
+ end
+end
diff --git a/plugins/boards/lib/boards/inline_onebox_handler.rb b/plugins/boards/lib/boards/inline_onebox_handler.rb
new file mode 100644
index 00000000000..b3db4e2cf46
--- /dev/null
+++ b/plugins/boards/lib/boards/inline_onebox_handler.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module Boards
+ class InlineOneboxHandler
+ def self.handle(url, route, opts = {})
+ opts ||= {}
+
+ if route[:card_id].present?
+ build_card_onebox(url, route[:card_id], route[:id], opts)
+ else
+ build_board_onebox(url, route[:id])
+ end
+ end
+
+ private
+
+ def self.build_card_onebox(url, card_id, board_id, opts)
+ board = Boards::Board.find_by(id: board_id)
+ return if !board || !board.can_be_oneboxed?
+
+ card = Boards::Card.includes(:topic).find_by(id: card_id, board_id: board_id)
+ return if !card
+ if card.topic?
+ if card.topic.blank? ||
+ Oneboxer.local_topic(card.topic.url, { id: card.topic_id }, opts).blank?
+ return
+ end
+ end
+
+ title =
+ I18n.t(
+ "boards.onebox.inline_to_card",
+ card_name: card.unicode_resolved_title,
+ board_name: board.unicode_name,
+ )
+
+ { url: url, title: title }
+ end
+
+ def self.build_board_onebox(url, board_id)
+ board = Boards::Board.find_by(id: board_id)
+ return if !board || !board.can_be_oneboxed?
+
+ title = I18n.t("boards.onebox.inline_to_board", board_name: board.unicode_name)
+
+ { url: url, title: title }
+ end
+ end
+end
diff --git a/plugins/boards/lib/boards/onebox_handler.rb b/plugins/boards/lib/boards/onebox_handler.rb
new file mode 100644
index 00000000000..62dd38b106b
--- /dev/null
+++ b/plugins/boards/lib/boards/onebox_handler.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+module Boards
+ class OneboxHandler
+ def self.handle(url, route, opts = {})
+ opts ||= {}
+
+ if route[:card_id].present?
+ build_card_onebox(url, route[:card_id], route[:id], opts)
+ else
+ build_board_onebox(url, route[:id])
+ end
+ end
+
+ private
+
+ def self.build_card_onebox(url, card_id, board_id, opts)
+ card = Boards::Card.find_by(id: card_id, board_id: board_id)
+ return "" if !card || !card.board.can_be_oneboxed?
+
+ if card.topic?
+ if card.topic.blank? ||
+ Oneboxer.local_topic(card.topic.url, { id: card.topic_id }, opts).blank?
+ return ""
+ end
+ end
+
+ tag_html = ""
+ if card.tags.any?
+ tag_hashtags = card.tags.map { |tag| "##{tag.name}" }.join("\n")
+ tag_html =
+ Nokogiri::HTML5.fragment(PrettyText.cook(tag_hashtags)).css("a").map(&:to_s).join("\n")
+ end
+
+ updated_at = card.updated_at || card.created_at
+
+ args = {
+ board_url: card.board.url,
+ board_name: card.board.unicode_name,
+ card_url: url,
+ card_name: card.unicode_resolved_title,
+ card_tags: tag_html,
+ card_column_title: card.column.unicode_title,
+ card_column_icon: card.column.icon,
+ creator_username: card.created_by.username,
+ creator_avatar_url: card.created_by.small_avatar_url,
+ updater_username: card.updated_by.username,
+ updater_avatar_url: card.updated_by.small_avatar_url,
+ notes:
+ PrettyText.excerpt(
+ PrettyText.cook(card.notes),
+ SiteSetting.post_onebox_maxlength,
+ keep_svg: true,
+ ),
+ created_by: I18n.t("boards.onebox.created_by", username: card.created_by.display_name),
+ updated_by: I18n.t("boards.onebox.updated_by", username: card.updated_by.display_name),
+ updated_at_ms: (updated_at.to_f * 1000).to_i,
+ updated_at_title: I18n.l(updated_at, format: :long),
+ updated_at_tiny: AgeWords.age_words((Time.now - updated_at).to_i),
+ onebox_type: I18n.t("boards.onebox.card"),
+ tags_preview: card.tags.any?,
+ has_notes: card.notes.present?,
+ }
+
+ Mustache.render(Boards.card_onebox_template, args)
+ end
+
+ def self.build_board_onebox(url, board_id)
+ board = Boards::Board.find_by(id: board_id)
+ return "" if !board || !board.can_be_oneboxed?
+
+ tag_html = ""
+ if board.tags.any?
+ tag_hashtags = board.tags.map { |tag| "##{tag.name}" }.join("\n")
+ tag_html =
+ Nokogiri::HTML5.fragment(PrettyText.cook(tag_hashtags)).css("a").map(&:to_s).join("\n")
+ end
+
+ category_html = ""
+ if board.categories.any?
+ category_hashtags = board.categories.map { |category| "##{category.name}" }.join("\n")
+ category_html =
+ Nokogiri::HTML5
+ .fragment(PrettyText.cook(category_hashtags))
+ .css("a")
+ .map(&:to_s)
+ .join("\n")
+ end
+
+ args = {
+ board_url: url,
+ board_name: board.unicode_name,
+ board_tags: tag_html,
+ board_categories: category_html,
+ board_columns:
+ board
+ .columns
+ .select(:title, :icon)
+ .map { |column| { name: column.unicode_title, icon: column.icon } },
+ creator_username: board.created_by.username,
+ creator_avatar_url: board.created_by.small_avatar_url,
+ created_by: I18n.t("boards.onebox.created_by", username: board.created_by.display_name),
+ column_count: I18n.t("boards.onebox.column_count", count: board.columns.count),
+ onebox_type: I18n.t("boards.onebox.board"),
+ tags_preview: board.tags.any?,
+ categories_preview: board.categories.any?,
+ has_constraints: board.tags.any? || board.categories.any?,
+ columns_preview: board.columns.any?,
+ }
+
+ Mustache.render(Boards.board_onebox_template, args)
+ end
+ end
+end
diff --git a/plugins/boards/lib/boards/statistics.rb b/plugins/boards/lib/boards/statistics.rb
new file mode 100644
index 00000000000..6dae1600004
--- /dev/null
+++ b/plugins/boards/lib/boards/statistics.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+module Boards
+ module Statistics
+ def self.created_boards
+ {
+ last_day: Boards::Board.where("created_at > ?", 1.day.ago).count,
+ "7_days": Boards::Board.where("created_at > ?", 7.days.ago).count,
+ "30_days": Boards::Board.where("created_at > ?", 30.days.ago).count,
+ previous_30_days:
+ Boards::Board.where("created_at BETWEEN ? AND ?", 60.days.ago, 30.days.ago).count,
+ }
+ end
+
+ def self.total_boards
+ { count: Boards::Board.count }
+ end
+
+ def self.viewed_boards
+ scope =
+ Boards::BoardHistory.where(action: Boards::BoardHistory.actions[:board_viewed]).select(
+ "DISTINCT board_id",
+ )
+ {
+ last_day: scope.where("created_at > ?", 1.day.ago).count,
+ "7_days": scope.where("created_at > ?", 7.days.ago).count,
+ "30_days": scope.where("created_at > ?", 30.days.ago).count,
+ previous_30_days: scope.where("created_at BETWEEN ? AND ?", 60.days.ago, 30.days.ago).count,
+ count: scope.count,
+ }
+ end
+
+ def self.active_boards
+ scope =
+ Boards::CardHistory.where(
+ action: [
+ Boards::CardHistory.actions[:card_viewed],
+ Boards::CardHistory.actions[:card_created],
+ Boards::CardHistory.actions[:card_edited],
+ Boards::CardHistory.actions[:card_moved],
+ Boards::CardHistory.actions[:card_assigned],
+ Boards::CardHistory.actions[:card_unassigned],
+ Boards::CardHistory.actions[:card_deleted],
+ ],
+ ).select("DISTINCT board_id")
+ {
+ last_day: scope.where("created_at > ?", 1.day.ago).count,
+ "7_days": scope.where("created_at > ?", 7.days.ago).count,
+ "30_days": scope.where("created_at > ?", 30.days.ago).count,
+ previous_30_days: scope.where("created_at BETWEEN ? AND ?", 60.days.ago, 30.days.ago).count,
+ count: scope.count,
+ }
+ end
+
+ def self.combined_history_scope(card_actions, board_actions)
+ card_scope =
+ Boards::CardHistory.where(action: card_actions).select(:acting_user_id, :created_at)
+ board_scope =
+ Boards::BoardHistory.where(action: board_actions).select(:acting_user_id, :created_at)
+
+ Boards::CardHistory.from(
+ "(#{card_scope.to_sql} UNION ALL #{board_scope.to_sql}) combined_histories",
+ )
+ end
+ private_class_method :combined_history_scope
+
+ def self.active_users
+ combined_scope =
+ combined_history_scope(
+ [Boards::CardHistory.actions[:card_viewed]],
+ [Boards::BoardHistory.actions[:board_viewed]],
+ ).select("DISTINCT acting_user_id")
+ {
+ last_day: combined_scope.where("created_at > ?", 1.day.ago).count,
+ "7_days": combined_scope.where("created_at > ?", 7.days.ago).count,
+ "30_days": combined_scope.where("created_at > ?", 30.days.ago).count,
+ previous_30_days:
+ combined_scope.where("created_at BETWEEN ? AND ?", 60.days.ago, 30.days.ago).count,
+ count: combined_scope.count,
+ }
+ end
+
+ def self.participating_users
+ combined_scope =
+ combined_history_scope(
+ [
+ Boards::CardHistory.actions[:card_created],
+ Boards::CardHistory.actions[:card_edited],
+ Boards::CardHistory.actions[:card_moved],
+ Boards::CardHistory.actions[:card_assigned],
+ Boards::CardHistory.actions[:card_unassigned],
+ Boards::CardHistory.actions[:card_deleted],
+ ],
+ [Boards::BoardHistory.actions[:board_created]],
+ ).select("DISTINCT acting_user_id")
+ {
+ last_day: combined_scope.where("created_at > ?", 1.day.ago).count,
+ "7_days": combined_scope.where("created_at > ?", 7.days.ago).count,
+ "30_days": combined_scope.where("created_at > ?", 30.days.ago).count,
+ previous_30_days:
+ combined_scope.where("created_at BETWEEN ? AND ?", 60.days.ago, 30.days.ago).count,
+ count: combined_scope.count,
+ }
+ end
+ end
+end
diff --git a/plugins/boards/lib/onebox/templates/boards_board.mustache b/plugins/boards/lib/onebox/templates/boards_board.mustache
new file mode 100644
index 00000000000..cdca628f78b
--- /dev/null
+++ b/plugins/boards/lib/onebox/templates/boards_board.mustache
@@ -0,0 +1,62 @@
+<aside class="onebox discourse-boards-onebox discourse-boards-board-onebox">
+ <div class="discourse-boards-board-card__header">
+ <a href="{{board_url}}" class="discourse-boards-board-card__name">
+ <svg
+ class="fa d-icon d-icon-table-columns svg-icon svg-string"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <use href="#table-columns"></use>
+ </svg> {{board_name}}
+ </a>
+ </div>
+
+ {{#has_constraints}}
+ <div class="discourse-boards-board-card__constraints">
+ {{#categories_preview}}
+ {{{board_categories}}}
+ {{/categories_preview}}
+ {{#tags_preview}}
+ <div class="list-tags">{{{board_tags}}}</div>
+ {{/tags_preview}}
+ </div>
+ {{/has_constraints}}
+
+ {{#columns_preview}}
+ <div class="discourse-boards-board-card__columns">
+ {{#board_columns}}
+ <span class="discourse-boards-column-pill">
+ {{#icon}}
+ <svg
+ class="fa d-icon d-icon-{{icon}} svg-icon svg-string"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <use href="#{{icon}}"></use>
+ </svg>
+ {{/icon}}
+ {{name}}
+ </span>
+ {{/board_columns}}
+ </div>
+ {{/columns_preview}}
+
+ <div class="discourse-boards-board-card__footer">
+ <a
+ class="discourse-boards-board-card__creator discourse-boards-badge trigger-user-card"
+ data-user-card="{{creator_username}}"
+ aria-hidden="true"
+ tabindex="-1"
+ >
+ {{created_by}}
+ <img
+ loading="lazy"
+ alt="{{creator_username}}"
+ width="12"
+ height="12"
+ src="{{creator_avatar_url}}"
+ class="avatar"
+ >
+ </a>
+
+ <span class="discourse-boards-badge">{{column_count}}</span>
+ </div>
+</aside>
diff --git a/plugins/boards/lib/onebox/templates/boards_card.mustache b/plugins/boards/lib/onebox/templates/boards_card.mustache
new file mode 100644
index 00000000000..dcce318b585
--- /dev/null
+++ b/plugins/boards/lib/onebox/templates/boards_card.mustache
@@ -0,0 +1,59 @@
+<aside class="onebox discourse-boards-onebox discourse-boards-card-onebox">
+ <div class="discourse-boards-card__row discourse-boards-card__title-row">
+ <a href="{{card_url}}" class="discourse-boards-card__title">
+ <svg
+ class="fa d-icon d-icon-far-rectangle-list
+ svg-icon svg-string"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <use href="#far-rectangle-list
+"></use>
+ </svg>
+ {{card_name}}
+ </a>
+ </div>
+
+ <div class="discourse-boards-card__row">
+ <a href="{{board_url}}" class="discourse-boards-board-pill"><svg
+ class="fa d-icon d-icon-table-columns svg-icon svg-string"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <use href="#table-columns"></use>
+ </svg>{{board_name}}</a>
+ <span class="discourse-boards-column-pill">
+ {{#card_column_icon}}
+ <svg
+ class="fa d-icon d-icon-{{card_column_icon}} svg-icon svg-string"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <use href="#{{card_column_icon}}"></use>
+ </svg>
+ {{/card_column_icon}}
+ {{card_column_title}}
+ </span>
+ </div>
+
+ {{#tags_preview}}
+ <div class="discourse-boards-card__row discourse-boards-card__tags">
+ {{{card_tags}}}
+ </div>
+ {{/tags_preview}}
+
+ {{#has_notes}}
+ <div class="discourse-boards-card__notes">
+ {{{notes}}}
+ </div>
+ {{/has_notes}}
+
+ <div class="discourse-boards-card__row discourse-boards-card__detail-row">
+ <div class="discourse-boards-card__last-post-by">
+ <span
+ class="relative-date"
+ data-time="{{updated_at_ms}}"
+ data-format="tiny"
+ title="{{updated_at_title}}"
+ >{{updated_at_tiny}}</span>
+ ({{updater_username}})
+ </div>
+ </div>
+</aside>
diff --git a/plugins/boards/package.json b/plugins/boards/package.json
new file mode 100644
index 00000000000..d6198f26b11
--- /dev/null
+++ b/plugins/boards/package.json
@@ -0,0 +1,6 @@
+{
+ "private": true,
+ "dependencies": {
+ "discourse": "npm:@discourse/types@*"
+ }
+}
diff --git a/plugins/boards/plugin.rb b/plugins/boards/plugin.rb
new file mode 100644
index 00000000000..c39a58378cd
--- /dev/null
+++ b/plugins/boards/plugin.rb
@@ -0,0 +1,212 @@
+# frozen_string_literal: true
+
+# name: boards
+# about: Boards with optional topic backing and board-level ACLs.
+# meta_topic_id: 118164
+# version: 0.1
+# authors: Discourse
+# url: https://github.com/discourse/discourse/tree/main/plugins/boards
+# required_version: 2.7.0
+
+enabled_site_setting :boards_enabled
+
+register_asset "stylesheets/boards-manage.scss"
+register_asset "stylesheets/boards-board.scss"
+register_asset "stylesheets/boards-oneboxes.scss"
+register_asset "stylesheets/boards-topic-pill.scss"
+register_asset "stylesheets/boards-add-from-topic-menu.scss"
+register_svg_icon "table-columns"
+register_svg_icon "boards"
+
+module ::Boards
+ PLUGIN_NAME = "boards"
+end
+
+require_relative "lib/boards/engine"
+
+after_initialize do
+ # Keep queued jobs from the standalone plugin executable across the deploy.
+ legacy_jobs =
+ if Jobs.const_defined?(:DiscourseKanban, false)
+ Jobs.const_get(:DiscourseKanban, false)
+ else
+ Jobs.const_set(:DiscourseKanban, Module.new)
+ end
+ unless legacy_jobs.const_defined?(:SyncTopicForKanban, false)
+ legacy_jobs.const_set(:SyncTopicForKanban, Jobs::Boards::SyncTopic)
+ end
+ unless legacy_jobs.const_defined?(:CardPostProcess, false)
+ legacy_jobs.const_set(:CardPostProcess, Jobs::Boards::CardPostProcess)
+ end
+
+ reloadable_patch { |plugin| Guardian.prepend Boards::GuardianExtensions }
+
+ # Register any column icons already in the DB so they appear in the SVG sprite
+ begin
+ if ActiveRecord::Base.connection.data_source_exists?(:discourse_kanban_columns) &&
+ ActiveRecord::Base.connection.column_exists?(:discourse_kanban_columns, :default_sort)
+ Boards::Column
+ .where.not(icon: [nil, ""])
+ .distinct
+ .pluck(:icon)
+ .each { |icon| DiscoursePluginRegistry.register_svg_icon(icon) }
+ end
+ rescue ActiveRecord::NoDatabaseError,
+ ActiveRecord::StatementInvalid,
+ ActiveRecord::DatabaseConnectionError
+ # Database may not exist/may have pending migrations yet during db:create / db:migrate bootstrap.
+ end
+
+ # When a column's icon changes, register it and expire the sprite cache
+ add_model_callback(Boards::Column, :after_commit) do
+ if saved_change_to_icon? && icon.present?
+ DiscoursePluginRegistry.register_svg_icon(icon)
+ SvgSprite.expire_cache
+ end
+ end
+
+ add_to_serializer(:current_user, :can_manage_boards) { scope.can_manage_boards? }
+
+ add_to_serializer(:current_user, :can_edit_any_boards) do
+ scope.target_ids_with_any_acl_permissions(Boards::Board, %w[edit manage]).any?
+ end
+
+ add_to_class(:topic, :board_cards_map) { @board_cards_map }
+ add_to_class(:topic, :board_cards_map=) { |cards| @board_cards_map = cards }
+
+ TopicList.on_preload do |topics, topic_list|
+ next unless SiteSetting.boards_enabled
+
+ guardian = topic_list.current_user.present? ? topic_list.current_user.guardian : Guardian.new
+
+ result = Boards::TopicBoardMemberships.call(guardian:, options: { topics: })
+ cards_map = result[:cards_map]
+ topics.each { |topic| topic.board_cards_map = cards_map.fetch(topic.id, {}) }
+ end
+
+ add_to_serializer(
+ :topic_list_item,
+ :board_memberships,
+ include_condition: -> { SiteSetting.boards_enabled && board_memberships.present? },
+ ) do
+ @board_memberships ||=
+ begin
+ cards_map = object.board_cards_map
+ if cards_map.nil?
+ result =
+ Boards::TopicBoardMemberships.call(guardian: scope, options: { topics: [object] })
+ cards_map = result[:cards_map].fetch(object.id, {})
+ end
+
+ ActiveModel::ArraySerializer.new(
+ cards_map.values,
+ each_serializer: Boards::TopicBoardMembershipSerializer,
+ scope:,
+ ).as_json
+ end
+ end
+
+ add_to_serializer(
+ :topic_view,
+ :board_memberships,
+ include_condition: -> { SiteSetting.boards_enabled },
+ ) do
+ @board_memberships ||=
+ begin
+ topic = object.topic
+ result = Boards::TopicBoardMemberships.call(guardian: scope, options: { topics: [topic] })
+ cards_map = result[:cards_map].fetch(topic.id, {})
+ ActiveModel::ArraySerializer.new(
+ cards_map.values,
+ each_serializer: Boards::TopicBoardMembershipSerializer,
+ scope:,
+ ).as_json
+ end
+ end
+
+ DiscoursePluginRegistry.register_acl_target_class(Boards::Board, self)
+
+ on(:topic_created) do |topic|
+ Boards::TopicSync.sync_topic(topic)
+ rescue StandardError => e
+ Rails.logger.warn("Boards: failed to sync topic #{topic&.id}: #{e.message}")
+ end
+
+ on(:topic_tags_changed) do |topic, _|
+ Boards::TopicSync.sync_topic(topic)
+ rescue StandardError => e
+ Rails.logger.warn("Boards: failed to sync topic #{topic&.id}: #{e.message}")
+ end
+
+ on(:topic_status_updated) do |topic, _, _|
+ Boards::TopicSync.sync_topic(topic)
+ rescue StandardError => e
+ Rails.logger.warn("Boards: failed to sync topic #{topic&.id}: #{e.message}")
+ end
+
+ on(:topic_recovered) do |topic, _|
+ Boards::TopicSync.sync_topic(topic)
+ rescue StandardError => e
+ Rails.logger.warn("Boards: failed to sync topic #{topic&.id}: #{e.message}")
+ end
+
+ on(:topic_destroyed) do |topic, _|
+ Boards::TopicSync.remove_topic(topic.id)
+ rescue StandardError => e
+ Rails.logger.warn("Boards: failed to remove topic #{topic&.id}: #{e.message}")
+ end
+
+ Oneboxer.register_local_handler("boards/boards") do |url, route, opts|
+ ::Boards::OneboxHandler.handle(url, route, opts)
+ end
+
+ InlineOneboxer.register_local_handler("boards/boards") do |url, route, opts|
+ ::Boards::InlineOneboxHandler.handle(url, route, opts)
+ end
+
+ if defined?(Assignment)
+ add_model_callback(Assignment, :after_commit) do
+ next unless SiteSetting.boards_enabled?
+
+ begin
+ tid = topic_id
+ next if tid.blank?
+
+ Jobs.cancel_scheduled_job("Boards::SyncTopic", topic_id: tid)
+ Jobs.enqueue_in(5.seconds, Jobs::Boards::SyncTopic, topic_id: tid)
+ rescue StandardError => e
+ Rails.logger.warn(
+ "Boards: failed to enqueue sync after assignment change for topic #{tid}: #{e.message}",
+ )
+ end
+ end
+ end
+
+ add_model_callback(Topic, :after_commit) do
+ next unless SiteSetting.boards_enabled?
+ next unless saved_changes?
+
+ begin
+ if saved_changes.key?("deleted_at") && deleted_at.present?
+ Boards::TopicSync.remove_topic(id)
+ next
+ end
+
+ tracked_changes = %w[category_id archetype visible]
+ next if (saved_changes.keys & tracked_changes).empty?
+
+ Boards::TopicSync.sync_topic(self)
+ rescue StandardError => e
+ Rails.logger.warn("Boards: after_commit sync failed for topic #{id}: #{e.message}")
+ end
+ end
+
+ register_stat("total_boards", stat_type: :boards) { Boards::Statistics.total_boards }
+ register_stat("created_boards", stat_type: :boards) { Boards::Statistics.created_boards }
+ register_stat("viewed_boards", stat_type: :boards) { Boards::Statistics.viewed_boards }
+ register_stat("active_boards", stat_type: :boards) { Boards::Statistics.active_boards }
+ register_stat("active_users", stat_type: :boards) { Boards::Statistics.active_users }
+ register_stat("participating_users", stat_type: :boards) do
+ Boards::Statistics.participating_users
+ end
+end
diff --git a/plugins/boards/public/images/upcoming_changes/boards_enabled.png b/plugins/boards/public/images/upcoming_changes/boards_enabled.png
new file mode 100644
index 00000000000..139e4b35fae
Binary files /dev/null and b/plugins/boards/public/images/upcoming_changes/boards_enabled.png differ
diff --git a/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rb b/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rb
new file mode 100644
index 00000000000..8b31caa682f
--- /dev/null
+++ b/plugins/boards/spec/db/migrate/20260901020329_migrate_discourse_kanban_to_boards_spec.rb
@@ -0,0 +1,148 @@
+# frozen_string_literal: true
+
+require Rails.root.join(
+ "plugins/boards/db/migrate/20260901020329_migrate_discourse_kanban_to_boards.rb",
+ )
+
+RSpec.describe MigrateDiscourseKanbanToBoards do
+ subject(:migrate) { described_class.new.up }
+
+ fab!(:creator, :user)
+ fab!(:board) do
+ Boards::Board.create!(name: "Migration board", slug: "migration-board", created_by: creator)
+ end
+ fab!(:group)
+
+ before do
+ @original_verbose = ActiveRecord::Migration.verbose
+ ActiveRecord::Migration.verbose = false
+ end
+
+ after do
+ ActiveRecord::Migration.verbose = @original_verbose
+ Discourse.clear_site_creation_date_cache
+ end
+
+ def mark_as_existing_site
+ DB.exec("UPDATE schema_migration_details SET created_at = NOW() - INTERVAL '2 hours'")
+ Discourse.clear_site_creation_date_cache
+ end
+
+ def insert_setting(name:, value:, data_type:)
+ DB.exec(<<~SQL, name:, value:, data_type:)
+ INSERT INTO site_settings (name, value, data_type, created_at, updated_at)
+ VALUES (:name, :value, :data_type, NOW(), NOW())
+ SQL
+ end
+
+ def insert_acl(target_type:, permission:, owner:)
+ AccessControlList.create!(
+ target_id: board.id,
+ target_type:,
+ permission:,
+ owner:,
+ allowed_group_ids: [group.id],
+ )
+ end
+
+ it "copies legacy settings on existing sites without removing or overwriting values" do
+ mark_as_existing_site
+ insert_setting(name: "discourse_kanban_enabled", value: "t", data_type: 5)
+ insert_setting(
+ name: "discourse_kanban_manage_board_allowed_groups",
+ value: "1|42",
+ data_type: 20,
+ )
+ insert_setting(name: "boards_enabled", value: "f", data_type: 5)
+
+ 2.times { migrate }
+
+ settings = DB.query(<<~SQL).map { |setting| [setting.name, setting.value, setting.data_type] }
+ SELECT name, value, data_type
+ FROM site_settings
+ WHERE name IN (
+ 'boards_enabled',
+ 'boards_manage_board_allowed_groups',
+ 'discourse_kanban_enabled',
+ 'discourse_kanban_manage_board_allowed_groups'
+ )
+ SQL
+
+ expect(settings).to contain_exactly(
+ ["boards_enabled", "f", 5],
+ ["boards_manage_board_allowed_groups", "1|42", 20],
+ ["discourse_kanban_enabled", "t", 5],
+ ["discourse_kanban_manage_board_allowed_groups", "1|42", 20],
+ )
+ end
+
+ it "does not copy legacy settings on fresh installs" do
+ DB.exec("UPDATE schema_migration_details SET created_at = NOW()")
+ Discourse.clear_site_creation_date_cache
+ insert_setting(name: "discourse_kanban_enabled", value: "t", data_type: 5)
+
+ migrate
+
+ setting_names = DB.query_single("SELECT name FROM site_settings")
+ expect(setting_names).not_to include("boards_enabled")
+ expect(setting_names).to include("discourse_kanban_enabled")
+ end
+
+ it "copies legacy ACLs to the Boards model while preserving the legacy rows" do
+ %w[view edit manage].each do |permission|
+ insert_acl(target_type: "DiscourseKanban::Board", permission:, owner: "discourse-kanban")
+ end
+
+ 2.times { migrate }
+
+ expect(
+ AccessControlList.where(target_id: board.id).pluck(
+ :target_type,
+ :owner,
+ :permission,
+ :allowed_group_ids,
+ ),
+ ).to contain_exactly(
+ ["DiscourseKanban::Board", "discourse-kanban", "view", [group.id]],
+ ["DiscourseKanban::Board", "discourse-kanban", "edit", [group.id]],
+ ["DiscourseKanban::Board", "discourse-kanban", "manage", [group.id]],
+ ["Boards::Board", "boards", "view", [group.id]],
+ ["Boards::Board", "boards", "edit", [group.id]],
+ ["Boards::Board", "boards", "manage", [group.id]],
+ )
+ end
+
+ it "copies legacy ACLs idempotently when the expected unique index is absent" do
+ insert_acl(target_type: "DiscourseKanban::Board", permission: "view", owner: "discourse-kanban")
+ DB.exec("DROP INDEX idx_on_target_type_target_id_permission_f472902150")
+
+ 2.times { migrate }
+
+ expect(
+ AccessControlList.where(
+ target_id: board.id,
+ target_type: "Boards::Board",
+ permission: "view",
+ ).pluck(:owner, :allowed_group_ids),
+ ).to eq([["boards", [group.id]]])
+ end
+
+ it "does not overwrite an existing Boards ACL when copying a legacy row" do
+ legacy =
+ insert_acl(
+ target_type: "DiscourseKanban::Board",
+ permission: "view",
+ owner: "discourse-kanban",
+ )
+ existing = insert_acl(target_type: "Boards::Board", permission: "view", owner: "core")
+
+ migrate
+
+ expect(legacy.reload).to have_attributes(
+ target_type: "DiscourseKanban::Board",
+ owner: "discourse-kanban",
+ )
+ expect(existing.reload).to have_attributes(target_type: "Boards::Board", owner: "core")
+ expect(AccessControlList.where(target_id: board.id, permission: "view").count).to eq(2)
+ end
+end
diff --git a/plugins/boards/spec/fabricators/boards_board_fabricator.rb b/plugins/boards/spec/fabricators/boards_board_fabricator.rb
new file mode 100644
index 00000000000..34c46e05ed1
--- /dev/null
+++ b/plugins/boards/spec/fabricators/boards_board_fabricator.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+Fabricator(:boards_board, class_name: "Boards::Board") do
+ name { sequence(:boards_board_name) { |i| "#{Faker::Company.buzzword.capitalize} Board #{i}" } }
+ created_by { Fabricate(:user) }
+ transient :column_names
+ transient :additional_manage_groups
+
+ after_create do |board, evaluator|
+ (evaluator[:column_names] || []).each_with_index do |column_name, index|
+ board.columns.create!(title: column_name, position: index)
+ end
+
+ additional_manage_groups =
+ Array
+ .wrap(evaluator[:additional_manage_groups])
+ .map { |group| AccessControlList.flat_acl_for(group, "manage") }
+
+ AccessControlList.bulk_insert_flattened_acl!(
+ AccessControlList.inject_mandatory_acl(additional_manage_groups, board),
+ board,
+ Boards::PLUGIN_NAME,
+ )
+ end
+end
diff --git a/plugins/boards/spec/fabricators/boards_board_history_fabricator.rb b/plugins/boards/spec/fabricators/boards_board_history_fabricator.rb
new file mode 100644
index 00000000000..13175c71028
--- /dev/null
+++ b/plugins/boards/spec/fabricators/boards_board_history_fabricator.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+Fabricator(:boards_board_history, class_name: "Boards::BoardHistory") do
+ board { Fabricate(:boards_board) }
+ acting_user { Fabricate(:user) }
+ action :board_viewed
+end
diff --git a/plugins/boards/spec/fabricators/boards_card_fabricator.rb b/plugins/boards/spec/fabricators/boards_card_fabricator.rb
new file mode 100644
index 00000000000..77570549010
--- /dev/null
+++ b/plugins/boards/spec/fabricators/boards_card_fabricator.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+Fabricator(:boards_card, class_name: "Boards::Card") do
+ board { |attrs| attrs[:column]&.board || Fabricate(:boards_board) }
+ column { |attrs| Fabricate(:boards_column, board: attrs[:board]) }
+ card_type :floater
+ title { Faker::Lorem.sentence(word_count: 10) }
+ position { sequence(:boards_card_position) }
+end
+
+Fabricator(:boards_topic_card, from: :boards_card) do
+ card_type :topic
+ title nil
+ topic { |attrs| Fabricate(:topic) }
+end
diff --git a/plugins/boards/spec/fabricators/boards_card_history_fabricator.rb b/plugins/boards/spec/fabricators/boards_card_history_fabricator.rb
new file mode 100644
index 00000000000..3f01f97ed57
--- /dev/null
+++ b/plugins/boards/spec/fabricators/boards_card_history_fabricator.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+Fabricator(:boards_card_history, class_name: "Boards::CardHistory") do
+ board { |attrs| attrs[:card]&.board || Fabricate(:boards_board) }
+ card { |attrs| Fabricate(:boards_card, board: attrs[:board]) }
+ acting_user { Fabricate(:user) }
+ action :card_viewed
+end
diff --git a/plugins/boards/spec/fabricators/boards_column_fabricator.rb b/plugins/boards/spec/fabricators/boards_column_fabricator.rb
new file mode 100644
index 00000000000..fbfb0f84e0d
--- /dev/null
+++ b/plugins/boards/spec/fabricators/boards_column_fabricator.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+Fabricator(:boards_column, class_name: "Boards::Column") do
+ board { Fabricate(:boards_board) }
+ title { Faker::Lorem.words(number: 2).map(&:capitalize).join(" ") }
+ position { sequence(:boards_column_position) }
+end
diff --git a/plugins/boards/spec/integration/assignment_callback_spec.rb b/plugins/boards/spec/integration/assignment_callback_spec.rb
new file mode 100644
index 00000000000..fdf33d0f20a
--- /dev/null
+++ b/plugins/boards/spec/integration/assignment_callback_spec.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+describe "Boards sync from the Assignment after_commit callback", if: defined?(Assignment) do
+ fab!(:topic)
+ fab!(:user)
+
+ before do
+ enable_current_plugin
+ SiteSetting.assign_enabled = true
+ end
+
+ it "enqueues a boards sync for the topic when an assignment is created" do
+ expect_enqueued_with(job: Jobs::Boards::SyncTopic, args: { topic_id: topic.id }) do
+ Fabricate(:topic_assignment, topic: topic, target: topic)
+ end
+ end
+
+ it "enqueues a boards sync for the topic when an assignment is updated" do
+ assignment = Fabricate(:topic_assignment, topic: topic, target: topic)
+
+ expect_enqueued_with(job: Jobs::Boards::SyncTopic, args: { topic_id: topic.id }) do
+ assignment.update!(assigned_to: user)
+ end
+ end
+
+ it "enqueues a boards sync for the topic when an assignment is destroyed" do
+ assignment = Fabricate(:topic_assignment, topic: topic, target: topic)
+
+ expect_enqueued_with(job: Jobs::Boards::SyncTopic, args: { topic_id: topic.id }) do
+ assignment.destroy!
+ end
+ end
+
+ it "cancels any sync already scheduled for the topic" do
+ # The job name passed to `cancel_scheduled_job` must camelcase into the job's
+ # full class name, otherwise nothing is ever cancelled.
+ Jobs
+ .expects(:cancel_scheduled_job)
+ .with do |job_name, opts|
+ "Jobs::#{job_name.to_s.camelcase}" == Jobs::Boards::SyncTopic.name &&
+ opts == { topic_id: topic.id }
+ end
+ .at_least_once
+
+ Fabricate(:topic_assignment, topic: topic, target: topic)
+ end
+
+ it "does not enqueue a sync when the plugin is disabled" do
+ SiteSetting.boards_enabled = false
+
+ expect_enqueued_with(
+ job: Jobs::Boards::SyncTopic,
+ args: {
+ topic_id: topic.id,
+ },
+ expectation: false,
+ ) { Fabricate(:topic_assignment, topic: topic, target: topic) }
+ end
+end
diff --git a/plugins/boards/spec/jobs/regular/boards/card_post_process_spec.rb b/plugins/boards/spec/jobs/regular/boards/card_post_process_spec.rb
new file mode 100644
index 00000000000..c64e9f959f6
--- /dev/null
+++ b/plugins/boards/spec/jobs/regular/boards/card_post_process_spec.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::Boards::CardPostProcess do
+ fab!(:admin)
+ fab!(:viewer, :user)
+ fab!(:viewer_group, :group)
+ fab!(:board) do
+ Fabricate(:boards_board, created_by: admin).tap do |board|
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [viewer_group],
+ )
+ end
+ end
+ fab!(:column) { Fabricate(:boards_column, board:) }
+ fab!(:card) do
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ title: "https://github.com/discourse/discourse/pull/42462",
+ created_by: admin,
+ )
+ end
+
+ before do
+ enable_current_plugin
+ viewer_group.add(viewer)
+ end
+
+ describe "#execute" do
+ let(:onebox_data) do
+ {
+ "url" => card.title,
+ "title" => "FEATURE: Add ProseMirror tab support",
+ "css_class" => "--gh-status-approved",
+ }
+ end
+
+ it "stores the inline onebox data without changing the card timestamp" do
+ original_updated_at = card.updated_at
+ Boards::Action::CardInlineOnebox.expects(:call).with(title: card.title).returns(onebox_data)
+
+ described_class.new.execute(card_id: card.id, title: card.title)
+
+ expect(card.reload.inline_onebox_data).to eq(onebox_data)
+ expect(card.updated_at).to eq_time(original_updated_at)
+ end
+
+ it "publishes the updated card to users who can view the board" do
+ Boards::Action::CardInlineOnebox.expects(:call).with(title: card.title).returns(onebox_data)
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") do
+ described_class.new.execute(card_id: card.id, title: card.title)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.group_ids).to include(viewer_group.id)
+ expect(messages.first.data).to include(type: "card_updated", client_id: nil)
+ expect(messages.first.data.dig(:card, :inline_onebox_data)).to eq(onebox_data)
+ end
+
+ it "does nothing when the title has changed since the job was enqueued" do
+ original_title = card.title
+ card.update!(title: "A newer title")
+ Boards::Action::CardInlineOnebox.expects(:call).never
+
+ expect do
+ described_class.new.execute(card_id: card.id, title: original_title)
+ end.not_to change { card.reload.inline_onebox_data }
+ end
+
+ it "does not publish when resolving produces no data" do
+ Boards::Action::CardInlineOnebox.expects(:call).with(title: card.title).returns(nil)
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") do
+ described_class.new.execute(card_id: card.id, title: card.title)
+ end
+
+ expect(messages).to be_empty
+ expect(card.reload.inline_onebox_data).to be_nil
+ end
+
+ it "does nothing for a topic-backed card" do
+ topic_card = Fabricate(:boards_topic_card, board:, column:, created_by: admin)
+ Boards::Action::CardInlineOnebox.expects(:call).never
+
+ described_class.new.execute(card_id: topic_card.id, title: card.title)
+ end
+
+ it "does nothing for a title that is not a URL" do
+ card.update!(title: "A regular card title")
+ Boards::Action::CardInlineOnebox.expects(:call).with(title: card.title).returns(nil)
+
+ described_class.new.execute(card_id: card.id, title: card.title)
+ end
+ end
+end
diff --git a/plugins/boards/spec/jobs/regular/boards/sync_topic_spec.rb b/plugins/boards/spec/jobs/regular/boards/sync_topic_spec.rb
new file mode 100644
index 00000000000..00a330df9e0
--- /dev/null
+++ b/plugins/boards/spec/jobs/regular/boards/sync_topic_spec.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::Boards::SyncTopic do
+ fab!(:topic)
+
+ before { enable_current_plugin }
+
+ describe "#execute" do
+ it "syncs the topic" do
+ Boards::TopicSync.expects(:sync_topic).with(topic)
+
+ described_class.new.execute(topic_id: topic.id)
+ end
+
+ it "does nothing when the plugin is disabled" do
+ SiteSetting.boards_enabled = false
+ Boards::TopicSync.expects(:sync_topic).never
+
+ described_class.new.execute(topic_id: topic.id)
+ end
+
+ it "does nothing when no topic_id is given" do
+ Boards::TopicSync.expects(:sync_topic).never
+
+ described_class.new.execute(topic_id: nil)
+ end
+
+ it "does nothing when the topic no longer exists" do
+ Boards::TopicSync.expects(:sync_topic).never
+
+ described_class.new.execute(topic_id: topic.id + 1000)
+ end
+ end
+end
diff --git a/plugins/boards/spec/lib/boards/inline_onebox_handler_spec.rb b/plugins/boards/spec/lib/boards/inline_onebox_handler_spec.rb
new file mode 100644
index 00000000000..1760c2ea9c5
--- /dev/null
+++ b/plugins/boards/spec/lib/boards/inline_onebox_handler_spec.rb
@@ -0,0 +1,267 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::InlineOneboxHandler do
+ fab!(:admin)
+ fab!(:topic) { Fabricate(:topic, title: "Topic card headline") }
+
+ before { enable_current_plugin }
+
+ fab!(:board) do
+ board =
+ Boards::Board.create!(name: "Roadmap board", slug: "roadmap-board", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [
+ Group::AUTO_GROUPS[:anonymous_users],
+ Group::AUTO_GROUPS[:logged_in_users],
+ ],
+ )
+ board
+ end
+
+ fab!(:column) { board.columns.create!(title: "Todo", position: 0) }
+
+ fab!(:floater_card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Standalone card title",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:topic_card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:base_url) { "https://example.com/boards-plugin-path" }
+
+ let(:route_board_only) { { id: board.id.to_s, card_id: nil } }
+ let(:floater_card_route) { { id: board.id.to_s, card_id: floater_card.id.to_s } }
+ let(:topic_card_route) { { id: board.id.to_s, card_id: topic_card.id.to_s } }
+
+ describe ".handle" do
+ context "when the route has no card id" do
+ it "handles nil opts gracefully" do
+ result = described_class.handle("#{base_url}/boards/x/#{board.id}", route_board_only, nil)
+ expect(result).to eq(
+ url: "#{base_url}/boards/x/#{board.id}",
+ title: I18n.t("boards.onebox.inline_to_board", board_name: board.name),
+ )
+ end
+
+ it "returns url and a board title when the board exists and is readable" do
+ result = described_class.handle("#{base_url}/boards/x/#{board.id}", route_board_only)
+
+ expect(result).to eq(
+ url: "#{base_url}/boards/x/#{board.id}",
+ title: I18n.t("boards.onebox.inline_to_board", board_name: board.name),
+ )
+ end
+
+ it "renders emoji codes in the board title as Unicode" do
+ board.update!(name: "Roadmap :rocket:")
+
+ result = described_class.handle("#{base_url}/boards/x/#{board.id}", route_board_only)
+
+ expect(result[:title]).to eq("Board 'Roadmap πŸš€'")
+ end
+
+ it "returns nil when the board does not exist" do
+ missing_id = Boards::Board.maximum(:id).to_i + 99_999
+ route = { id: missing_id.to_s, card_id: nil }
+
+ expect(described_class.handle("#{base_url}/boards/x/#{missing_id}", route)).to be_nil
+ end
+
+ it "returns nil when the guardian denies board read access" do
+ private_group = Fabricate(:group)
+ board.access_control_lists.destroy_all
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [private_group],
+ )
+ expect(
+ described_class.handle("#{base_url}/boards/x/#{board.id}", route_board_only),
+ ).to be_nil
+ end
+ end
+
+ context "when the route includes a card id" do
+ it "returns url and a card title using the floater card name" do
+ result =
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{floater_card.id}",
+ floater_card_route,
+ )
+
+ expect(result).to eq(
+ url: "#{base_url}/boards/x/#{board.id}/cards/#{floater_card.id}",
+ title:
+ I18n.t(
+ "boards.onebox.inline_to_card",
+ card_name: floater_card.resolved_title,
+ board_name: board.name,
+ ),
+ )
+ end
+
+ it "renders emoji codes in card and board titles as Unicode" do
+ board.update!(name: "Roadmap :rocket:")
+ floater_card.update!(title: "Launch :tada:")
+
+ result =
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{floater_card.id}",
+ floater_card_route,
+ )
+
+ expect(result[:title]).to eq("Card 'Launch πŸŽ‰' on board 'Roadmap πŸš€'")
+ end
+
+ it "uses the topic title for topic-backed cards" do
+ result =
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ topic_card_route,
+ )
+
+ expect(result).to eq(
+ url: "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ title:
+ I18n.t(
+ "boards.onebox.inline_to_card",
+ card_name: "Topic card headline",
+ board_name: board.name,
+ ),
+ )
+ end
+
+ it "handles nil opts gracefully for topic backed cards" do
+ result =
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ topic_card_route,
+ nil,
+ )
+
+ expect(result).to eq(
+ url: "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ title:
+ I18n.t(
+ "boards.onebox.inline_to_card",
+ card_name: "Topic card headline",
+ board_name: board.name,
+ ),
+ )
+ end
+
+ it "does not expose the title of a topic the viewer cannot read" do
+ private_group = Fabricate(:group)
+ private_category = Fabricate(:private_category, group: private_group)
+ private_topic =
+ Fabricate(:topic, title: "Restricted topic card headline", category: private_category)
+ topic_card.update!(topic: private_topic)
+
+ expect(
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ topic_card_route,
+ ),
+ ).to be_nil
+ end
+
+ it "returns the card title for an authorized same-category context" do
+ private_group = Fabricate(:group)
+ private_user = Fabricate(:user)
+ Fabricate(:group_user, group: private_group, user: private_user)
+ private_category = Fabricate(:private_category, group: private_group)
+ private_topic =
+ Fabricate(:topic, title: "Restricted topic card headline", category: private_category)
+ topic_card.update!(topic: private_topic)
+
+ result =
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ topic_card_route,
+ { user_id: private_user.id, category_id: private_category.id },
+ )
+
+ expect(result).to eq(
+ url: "#{base_url}/boards/x/#{board.id}/cards/#{topic_card.id}",
+ title:
+ I18n.t(
+ "boards.onebox.inline_to_card",
+ card_name: private_topic.title,
+ board_name: board.name,
+ ),
+ )
+ end
+
+ it "returns nil when the board does not exist" do
+ missing_board_id = Boards::Board.maximum(:id).to_i + 99_999
+ route = { id: missing_board_id.to_s, card_id: floater_card.id.to_s }
+
+ expect(
+ described_class.handle(
+ "#{base_url}/boards/x/#{missing_board_id}/cards/#{floater_card.id}",
+ route,
+ ),
+ ).to be_nil
+ end
+
+ it "returns nil when the guardian denies board read access" do
+ private_group = Fabricate(:group)
+ board.access_control_lists.destroy_all
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [private_group],
+ )
+ expect(
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{floater_card.id}",
+ floater_card_route,
+ ),
+ ).to be_nil
+ end
+
+ it "returns nil when no card matches the id and board id" do
+ other_board =
+ Boards::Board.create!(name: "Other", slug: "other-board", created_by_id: admin.id)
+ route = { id: other_board.id.to_s, card_id: floater_card.id.to_s }
+
+ expect(
+ described_class.handle(
+ "#{base_url}/boards/x/#{other_board.id}/cards/#{floater_card.id}",
+ route,
+ ),
+ ).to be_nil
+ end
+
+ it "returns nil when the card id does not exist" do
+ missing_card_id = Boards::Card.maximum(:id).to_i + 99_999
+ route = { id: board.id.to_s, card_id: missing_card_id.to_s }
+
+ expect(
+ described_class.handle(
+ "#{base_url}/boards/x/#{board.id}/cards/#{missing_card_id}",
+ route,
+ ),
+ ).to be_nil
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/lib/boards/onebox_handler_spec.rb b/plugins/boards/spec/lib/boards/onebox_handler_spec.rb
new file mode 100644
index 00000000000..8d1b9ff222d
--- /dev/null
+++ b/plugins/boards/spec/lib/boards/onebox_handler_spec.rb
@@ -0,0 +1,363 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::OneboxHandler do
+ fab!(:admin)
+
+ before { enable_current_plugin }
+
+ fab!(:board) do
+ board =
+ Boards::Board.create!(name: "Roadmap board", slug: "roadmap-board", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [
+ Group::AUTO_GROUPS[:anonymous_users],
+ Group::AUTO_GROUPS[:logged_in_users],
+ ],
+ )
+ board
+ end
+
+ fab!(:topic) { Fabricate(:topic, title: "Topic card headline") }
+
+ fab!(:column) { board.columns.create!(title: "Todo", position: 0) }
+ fab!(:tag_1, :tag)
+ fab!(:tag_2, :tag)
+ fab!(:category) { Fabricate(:category, name: "events", slug: "events") }
+
+ fab!(:floater_card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Standalone card title",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ tag_ids: [tag_1.id, tag_2.id],
+ notes: "This is **markdown** _note_",
+ )
+ end
+
+ fab!(:topic_card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+
+ describe "card onebox" do
+ it "returns empty string if the card does not exist" do
+ floater_card.destroy!
+ expect(
+ Boards::OneboxHandler.handle(floater_card.url, { id: board.id, card_id: floater_card.id }),
+ ).to eq("")
+ end
+
+ it "returns empty string if the user does not have permission to read the board" do
+ private_group = Fabricate(:group)
+ board.access_control_lists.destroy_all
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [private_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [private_group],
+ )
+ expect(
+ Boards::OneboxHandler.handle(floater_card.url, { id: board.id, card_id: floater_card.id }),
+ ).to eq("")
+ end
+
+ it "does not expose the title of a topic the viewer cannot read" do
+ private_group = Fabricate(:group)
+ private_category = Fabricate(:private_category, group: private_group)
+ private_topic =
+ Fabricate(:topic, title: "Restricted topic card headline", category: private_category)
+ topic_card.update!(topic: private_topic)
+
+ onebox_html =
+ Boards::OneboxHandler.handle(topic_card.url, { id: board.id, card_id: topic_card.id })
+
+ expect(onebox_html).to eq("")
+ end
+
+ it "renders a restricted topic card onebox for an authorized same-category context" do
+ private_group = Fabricate(:group)
+ private_user = Fabricate(:user)
+ Fabricate(:group_user, group: private_group, user: private_user)
+ private_category = Fabricate(:private_category, group: private_group)
+ private_topic =
+ Fabricate(:topic, title: "Restricted topic card headline", category: private_category)
+ topic_card.update!(topic: private_topic)
+
+ onebox_html =
+ Boards::OneboxHandler.handle(
+ topic_card.url,
+ { id: board.id, card_id: topic_card.id },
+ { user_id: private_user.id, category_id: private_category.id },
+ )
+
+ expect(onebox_html).to include(private_topic.title)
+ end
+
+ it "does not return empty string if the onebox renders successfully" do
+ expect(
+ Boards::OneboxHandler.handle(floater_card.url, { id: board.id, card_id: floater_card.id }),
+ ).not_to eq("")
+ end
+
+ it "renders emoji codes in the column title as Unicode" do
+ column.update!(title: "Todo :rocket:")
+
+ onebox_html =
+ Boards::OneboxHandler.handle(floater_card.url, { id: board.id, card_id: floater_card.id })
+
+ expect(onebox_html).to include("Todo πŸš€")
+ expect(onebox_html).not_to include(":rocket:")
+ end
+
+ it "renders emoji codes in the card title as Unicode" do
+ floater_card.update!(title: "Launch :rocket:")
+
+ onebox_html =
+ Boards::OneboxHandler.handle(floater_card.url, { id: board.id, card_id: floater_card.id })
+
+ expect(onebox_html).to include("Launch πŸš€")
+ expect(onebox_html).not_to include(":rocket:")
+ end
+
+ it "has the correct HTML structure" do
+ onebox_html =
+ Boards::OneboxHandler.handle(floater_card.url, { id: board.id, card_id: floater_card.id })
+
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "discourse-boards-card__title",
+ href: floater_card.url,
+ },
+ seen: floater_card.resolved_title,
+ )
+
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "discourse-boards-board-pill",
+ href: board.url,
+ },
+ seen: board.name,
+ )
+
+ expect(onebox_html).to have_tag(
+ "span",
+ with: {
+ class: "discourse-boards-column-pill",
+ },
+ seen: column.title,
+ )
+
+ expect(onebox_html).to have_tag("div", with: { class: "discourse-boards-card__tags" })
+
+ floater_card.tags.each do |tag|
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "hashtag-cooked",
+ "data-slug": tag.name,
+ },
+ seen: tag.name,
+ )
+ end
+
+ expect(onebox_html).to have_tag(
+ "div",
+ with: {
+ class: "discourse-boards-card__notes",
+ },
+ seen: "This is markdown note",
+ )
+
+ expect(onebox_html).to have_tag(
+ "span",
+ with: {
+ class: "relative-date",
+ "data-time": (floater_card.updated_at.to_f * 1000).to_i,
+ "data-format": "tiny",
+ },
+ )
+
+ expect(onebox_html).to include(
+ "(#{floater_card.updated_by&.username || floater_card.created_by.username})",
+ )
+ expect(onebox_html).to have_tag("aside", with: { class: "onebox" })
+ end
+
+ it "handles nil opts gracefully for a topic card" do
+ onebox_html =
+ Boards::OneboxHandler.handle(topic_card.url, { id: board.id, card_id: topic_card.id }, nil)
+
+ expect(onebox_html).to include(topic_card.resolved_title)
+ end
+ end
+
+ describe "board onebox" do
+ it "returns empty string if the board does not exist" do
+ board.destroy!
+ expect(Boards::OneboxHandler.handle(board.url, { id: board.id })).to eq("")
+ end
+
+ it "returns empty string if the user does not have permission to read the board" do
+ private_group = Fabricate(:group)
+ board.access_control_lists.destroy_all
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [private_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [private_group],
+ )
+ expect(Boards::OneboxHandler.handle(board.url, { id: board.id })).to eq("")
+ end
+
+ it "does not return empty string if the onebox renders successfully" do
+ expect(Boards::OneboxHandler.handle(board.url, { id: board.id })).not_to eq("")
+ end
+
+ it "renders emoji codes in the board name as Unicode" do
+ board.update!(name: "Roadmap :rocket:")
+
+ onebox_html = Boards::OneboxHandler.handle(board.url, { id: board.id })
+
+ expect(onebox_html).to include("Roadmap πŸš€")
+ expect(onebox_html).not_to include(":rocket:")
+ end
+
+ it "renders emoji codes in column titles as Unicode" do
+ column.update!(title: "Todo :rocket:")
+
+ onebox_html = Boards::OneboxHandler.handle(board.url, { id: board.id })
+
+ expect(onebox_html).to include("Todo πŸš€")
+ expect(onebox_html).not_to include(":rocket:")
+ end
+
+ it "has the correct HTML structure" do
+ board.update!(tag_ids: [tag_1.id, tag_2.id], category_ids: [category.id])
+
+ onebox_html = Boards::OneboxHandler.handle(board.url, { id: board.id })
+
+ expect(onebox_html).to have_tag("aside", with: { class: "onebox" })
+
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "discourse-boards-board-card__name",
+ href: board.url,
+ },
+ seen: board.name,
+ )
+
+ expect(onebox_html).to have_tag(
+ "div",
+ with: {
+ class: "discourse-boards-board-card__constraints",
+ },
+ )
+ expect(onebox_html).to have_tag("div", with: { class: "list-tags" })
+
+ board.tags.each do |tag|
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "hashtag-cooked",
+ "data-slug": tag.name,
+ },
+ seen: tag.name,
+ )
+ end
+
+ board.categories.each do |board_category|
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "hashtag-cooked",
+ "data-slug": board_category.slug,
+ },
+ seen: board_category.name,
+ )
+ end
+
+ expect(onebox_html).to have_tag(
+ "div",
+ with: {
+ class: "discourse-boards-board-card__columns",
+ },
+ )
+
+ board.columns.each do |board_column|
+ expect(onebox_html).to have_tag(
+ "span",
+ with: {
+ class: "discourse-boards-column-pill",
+ },
+ seen: board_column.title,
+ )
+ end
+
+ expect(onebox_html).to have_tag(
+ "a",
+ with: {
+ class: "discourse-boards-board-card__creator discourse-boards-badge trigger-user-card",
+ "data-user-card": admin.username,
+ },
+ seen: I18n.t("boards.onebox.created_by", username: admin.display_name),
+ )
+
+ expect(onebox_html).to have_tag(
+ "span",
+ with: {
+ class: "discourse-boards-badge",
+ },
+ seen: I18n.t("boards.onebox.column_count", count: board.columns.count),
+ )
+ end
+
+ context "when the board is restricted" do
+ fab!(:private_group, :group)
+
+ before do
+ board.access_control_lists.destroy_all
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [private_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [private_group],
+ )
+ end
+
+ it "returns an empty string" do
+ expect(Boards::OneboxHandler.handle(board.url, { id: board.id })).to eq("")
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/lib/guardian_extensions_spec.rb b/plugins/boards/spec/lib/guardian_extensions_spec.rb
new file mode 100644
index 00000000000..d033e92a810
--- /dev/null
+++ b/plugins/boards/spec/lib/guardian_extensions_spec.rb
@@ -0,0 +1,133 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::GuardianExtensions do
+ fab!(:admin)
+ fab!(:creator, :user)
+ fab!(:reader, :user)
+ fab!(:writer, :user)
+ fab!(:outsider, :user)
+ fab!(:member) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:read_group, :group)
+ fab!(:write_group, :group)
+ let(:anonymous_guardian) { Guardian.new }
+
+ before do
+ enable_current_plugin
+
+ read_group.add(reader)
+ write_group.add(writer)
+ end
+
+ describe "#can_read_boards_board?" do
+ it "denies read to non-editors when no read or write groups are set" do
+ board = Boards::Board.create!(name: "Roadmap", slug: "roadmap")
+
+ expect(reader.guardian.can_read_boards_board?(board)).to be_falsey
+ expect(outsider.guardian.can_read_boards_board?(board)).to be_falsey
+ expect(anonymous_guardian.can_read_boards_board?(board)).to be_falsey
+ end
+
+ it "does not allow anonymous users to read when read_group_ids are set" do
+ board = Boards::Board.create!(name: "Roadmap", slug: "roadmap")
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ expect(anonymous_guardian.can_read_boards_board?(board)).to be_falsey
+ end
+
+ it "grants read through read groups" do
+ board = Boards::Board.create!(name: "Roadmap", slug: "roadmap")
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+
+ expect(reader.guardian.can_read_boards_board?(board)).to be_truthy
+ expect(outsider.guardian.can_read_boards_board?(board)).to be_falsey
+ end
+
+ it "returns true when the user can write" do
+ board = Boards::Board.create!(name: "Operations", slug: "operations")
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+
+ expect(writer.guardian.can_read_boards_board?(board)).to be_truthy
+ end
+
+ it "grants public read to anonymous and logged in users via the anonymous and trust level 0 groups" do
+ board = Boards::Board.create!(name: "Public", slug: "public")
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [
+ Group::AUTO_GROUPS[:anonymous_users],
+ Group::AUTO_GROUPS[:logged_in_users],
+ ],
+ )
+
+ expect(anonymous_guardian.can_read_boards_board?(board)).to be_truthy
+ expect(member.guardian.can_read_boards_board?(board)).to be_truthy
+ end
+
+ it "grants members-only read via logged in users while excluding anonymous users" do
+ board = Boards::Board.create!(name: "Members", slug: "members")
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [Group::AUTO_GROUPS[:logged_in_users]],
+ )
+
+ expect(member.guardian.can_read_boards_board?(board)).to be_truthy
+ expect(anonymous_guardian.can_read_boards_board?(board)).to be_falsey
+ end
+ end
+
+ describe "#can_write_boards_board?" do
+ it "grants write through write groups" do
+ board = Boards::Board.create!(name: "Operations", slug: "operations")
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+
+ expect(writer.guardian.can_write_boards_board?(board)).to eq(true)
+ expect(outsider.guardian.can_write_boards_board?(board)).to eq(false)
+ end
+
+ it "does not grant write to admins without an edit or manage ACL" do
+ board = Boards::Board.create!(name: "Engineering", slug: "engineering")
+
+ expect(admin.guardian.can_write_boards_board?(board)).to eq(false)
+ end
+
+ it "does not allow creator special priveleges to write if they are not in a write group" do
+ board = Boards::Board.create!(name: "Support", slug: "support", created_by_id: creator.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+
+ expect(creator.guardian.can_write_boards_board?(board)).to eq(false)
+
+ write_group.add(creator)
+ creator.reload
+
+ expect(creator.guardian.can_write_boards_board?(board)).to eq(true)
+ end
+ end
+end
diff --git a/plugins/boards/spec/lib/statistics_spec.rb b/plugins/boards/spec/lib/statistics_spec.rb
new file mode 100644
index 00000000000..8ae05bc1adb
--- /dev/null
+++ b/plugins/boards/spec/lib/statistics_spec.rb
@@ -0,0 +1,326 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Statistics do
+ fab!(:admin)
+ fab!(:user_one, :user)
+ fab!(:user_two, :user)
+ fab!(:user_three, :user)
+
+ let(:reference_time) { Time.zone.parse("2026-06-09 12:00:00") }
+
+ before { enable_current_plugin }
+
+ describe ".total_boards" do
+ subject(:stats) { described_class.total_boards }
+
+ before do
+ freeze_time(reference_time) do
+ Fabricate(:boards_board, name: "Total Boards Board", created_by: admin)
+ end
+ end
+
+ it "returns the total number of boards" do
+ freeze_time(reference_time) { expect(stats).to eq({ count: 1 }) }
+ end
+ end
+
+ describe ".created_boards" do
+ subject(:stats) { described_class.created_boards }
+
+ before do
+ freeze_time(reference_time) do
+ Fabricate(
+ :boards_board,
+ name: "Recent Board",
+ created_by: admin,
+ created_at: reference_time - 6.hours,
+ )
+ Fabricate(
+ :boards_board,
+ name: "Week Board",
+ created_by: admin,
+ created_at: reference_time - 4.days,
+ )
+ Fabricate(
+ :boards_board,
+ name: "Month Board",
+ created_by: admin,
+ created_at: reference_time - 15.days,
+ )
+ Fabricate(
+ :boards_board,
+ name: "Previous Month Board",
+ created_by: admin,
+ created_at: reference_time - 45.days,
+ )
+ Fabricate(
+ :boards_board,
+ name: "Old Board",
+ created_by: admin,
+ created_at: reference_time - 70.days,
+ )
+ end
+ end
+
+ it "returns counts for each time bucket" do
+ freeze_time(reference_time) do
+ expect(stats).to eq({ last_day: 1, "7_days": 2, "30_days": 3, previous_30_days: 1 })
+ end
+ end
+ end
+
+ describe ".viewed_boards" do
+ subject(:stats) { described_class.viewed_boards }
+
+ fab!(:recent_board) { Fabricate(:boards_board, name: "Viewed Recent", created_by: admin) }
+ fab!(:week_board) { Fabricate(:boards_board, name: "Viewed Week", created_by: admin) }
+ fab!(:previous_month_board) do
+ Fabricate(:boards_board, name: "Viewed Previous Month", created_by: admin)
+ end
+
+ before do
+ freeze_time(reference_time) do
+ Fabricate(
+ :boards_board_history,
+ board: recent_board,
+ acting_user: user_one,
+ action: :board_viewed,
+ created_at: reference_time - 6.hours,
+ )
+ Fabricate(
+ :boards_board_history,
+ board: recent_board,
+ acting_user: user_two,
+ action: :board_viewed,
+ created_at: reference_time - 3.days,
+ )
+ Fabricate(
+ :boards_board_history,
+ board: week_board,
+ acting_user: user_two,
+ action: :board_viewed,
+ created_at: reference_time - 4.days,
+ )
+ Fabricate(
+ :boards_board_history,
+ board: previous_month_board,
+ acting_user: user_three,
+ action: :board_viewed,
+ created_at: reference_time - 45.days,
+ )
+ Fabricate(
+ :boards_board_history,
+ board: recent_board,
+ acting_user: user_one,
+ action: :board_renamed,
+ created_at: reference_time - 6.hours,
+ )
+ end
+ end
+
+ it "returns counts for each time bucket" do
+ freeze_time(reference_time) do
+ expect(stats).to eq(
+ { last_day: 1, "7_days": 2, "30_days": 2, previous_30_days: 1, count: 3 },
+ )
+ end
+ end
+ end
+
+ describe ".active_boards" do
+ subject(:stats) { described_class.active_boards }
+
+ fab!(:recent_board) { Fabricate(:boards_board, name: "Active Recent", created_by: admin) }
+ fab!(:month_board) { Fabricate(:boards_board, name: "Active Month", created_by: admin) }
+ fab!(:previous_month_board) do
+ Fabricate(:boards_board, name: "Active Previous Month", created_by: admin)
+ end
+ fab!(:column) { Fabricate(:boards_column, board: recent_board) }
+ fab!(:recent_card) { Fabricate(:boards_card, board: recent_board, column:) }
+ fab!(:month_card) do
+ Fabricate(
+ :boards_card,
+ board: month_board,
+ column: Fabricate(:boards_column, board: month_board),
+ )
+ end
+ fab!(:previous_month_card) do
+ Fabricate(
+ :boards_card,
+ board: previous_month_board,
+ column: Fabricate(:boards_column, board: previous_month_board),
+ )
+ end
+
+ before do
+ freeze_time(reference_time) do
+ Fabricate(
+ :boards_card_history,
+ board: recent_board,
+ card: recent_card,
+ acting_user: user_one,
+ action: :card_created,
+ created_at: reference_time - 6.hours,
+ )
+ Fabricate(
+ :boards_card_history,
+ board: recent_board,
+ card: recent_card,
+ acting_user: user_one,
+ action: :card_edited,
+ created_at: reference_time - 4.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board: month_board,
+ card: month_card,
+ acting_user: user_two,
+ action: :card_moved,
+ created_at: reference_time - 15.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board: previous_month_board,
+ card: previous_month_card,
+ acting_user: user_three,
+ action: :card_deleted,
+ created_at: reference_time - 45.days,
+ )
+ Fabricate(
+ :boards_board_history,
+ board: recent_board,
+ acting_user: user_one,
+ action: :board_renamed,
+ created_at: reference_time - 6.hours,
+ )
+ end
+ end
+
+ it "returns counts for each time bucket" do
+ freeze_time(reference_time) do
+ expect(stats).to eq(
+ { last_day: 1, "7_days": 1, "30_days": 2, previous_30_days: 1, count: 3 },
+ )
+ end
+ end
+ end
+
+ describe ".active_users" do
+ subject(:stats) { described_class.active_users }
+
+ fab!(:board) { Fabricate(:boards_board, name: "Active Users Board", created_by: admin) }
+ fab!(:column) { Fabricate(:boards_column, board:) }
+ fab!(:card) { Fabricate(:boards_card, board:, column:) }
+
+ before do
+ freeze_time(reference_time) do
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_one,
+ action: :card_viewed,
+ created_at: reference_time - 6.hours,
+ )
+ Fabricate(
+ :boards_board_history,
+ board:,
+ acting_user: user_two,
+ action: :board_viewed,
+ created_at: reference_time - 4.days,
+ )
+ Fabricate(
+ :boards_board_history,
+ board:,
+ acting_user: user_one,
+ action: :board_viewed,
+ created_at: reference_time - 15.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_three,
+ action: :card_viewed,
+ created_at: reference_time - 45.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_one,
+ action: :card_created,
+ created_at: reference_time - 6.hours,
+ )
+ end
+ end
+
+ it "returns counts for each time bucket" do
+ freeze_time(reference_time) do
+ expect(stats).to eq(
+ { last_day: 1, "7_days": 2, "30_days": 2, previous_30_days: 1, count: 3 },
+ )
+ end
+ end
+ end
+
+ describe ".participating_users" do
+ subject(:stats) { described_class.participating_users }
+
+ fab!(:board) { Fabricate(:boards_board, name: "Participating Users Board", created_by: admin) }
+ fab!(:column) { Fabricate(:boards_column, board:) }
+ fab!(:card) { Fabricate(:boards_card, board:, column:) }
+
+ before do
+ freeze_time(reference_time) do
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_one,
+ action: :card_created,
+ created_at: reference_time - 6.hours,
+ )
+ Fabricate(
+ :boards_board_history,
+ board:,
+ acting_user: user_two,
+ action: :board_created,
+ created_at: reference_time - 4.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_one,
+ action: :card_moved,
+ created_at: reference_time - 15.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_three,
+ action: :card_edited,
+ created_at: reference_time - 45.days,
+ )
+ Fabricate(
+ :boards_card_history,
+ board:,
+ card:,
+ acting_user: user_one,
+ action: :card_viewed,
+ created_at: reference_time - 6.hours,
+ )
+ end
+ end
+
+ it "returns counts for each time bucket" do
+ freeze_time(reference_time) do
+ expect(stats).to eq(
+ { last_day: 1, "7_days": 2, "30_days": 2, previous_30_days: 1, count: 3 },
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/models/boards/board_spec.rb b/plugins/boards/spec/models/boards/board_spec.rb
new file mode 100644
index 00000000000..07cc8dd7ff9
--- /dev/null
+++ b/plugins/boards/spec/models/boards/board_spec.rb
@@ -0,0 +1,280 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Board do
+ before { enable_current_plugin }
+
+ describe "#topic_matches?" do
+ fab!(:category)
+ fab!(:tag)
+
+ it "matches topic by category_ids" do
+ board = described_class.create!(name: "B", slug: "b", category_ids: [category.id])
+ topic = Fabricate(:topic, category: category)
+
+ expect(board.topic_matches?(topic)).to eq(true)
+ end
+
+ it "does not match topic in different category" do
+ board = described_class.create!(name: "B", slug: "b", category_ids: [category.id])
+ topic = Fabricate(:topic, category: Fabricate(:category))
+
+ expect(board.topic_matches?(topic)).to eq(false)
+ end
+
+ it "matches topic by tag_ids" do
+ board = described_class.create!(name: "B", slug: "b", tag_ids: [tag.id])
+ topic = Fabricate(:topic, tags: [tag])
+
+ expect(board.topic_matches?(topic)).to eq(true)
+ end
+
+ it "does not match topic without required tags" do
+ board = described_class.create!(name: "B", slug: "b", tag_ids: [tag.id])
+ topic = Fabricate(:topic)
+
+ expect(board.topic_matches?(topic)).to eq(false)
+ end
+
+ it "requires both category and tag match when both are set" do
+ board =
+ described_class.create!(
+ name: "B",
+ slug: "b",
+ category_ids: [category.id],
+ tag_ids: [tag.id],
+ )
+ topic_with_both = Fabricate(:topic, category: category, tags: [tag])
+ topic_category_only = Fabricate(:topic, category: category)
+ topic_tag_only = Fabricate(:topic, tags: [tag])
+
+ expect(board.topic_matches?(topic_with_both)).to eq(true)
+ expect(board.topic_matches?(topic_category_only)).to eq(false)
+ expect(board.topic_matches?(topic_tag_only)).to eq(false)
+ end
+
+ it "returns false when both category_ids and tag_ids are empty" do
+ board = described_class.create!(name: "B", slug: "b")
+ topic = Fabricate(:topic)
+
+ expect(board.topic_matches?(topic)).to eq(false)
+ end
+ end
+
+ describe "#topic_will_match_after_mutation?" do
+ fab!(:board_tag, :tag) { Fabricate(:tag, name: "board-filter") }
+ fab!(:sibling_tag, :tag) { Fabricate(:tag, name: "sibling-column") }
+ fab!(:target_tag, :tag) { Fabricate(:tag, name: "target-column") }
+ fab!(:board) { Fabricate(:boards_board, tag_ids: [board_tag.id]) }
+ fab!(:sibling_column) { Fabricate(:boards_column, board:, tag: sibling_tag) }
+ fab!(:target_column) { Fabricate(:boards_column, board:) }
+
+ context "when the target column is untagged" do
+ fab!(:topic) { Fabricate(:topic, tags: [sibling_tag]) }
+
+ before { board.update!(tag_ids: [sibling_tag.id]) }
+
+ it "predicts that all board column tags will be removed" do
+ expect(board.topic_will_match_after_mutation?(topic, target_column)).to eq(false)
+ end
+ end
+
+ context "when the target column has a tag" do
+ fab!(:topic) { Fabricate(:topic, tags: [sibling_tag]) }
+
+ before do
+ board.update!(tag_ids: [target_tag.id])
+ target_column.update!(tag_id: target_tag.id)
+ end
+
+ it "predicts that the target tag will replace sibling column tags" do
+ expect(board.topic_will_match_after_mutation?(topic, target_column)).to eq(true)
+ end
+
+ it "does not retain the replaced sibling tag" do
+ board.update!(tag_ids: [sibling_tag.id])
+
+ expect(board.topic_will_match_after_mutation?(topic, target_column)).to eq(false)
+ end
+ end
+ end
+
+ describe "#tags and #categories" do
+ fab!(:category_a) { Fabricate(:category, name: "alpha-cat") }
+ fab!(:category_b) { Fabricate(:category, name: "beta-cat") }
+ fab!(:tag_a) { Fabricate(:tag, name: "alpha") }
+ fab!(:tag_b) { Fabricate(:tag, name: "beta") }
+
+ it "returns tags ordered by name" do
+ board = described_class.create!(name: "B", slug: "b", tag_ids: [tag_b.id, tag_a.id])
+
+ expect(board.tags).to eq([tag_a, tag_b])
+ end
+
+ it "returns categories ordered by name" do
+ board =
+ described_class.create!(name: "B", slug: "b", category_ids: [category_b.id, category_a.id])
+
+ expect(board.categories).to eq([category_a, category_b])
+ end
+
+ it "returns empty arrays when nothing is set" do
+ board = described_class.create!(name: "B", slug: "b")
+
+ expect(board.tags).to eq([])
+ expect(board.categories).to eq([])
+ end
+
+ it "memoizes the result so repeated access does not requery" do
+ board = described_class.create!(name: "B", slug: "b", tag_ids: [tag_a.id])
+ board.tags
+
+ queries = track_sql_queries { 5.times { board.tags } }
+ expect(queries).to be_empty
+ end
+
+ it "resets memoization on reload" do
+ board = described_class.create!(name: "B", slug: "b", tag_ids: [tag_a.id])
+ expect(board.tags).to eq([tag_a])
+
+ board.update!(tag_ids: [tag_b.id])
+ board.reload
+
+ expect(board.tags).to eq([tag_b])
+ end
+ end
+
+ describe ".preload_tags and .preload_categories" do
+ fab!(:tag_a) { Fabricate(:tag, name: "alpha") }
+ fab!(:tag_b) { Fabricate(:tag, name: "beta") }
+ fab!(:category_a) { Fabricate(:category, name: "alpha-cat") }
+ fab!(:category_b) { Fabricate(:category, name: "beta-cat") }
+
+ it "preloads tags for many boards in a single query" do
+ board_a = described_class.create!(name: "A", slug: "a", tag_ids: [tag_a.id])
+ board_b = described_class.create!(name: "B", slug: "b", tag_ids: [tag_a.id, tag_b.id])
+
+ boards = [board_a, board_b]
+ described_class.preload_tags(boards)
+
+ queries = track_sql_queries { boards.each(&:tags) }
+ expect(queries).to be_empty
+ expect(board_a.tags).to eq([tag_a])
+ expect(board_b.tags).to eq([tag_a, tag_b])
+ end
+
+ it "preloads categories for many boards in a single query" do
+ board_a = described_class.create!(name: "A", slug: "a", category_ids: [category_a.id])
+ board_b =
+ described_class.create!(name: "B", slug: "b", category_ids: [category_a.id, category_b.id])
+
+ boards = [board_a, board_b]
+ described_class.preload_categories(boards)
+
+ queries = track_sql_queries { boards.each(&:categories) }
+ expect(queries).to be_empty
+ expect(board_a.categories).to eq([category_a])
+ expect(board_b.categories).to eq([category_a, category_b])
+ end
+
+ it "handles empty input and boards without ids" do
+ expect(described_class.preload_tags([])).to eq([])
+
+ board = described_class.create!(name: "B", slug: "b")
+ described_class.preload_tags([board])
+ described_class.preload_categories([board])
+
+ expect(board.tags).to eq([])
+ expect(board.categories).to eq([])
+ end
+ end
+
+ describe "#all_matching_columns" do
+ fab!(:category)
+ fab!(:tag_a) { Fabricate(:tag, name: "alpha") }
+ fab!(:tag_b) { Fabricate(:tag, name: "beta") }
+
+ it "matches columns by tag_id" do
+ board = described_class.create!(name: "B", slug: "b", category_ids: [category.id])
+ col_a = board.columns.create!(title: "A", position: 0, tag_id: tag_a.id)
+ col_b = board.columns.create!(title: "B", position: 1, tag_id: tag_b.id)
+
+ topic = Fabricate(:topic, category: category, tags: [tag_a])
+ expect(board.all_matching_columns(topic)).to eq([col_a])
+
+ topic2 = Fabricate(:topic, category: category, tags: [tag_a, tag_b])
+ expect(board.all_matching_columns(topic2)).to contain_exactly(col_a, col_b)
+ end
+
+ it "does not include unconstrained columns in matching results" do
+ board = described_class.create!(name: "B", slug: "b", category_ids: [category.id])
+ board.columns.create!(title: "Catch", position: 0, tag_id: nil)
+ col_a = board.columns.create!(title: "A", position: 1, tag_id: tag_a.id)
+
+ topic = Fabricate(:topic, category: category, tags: [tag_a])
+ expect(board.all_matching_columns(topic)).to eq([col_a])
+
+ topic2 = Fabricate(:topic, category: category)
+ expect(board.all_matching_columns(topic2)).to eq([])
+ end
+ end
+
+ describe "can_be_oneboxed?" do
+ fab!(:boards_board)
+
+ context "when the site is login_required" do
+ before { SiteSetting.login_required = true }
+
+ it "returns true for boards viewable by logged in users" do
+ Fabricate(
+ :access_control_list_with_groups,
+ target: boards_board,
+ permission: "view",
+ group_ids: [Group::AUTO_GROUPS[:logged_in_users]],
+ )
+ boards_board.reload
+
+ expect(boards_board.can_be_oneboxed?).to eq(true)
+ end
+
+ it "returns false for boards not viewable by anonymous users" do
+ expect(boards_board.can_be_oneboxed?).to eq(false)
+ end
+ end
+
+ context "when the site is not login_required" do
+ before { SiteSetting.login_required = false }
+
+ it "returns true for boards viewable by anonymous users" do
+ Fabricate(
+ :access_control_list_with_groups,
+ target: boards_board,
+ permission: "view",
+ group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ boards_board.reload
+
+ expect(boards_board.can_be_oneboxed?).to eq(true)
+ end
+
+ it "returns false for boards not viewable by anonymous users" do
+ expect(boards_board.can_be_oneboxed?).to eq(false)
+ end
+ end
+ end
+
+ describe ".banned_acl" do
+ it "bans the everyone pseudogroup for every permission" do
+ %w[view edit manage].each do |permission|
+ acl = { type: :group, id: Group::AUTO_GROUPS[:everyone], permission: permission }
+
+ expect(described_class.acl_is_banned?(acl)).to eq(true)
+ end
+ end
+
+ it "allows the logged_in_users pseudogroup to view" do
+ acl = { type: :group, id: Group::AUTO_GROUPS[:logged_in_users], permission: "view" }
+
+ expect(described_class.acl_is_banned?(acl)).to eq(false)
+ end
+ end
+end
diff --git a/plugins/boards/spec/models/boards/card_spec.rb b/plugins/boards/spec/models/boards/card_spec.rb
new file mode 100644
index 00000000000..458f8462d44
--- /dev/null
+++ b/plugins/boards/spec/models/boards/card_spec.rb
@@ -0,0 +1,316 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Card do
+ fab!(:admin)
+ fab!(:category)
+ fab!(:tag)
+ fab!(:topic) { Fabricate(:topic, category: category) }
+
+ before { enable_current_plugin }
+
+ fab!(:board) { Boards::Board.create!(name: "Test", slug: "test-card", created_by_id: admin.id) }
+ fab!(:column) { board.columns.create!(title: "Col", position: 0) }
+
+ describe "validations" do
+ it "is valid as a floater with title and column" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ title: "A task",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ expect(card).to be_valid
+ end
+
+ it "is valid as a topic card with topic and column" do
+ card =
+ board.cards.build(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ expect(card).to be_valid
+ end
+
+ it "requires title for floater cards" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ title: nil,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ expect(card).not_to be_valid
+ expect(card.errors[:title]).to include("can't be blank")
+ end
+
+ it "requires topic_id for topic cards" do
+ card =
+ board.cards.build(
+ card_type: :topic,
+ topic_id: nil,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ expect(card).not_to be_valid
+ expect(card.errors[:topic_id]).to include("can't be blank")
+ end
+
+ it "normalizes card_type to topic when topic_id is present" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card.valid?
+ expect(card.card_type).to eq("topic")
+ end
+
+ it "requires column_id for floater cards" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ title: "Orphan",
+ column_id: nil,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ expect(card).not_to be_valid
+ expect(card.errors[:column_id]).to include("can't be blank")
+ end
+
+ it "requires column_id for topic cards" do
+ card =
+ board.cards.build(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: nil,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ expect(card).not_to be_valid
+ expect(card.errors[:column_id]).to include("can't be blank")
+ end
+
+ it "requires position" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ title: "No position",
+ column_id: column.id,
+ position: nil,
+ created_by_id: admin.id,
+ )
+ expect(card).not_to be_valid
+ expect(card.errors[:position]).to include("can't be blank")
+ end
+ end
+
+ describe "normalize_card_type" do
+ it "auto-sets card_type to topic when topic_id is present" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card.valid?
+ expect(card.card_type).to eq("topic")
+ end
+
+ it "does not change card_type when topic_id is blank" do
+ card =
+ board.cards.build(
+ card_type: :floater,
+ title: "Floater",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card.valid?
+ expect(card.card_type).to eq("floater")
+ end
+ end
+
+ describe "scopes" do
+ it ".with_column returns only cards with a column" do
+ in_col =
+ board.cards.create!(
+ card_type: :floater,
+ title: "In column",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect(described_class.with_column.pluck(:id)).to eq([in_col.id])
+ end
+
+ it ".ordered sorts by position then id" do
+ card_b =
+ board.cards.create!(
+ card_type: :floater,
+ title: "B",
+ column_id: column.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ card_a =
+ board.cards.create!(
+ card_type: :floater,
+ title: "A",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect(described_class.ordered.pluck(:id)).to eq([card_a.id, card_b.id])
+ end
+ end
+
+ describe ".normalize_tag_ids!" do
+ it "rejects malformed tag ids" do
+ expect { described_class.normalize_tag_ids!(["#{tag.id}abc"]) }.to raise_error(
+ Discourse::InvalidParameters,
+ )
+ end
+ end
+
+ describe ".ordered_tags" do
+ it "omits missing tags" do
+ expect(described_class.ordered_tags([tag.id, tag.id + 1000])).to eq([tag])
+ end
+ end
+
+ describe "#tags" do
+ fab!(:tag_a) { Fabricate(:tag, name: "alpha") }
+ fab!(:tag_b) { Fabricate(:tag, name: "beta") }
+
+ it "returns tags ordered by name" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "T",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ tag_ids: [tag_b.id, tag_a.id],
+ )
+
+ expect(card.tags).to eq([tag_a, tag_b])
+ end
+
+ it "memoizes the result" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "T",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ tag_ids: [tag_a.id],
+ )
+ card.tags
+
+ queries = track_sql_queries { 5.times { card.tags } }
+ expect(queries).to be_empty
+ end
+ end
+
+ describe ".preload_tags" do
+ fab!(:tag_a) { Fabricate(:tag, name: "alpha") }
+ fab!(:tag_b) { Fabricate(:tag, name: "beta") }
+
+ it "loads tags for many cards in a single query" do
+ card_a =
+ board.cards.create!(
+ card_type: :floater,
+ title: "A",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ tag_ids: [tag_a.id],
+ )
+ card_b =
+ board.cards.create!(
+ card_type: :floater,
+ title: "B",
+ column_id: column.id,
+ position: 1,
+ created_by_id: admin.id,
+ tag_ids: [tag_a.id, tag_b.id],
+ )
+
+ cards = [card_a, card_b]
+ described_class.preload_tags(cards)
+
+ queries = track_sql_queries { cards.each(&:tags) }
+ expect(queries).to be_empty
+ expect(card_a.tags).to eq([tag_a])
+ expect(card_b.tags).to eq([tag_a, tag_b])
+ end
+
+ it "handles empty input and cards without tags" do
+ expect(described_class.preload_tags([])).to eq([])
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "T",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ described_class.preload_tags([card])
+
+ expect(card.tags).to eq([])
+ end
+ end
+
+ describe "#recency_at" do
+ it "uses the later of topic bumped_at and column_changed_at for topic cards" do
+ bumped_at = 2.days.ago
+ column_changed_at = 1.day.ago
+ topic.update_columns(bumped_at: bumped_at)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ column_changed_at: column_changed_at,
+ created_by_id: admin.id,
+ )
+
+ expect(card.reload.recency_at.to_i).to eq(column_changed_at.to_i)
+ end
+
+ it "uses the later of updated_at and column_changed_at for floater cards" do
+ column_changed_at = 3.days.ago
+ updated_at = 2.hours.ago
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Recent floater",
+ column_id: column.id,
+ position: 0,
+ column_changed_at: column_changed_at,
+ created_by_id: admin.id,
+ )
+ card.update_columns(updated_at: updated_at)
+
+ expect(card.reload.recency_at.to_i).to eq(updated_at.to_i)
+ end
+ end
+end
diff --git a/plugins/boards/spec/models/boards/column_spec.rb b/plugins/boards/spec/models/boards/column_spec.rb
new file mode 100644
index 00000000000..9a9000cac49
--- /dev/null
+++ b/plugins/boards/spec/models/boards/column_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Column do
+ fab!(:admin)
+
+ before { enable_current_plugin }
+
+ fab!(:board) { Boards::Board.create!(name: "Test", slug: "test-column", created_by_id: admin.id) }
+
+ it "defaults to priority sorting" do
+ column = board.columns.create!(title: "Backlog", position: 0)
+
+ expect(column.default_sort).to eq("priority")
+ expect(column).to be_priority
+ end
+
+ it "supports recency sorting" do
+ column = board.columns.create!(title: "Done", position: 0, default_sort: "recency")
+
+ expect(column.default_sort).to eq("recency")
+ expect(column).to be_recency
+ end
+
+ it "accepts a bare hex or no color, but rejects malformed values" do
+ expect(board.columns.build(title: "A", position: 0, color: "1A2B3C")).to be_valid
+ expect(board.columns.build(title: "B", position: 1, color: "f0a")).to be_valid
+ expect(board.columns.build(title: "C", position: 2, color: nil)).to be_valid
+
+ # Stored without a leading "#", and the old named keys are no longer valid.
+ expect(board.columns.build(title: "D", position: 3, color: "#1A2B3C")).not_to be_valid
+ expect(board.columns.build(title: "E", position: 4, color: "purple")).not_to be_valid
+ end
+end
diff --git a/plugins/boards/spec/requests/boards/boards_controller_spec.rb b/plugins/boards/spec/requests/boards/boards_controller_spec.rb
new file mode 100644
index 00000000000..7f3ecee0ebe
--- /dev/null
+++ b/plugins/boards/spec/requests/boards/boards_controller_spec.rb
@@ -0,0 +1,764 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Api::BoardsController do
+ fab!(:admin)
+ fab!(:reader, :user)
+ fab!(:writer, :user)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:read_group, :group)
+ fab!(:write_group, :group)
+ fab!(:manage_group, :group)
+ fab!(:category) { Fabricate(:category, name: "General") }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ read_group.add(reader)
+ write_group.add(writer)
+ manage_group.add(manager)
+ end
+
+ describe "GET /boards/api/boards" do
+ it "returns only boards visible to the current user" do
+ other_group = Fabricate(:group)
+
+ visible = Fabricate(:boards_board, name: "Visible", slug: "visible", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: visible,
+ permission: "view",
+ groups: [read_group],
+ )
+ hidden = Fabricate(:boards_board, name: "Hidden", slug: "hidden", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: hidden,
+ permission: "view",
+ groups: [other_group],
+ )
+
+ visible.columns.create!(title: "One", position: 0)
+
+ sign_in(reader)
+ get "/boards/api/boards.json"
+
+ expect(response.status).to eq(200)
+ slugs = response.parsed_body["boards"].map { |b| b["slug"] }
+ expect(slugs).to contain_exactly("visible")
+ end
+
+ it "returns all boards for admins" do
+ other_group = Fabricate(:group)
+
+ private_board = Fabricate(:boards_board, name: "Private", slug: "private", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: private_board,
+ permission: "view",
+ groups: [other_group],
+ )
+
+ sign_in(admin)
+ get "/boards/api/boards.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["boards"].length).to eq(1)
+ end
+
+ it "limits boards to the requested permissions" do
+ board_editable =
+ Fabricate(:boards_board, name: "Editable", slug: "editable", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board_editable,
+ permission: "edit",
+ groups: [write_group],
+ )
+ board_view_only =
+ Fabricate(:boards_board, name: "View Only", slug: "view-only", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board_view_only,
+ permission: "view",
+ groups: [write_group],
+ )
+
+ sign_in(writer)
+ get "/boards/api/boards.json", params: { allowed_permissions: "edit" }
+
+ expect(response.status).to eq(200)
+ slugs = response.parsed_body["boards"].map { |b| b["slug"] }
+ expect(slugs).to contain_exactly("editable")
+ end
+ end
+
+ describe "GET /boards/api/boards/available" do
+ fab!(:topic)
+ fab!(:board) { Fabricate(:boards_board, name: "Product", created_by: admin) }
+ fab!(:backlog_column) { Fabricate(:boards_column, board:, title: "Backlog", position: 0) }
+ fab!(:done_column) { Fabricate(:boards_column, board:, title: "Done", position: 1) }
+ fab!(:topic_card) { Fabricate(:boards_topic_card, board:, column: backlog_column, topic:) }
+ fab!(:other_board) { Fabricate(:boards_board, name: "Roadmap", created_by: admin) }
+ fab!(:other_column) { Fabricate(:boards_column, board: other_board, title: "Next") }
+
+ before do
+ [board, other_board].each do |visible_board|
+ Fabricate(
+ :access_control_list_with_groups,
+ target: visible_board,
+ permission: "view",
+ groups: [read_group],
+ )
+ end
+ end
+
+ it "returns the topic's board and column memberships" do
+ sign_in(reader)
+
+ get "/boards/api/boards/available.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(200)
+ boards = response.parsed_body["boards"].index_by { |item| item["id"] }
+
+ expect(boards[board.id]["topic_is_member"]).to eq(true)
+ expect(
+ boards[board.id]["columns"].to_h { |column| [column["id"], column["topic_is_member"]] },
+ ).to eq(backlog_column.id => true, done_column.id => false)
+ expect(boards[other_board.id]["topic_is_member"]).to eq(false)
+ expect(boards[other_board.id]["columns"].sole["topic_is_member"]).to eq(false)
+ end
+
+ it "denies access when the user cannot see the topic" do
+ private_category = Fabricate(:private_category, group: write_group)
+ private_topic = Fabricate(:topic, category: private_category)
+ sign_in(reader)
+
+ get "/boards/api/boards/available.json", params: { topic_id: private_topic.id }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "GET /boards/api/boards/:id" do
+ it "returns full board payload with columns and cards" do
+ topic = Fabricate(:topic, category: category)
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Sprint",
+ slug: "sprint",
+ show_tags: true,
+ card_style: "detailed",
+ category_ids: [category.id],
+ created_by: admin,
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ col = board.columns.create!(title: "Backlog", position: 0, icon: "list")
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(200)
+ body = response.parsed_body
+
+ board_data = body["board"]
+ expect(board_data["name"]).to eq("Sprint")
+ expect(board_data["can_write"]).to eq(true)
+ expect(board_data["show_tags"]).to eq(true)
+ expect(board_data["card_style"]).to eq("detailed")
+
+ columns = body["columns"]
+ expect(columns.length).to eq(1)
+ expect(columns[0]["title"]).to eq("Backlog")
+ expect(columns[0]["icon"]).to eq("list")
+ expect(columns[0]["default_sort"]).to eq("priority")
+ expect(columns[0]["cards"].length).to eq(1)
+
+ card = columns[0]["cards"][0]
+ expect(card["card_type"]).to eq("topic")
+ expect(card["topic"]["title"]).to eq(topic.title)
+ expect(card["topic"]["slug"]).to eq(topic.slug)
+ end
+
+ it "hides restricted board and column tags from users who can read the board" do
+ hidden_tag = Fabricate(:tag, name: "security-internal")
+ visible_tag = Fabricate(:tag, name: "public-roadmap")
+ staff_tag_group =
+ Fabricate(:tag_group, name: "Staff Boards Tags", tag_names: [hidden_tag.name])
+ staff_tag_group.permissions = [
+ [Group::AUTO_GROUPS[:staff], TagGroupPermission.permission_types[:full]],
+ ]
+ staff_tag_group.save!
+
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Public Roadmap",
+ slug: "public-roadmap",
+ tag_ids: [hidden_tag.id, visible_tag.id],
+ created_by: admin,
+ )
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ board.columns.create!(title: "Visible", position: 0, tag_id: visible_tag.id)
+ board.columns.create!(title: "Hidden", position: 1, tag_id: hidden_tag.id)
+
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(200)
+ body = response.parsed_body
+
+ expect(body["board"]["tag_ids"]).to contain_exactly(visible_tag.id)
+ expect(body["board"]["tag_names"]).to contain_exactly(visible_tag.name)
+ expect(body["board"]["columns"].map { |column| column["tag_id"] }).to contain_exactly(
+ visible_tag.id,
+ nil,
+ )
+ expect(body["board"]["columns"].map { |column| column["tag_name"] }).to contain_exactly(
+ visible_tag.name,
+ nil,
+ )
+ expect(body["columns"].map { |column| column["tag_id"] }).to contain_exactly(
+ visible_tag.id,
+ nil,
+ )
+ expect(body["columns"].map { |column| column["tag_name"] }).to contain_exactly(
+ visible_tag.name,
+ nil,
+ )
+ expect(response.body).not_to include(hidden_tag.name)
+ end
+
+ it "hides restricted tags attached to floater cards from users who can read the board" do
+ hidden_tag = Fabricate(:tag, name: "staff-floater")
+ visible_tag = Fabricate(:tag, name: "public-floater")
+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Public Roadmap",
+ slug: "public-roadmap-floaters",
+ created_by: admin,
+ )
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ column = board.columns.create!(title: "Visible", position: 0)
+ board.cards.create!(
+ card_type: :floater,
+ title: "Public card",
+ tag_ids: [visible_tag.id, hidden_tag.id],
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(200)
+ card = response.parsed_body["columns"].first["cards"].first
+ expect(card["tag_ids"]).to contain_exactly(visible_tag.id)
+ expect(card["tags"].map { |tag| tag["name"] }).to contain_exactly(visible_tag.name)
+ expect(response.body).not_to include(hidden_tag.name)
+ end
+
+ it "includes can_manage for users in the manage group" do
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Test",
+ slug: "test-manage",
+ created_by: admin,
+ additional_manage_groups: [manage_group],
+ )
+ board.columns.create!(title: "Col", position: 0)
+
+ sign_in(manager)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.parsed_body["board"]["can_manage"]).to eq(true)
+ end
+
+ it "includes can_manage for admins" do
+ board = Fabricate(:boards_board, name: "Test", slug: "test-admin-manage", created_by: admin)
+ board.columns.create!(title: "Col", position: 0)
+
+ sign_in(admin)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.parsed_body["board"]["can_manage"]).to eq(true)
+ end
+
+ it "sets can_manage to false for users not in the manage group" do
+ board = Fabricate(:boards_board, name: "Test", slug: "test-nomanage", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board.columns.create!(title: "Col", position: 0)
+
+ sign_in(reader)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.parsed_body["board"]["can_manage"]).to eq(false)
+ end
+
+ it "includes the creator's username and avatar_template" do
+ board =
+ Fabricate(:boards_board, name: "Creator Test", slug: "creator-test", created_by: admin)
+ board.columns.create!(title: "Col", position: 0)
+
+ sign_in(admin)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(200)
+ created_by = response.parsed_body["board"]["created_by"]
+ expect(created_by).to be_present
+ expect(created_by["username"]).to eq(admin.username)
+ expect(created_by["avatar_template"]).to eq(admin.avatar_template)
+ end
+
+ it "includes topic details for detailed cards" do
+ topic = Fabricate(:topic, category: category)
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Detailed",
+ slug: "detailed",
+ card_style: "detailed",
+ category_ids: [category.id],
+ created_by: admin,
+ )
+ col = board.columns.create!(title: "Col", position: 0)
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+ get "/boards/api/boards/#{board.id}.json"
+
+ topic_data = response.parsed_body["columns"][0]["cards"][0]["topic"]
+ expect(topic_data["image_url"]).to be_present.or be_nil
+ expect(topic_data).to have_key("last_poster")
+ expect(topic_data["bumped_at"]).to be_present
+ expect(topic_data["category_id"]).to eq(category.id)
+ end
+
+ it "filters out topics the user cannot see" do
+ private_category = Fabricate(:private_category, group: write_group)
+ visible_topic = Fabricate(:topic, category: category)
+ private_topic = Fabricate(:topic, category: private_category)
+
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Mixed",
+ slug: "mixed",
+ category_ids: [category.id, private_category.id],
+ created_by: admin,
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ col = board.columns.create!(title: "Col", position: 0)
+
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: visible_topic.id,
+ column_id: col.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: private_topic.id,
+ column_id: col.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+
+ sign_in(reader)
+ get "/boards/api/boards/#{board.id}.json"
+
+ card_titles = response.parsed_body["columns"][0]["cards"].map { |c| c["topic"]["title"] }
+ expect(card_titles).to include(visible_topic.title)
+ expect(card_titles).not_to include(private_topic.title)
+ end
+
+ it "does not backfill cards into unconstrained columns even when the board filter matches" do
+ topic = Fabricate(:topic, category: category)
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Auto Board",
+ slug: "auto-board",
+ category_ids: [category.id],
+ created_by: admin,
+ )
+ board.columns.create!(title: "Backlog", position: 0)
+
+ sign_in(admin)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(200)
+ cards = response.parsed_body["columns"][0]["cards"]
+ expect(cards).to eq([])
+ expect(board.cards.where(topic_id: topic.id)).to be_blank
+ end
+
+ it "orders columns by recency default sort order based on computed recency_at" do
+ board =
+ Fabricate(:boards_board, name: "Recent Board", slug: "recent-board", created_by: admin)
+ col = board.columns.create!(title: "Done", position: 0, default_sort: "recency")
+ old_card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Old",
+ column_id: col.id,
+ position: 0,
+ column_changed_at: 5.days.ago,
+ created_by_id: admin.id,
+ )
+ new_card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "New",
+ column_id: col.id,
+ position: 10_000,
+ column_changed_at: 5.days.ago,
+ created_by_id: admin.id,
+ )
+ old_card.update_columns(updated_at: 4.days.ago)
+ new_card.update_columns(updated_at: 1.hour.ago)
+
+ sign_in(admin)
+ get "/boards/api/boards/#{board.id}.json"
+
+ card_titles = response.parsed_body["columns"][0]["cards"].map { |card| card["title"] }
+ expect(card_titles).to eq(%w[New Old])
+ expect(response.parsed_body["columns"][0]["cards"][0]["recency_at"]).to be_present
+ end
+
+ it "denies access to users without read permission" do
+ board = Fabricate(:boards_board, name: "Secret", slug: "secret", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board.columns.create!(title: "Col", position: 0)
+
+ sign_in(outsider)
+ get "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "reports public_read based on the anonymous group" do
+ public_board = Fabricate(:boards_board, name: "Public", slug: "public", created_by: admin)
+ Fabricate(
+ :access_control_list,
+ target: public_board,
+ permission: "view",
+ allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ public_board.columns.create!(title: "Col", position: 0)
+
+ restricted_board =
+ Fabricate(:boards_board, name: "Restricted", slug: "restricted", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: restricted_board,
+ permission: "view",
+ groups: [read_group],
+ )
+ restricted_board.columns.create!(title: "Col", position: 0)
+
+ sign_in(admin)
+
+ get "/boards/api/boards/#{public_board.id}.json"
+ expect(response.parsed_body["board"]["anonymous_can_read"]).to be_truthy
+
+ get "/boards/api/boards/#{restricted_board.id}.json"
+ expect(response.parsed_body["board"]["anonymous_can_read"]).to be_falsey
+ end
+ end
+
+ describe "POST /boards/api/boards" do
+ it "creates a board for users in the manage group" do
+ sign_in(manager)
+
+ post "/boards/api/boards.json",
+ params: {
+ board: {
+ name: "Engineering",
+ slug: "engineering",
+ columns: [{ title: "Backlog" }, { title: "In Progress" }],
+ },
+ }
+
+ expect(response.status).to eq(201)
+ board = Boards::Board.find_by(slug: "engineering")
+ expect(board).to be_present
+ expect(board.columns.count).to eq(2)
+ expect(board.columns.order(:position).pluck(:title)).to eq(["Backlog", "In Progress"])
+ end
+
+ it "creates a board for admin users" do
+ sign_in(admin)
+
+ post "/boards/api/boards.json",
+ params: {
+ board: {
+ name: "Admin Board",
+ slug: "admin-board",
+ },
+ }
+
+ expect(response.status).to eq(201)
+ end
+
+ it "rejects users not in the manage group" do
+ sign_in(outsider)
+
+ post "/boards/api/boards.json", params: { board: { name: "Nope", slug: "nope" } }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "PUT /boards/api/boards/:id" do
+ it "updates board attributes for users in the manage group" do
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Old Name",
+ slug: "old-name",
+ created_by: admin,
+ additional_manage_groups: [manage_group],
+ )
+ board.columns.create!(title: "Col", position: 0)
+
+ sign_in(manager)
+
+ put "/boards/api/boards/#{board.id}.json",
+ params: {
+ board: {
+ name: "New Name",
+ show_tags: true,
+ columns: [{ id: board.columns.first.id, title: "Renamed" }],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ board.reload
+ expect(board.name).to eq("New Name")
+ expect(board.show_tags).to eq(true)
+ expect(board.columns.first.title).to eq("Col")
+ end
+
+ it "does not update columns when a columns payload is submitted" do
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Column Payload",
+ slug: "column-payload",
+ created_by: admin,
+ additional_manage_groups: [manage_group],
+ )
+ column = board.columns.create!(title: "Col", position: 0)
+
+ sign_in(manager)
+
+ put "/boards/api/boards/#{board.id}.json",
+ params: {
+ board: {
+ name: "Updated",
+ columns: [{ id: column.id, title: "Renamed", default_sort: "recency" }],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(column.reload).to have_attributes(title: "Col", default_sort: "priority")
+ end
+
+ it "rejects users not in the manage group" do
+ board = Fabricate(:boards_board, name: "Protected", slug: "protected", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}.json", params: { board: { name: "Hacked" } }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "POST /boards/api/boards/:id/move-column" do
+ fab!(:sales_tag, :tag) { Fabricate(:tag, name: "sales") }
+ fab!(:board_mc) do
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Move Col",
+ slug: "move-col",
+ tag_ids: [sales_tag.id],
+ created_by: admin,
+ additional_manage_groups: [manage_group],
+ )
+ board
+ end
+ fab!(:col_a) { board_mc.columns.create!(title: "A", position: 0) }
+ fab!(:col_b) { board_mc.columns.create!(title: "B", position: 1) }
+ fab!(:col_c) { board_mc.columns.create!(title: "C", position: 2) }
+
+ before { manage_group.add(admin) }
+
+ it "swaps column positions and returns the new order" do
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board_mc.id}/move-column.json",
+ params: {
+ column_id: col_b.id,
+ direction: 1,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["column_order"]).to eq([col_a.id, col_c.id, col_b.id])
+ expect(col_b.reload.position).to eq(2)
+ expect(col_c.reload.position).to eq(1)
+ end
+
+ it "returns 403 for non-manager users" do
+ sign_in(outsider)
+
+ post "/boards/api/boards/#{board_mc.id}/move-column.json",
+ params: {
+ column_id: col_b.id,
+ direction: 1,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 403 for anonymous users" do
+ post "/boards/api/boards/#{board_mc.id}/move-column.json",
+ params: {
+ column_id: col_b.id,
+ direction: 1,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns 404 for a nonexistent board" do
+ sign_in(admin)
+
+ post "/boards/api/boards/0/move-column.json", params: { column_id: col_b.id, direction: 1 }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for a nonexistent column" do
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board_mc.id}/move-column.json",
+ params: {
+ column_id: 0,
+ direction: 1,
+ }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 400 for an invalid direction" do
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board_mc.id}/move-column.json",
+ params: {
+ column_id: col_b.id,
+ direction: 5,
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns 422 when moving past the boundary" do
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board_mc.id}/move-column.json",
+ params: {
+ column_id: col_c.id,
+ direction: 1,
+ }
+
+ expect(response.status).to eq(422)
+ end
+ end
+
+ describe "DELETE /boards/api/boards/:id" do
+ it "deletes a board for users in the manage group" do
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Deletable",
+ slug: "deletable",
+ created_by: admin,
+ additional_manage_groups: [manage_group],
+ )
+
+ sign_in(manager)
+
+ expect { delete "/boards/api/boards/#{board.id}.json" }.to change { Boards::Board.count }.by(
+ -1,
+ )
+
+ expect(response.status).to eq(204)
+ end
+
+ it "rejects users not in the manage group" do
+ board = Fabricate(:boards_board, name: "Protected", slug: "protected", created_by: admin)
+
+ sign_in(outsider)
+
+ delete "/boards/api/boards/#{board.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+ end
+end
diff --git a/plugins/boards/spec/requests/boards/cards_controller_spec.rb b/plugins/boards/spec/requests/boards/cards_controller_spec.rb
new file mode 100644
index 00000000000..18d0c9d2798
--- /dev/null
+++ b/plugins/boards/spec/requests/boards/cards_controller_spec.rb
@@ -0,0 +1,1759 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Api::CardsController do
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:reader, :user)
+ fab!(:outsider, :user)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+ fab!(:category) { Fabricate(:category, name: "Todo") }
+ fab!(:topic) { Fabricate(:topic, category: category, user: writer) }
+ fab!(:urgent_tag, :tag) { Fabricate(:tag, name: "urgent") }
+
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Test Board", slug: "test-board", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:col_todo) { board.columns.create!(title: "To Do", position: 0) }
+ fab!(:done_tag, :tag) { Fabricate(:tag, name: "done") }
+ fab!(:col_done) { board.columns.create!(title: "Done", position: 1, tag_id: done_tag.id) }
+ fab!(:col_recent) { board.columns.create!(title: "Recent", position: 2, default_sort: "recency") }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ write_group.add(admin)
+ read_group.add(reader)
+ end
+
+ describe "POST /boards/api/boards/:board_id/cards" do
+ it "creates a floater card" do
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "New task",
+ },
+ }
+
+ expect(response.status).to eq(201)
+ card = response.parsed_body["card"]
+ expect(card["card_type"]).to eq("floater")
+ expect(card["title"]).to eq("New task")
+ expect(card["column_id"]).to eq(col_todo.id)
+ expect(card["column_changed_at"]).to be_present
+ expect(card["recency_at"]).to be_present
+ end
+
+ it "enqueues post-processing for a URL-only floater title" do
+ url = "https://github.com/discourse/discourse/pull/42462"
+ sign_in(writer)
+
+ expect_enqueued_with(job: Jobs::Boards::CardPostProcess, args: { title: url }) do
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: url,
+ },
+ }
+ end
+
+ expect(response.status).to eq(201)
+ expect(response.parsed_body.dig("card", "inline_onebox_data")).to be_nil
+ end
+
+ it "creates a floater card with tag ids" do
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Tagged task",
+ tag_ids: [urgent_tag.id],
+ },
+ }
+
+ expect(response.status).to eq(201)
+ card = response.parsed_body["card"]
+ expect(card["tag_ids"]).to eq([urgent_tag.id])
+ expect(card["tags"].pluck("name")).to eq([urgent_tag.name])
+ expect(Boards::Card.find(card["id"]).tag_ids).to eq([urgent_tag.id])
+ end
+
+ it "rejects unknown floater card tag ids" do
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Bad tag",
+ tag_ids: [urgent_tag.id + 1000],
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects hidden floater card tag ids" do
+ hidden_tag = Fabricate(:tag, name: "staff-urgent")
+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Bad tag",
+ tag_ids: [hidden_tag.id],
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(Boards::Card.where(title: "Bad tag")).to be_empty
+ end
+
+ it "creates a topic card" do
+ sign_in(writer)
+
+ messages =
+ MessageBus.track_publish("/topic/#{topic.id}") do
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ client_id: "test-client",
+ card: {
+ column_id: col_todo.id,
+ topic_id: topic.id,
+ },
+ }
+ end
+
+ expect(response.status).to eq(201)
+ card = response.parsed_body["card"]
+ expect(card["card_type"]).to eq("topic")
+ expect(card["topic_id"]).to eq(topic.id)
+ expect(card["topic"]["title"]).to eq(topic.title)
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data).to eq(reload_topic: true, client_id: "test-client")
+ end
+
+ it "allows topic cards in different columns when another insert races" do
+ inserted_competitor = false
+ allow(Boards::CardOrdering).to receive(
+ :append_to_column!,
+ ).and_wrap_original do |original, card, column|
+ unless inserted_competitor
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_done.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ inserted_competitor = true
+ end
+
+ original.call(card, column)
+ end
+
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(201)
+ expect(board.cards.where(topic_id: topic.id).count).to eq(2)
+
+ created_card = board.cards.find_by(topic_id: topic.id, column_id: col_todo.id)
+ expect(created_card).to be_present
+ end
+
+ it "returns 404 when topic does not exist" do
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ topic_id: -1,
+ },
+ }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when user cannot see the topic" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ topic_id: private_topic.id,
+ },
+ }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "rejects requests from users without write access" do
+ sign_in(reader)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Sneaky card",
+ },
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects anonymous requests" do
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Anon card",
+ },
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "includes all_assigned_users in the response when assignments exist" do
+ skip("requires discourse-assign") unless defined?(Assignment)
+
+ assignee_1 = Fabricate(:user)
+ assignee_2 = Fabricate(:user)
+ post_in_topic = Fabricate(:post, topic: topic)
+ Assignment.create!(
+ target: topic,
+ topic_id: topic.id,
+ assigned_to: assignee_1,
+ assigned_by_user: admin,
+ active: true,
+ )
+ Assignment.create!(
+ target: post_in_topic,
+ topic_id: topic.id,
+ assigned_to: assignee_2,
+ assigned_by_user: admin,
+ active: true,
+ )
+
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(201)
+ all_assigned = response.parsed_body.dig("card", "topic", "all_assigned_users")
+ expect(all_assigned).to be_present
+ usernames = all_assigned.map { |u| u["username"] }
+ expect(usernames).to include(assignee_1.username, assignee_2.username)
+ end
+
+ it "creates a floater card assigned to a user" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ assignee = Fabricate(:user)
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Assigned task",
+ assigned_to_name: assignee.username,
+ },
+ }
+
+ expect(response.status).to eq(201)
+ card = response.parsed_body["card"]
+ expect(card["assigned_to"]["type"]).to eq("User")
+ expect(card["assigned_to"]["username"]).to eq(assignee.username)
+ end
+
+ it "creates a floater card assigned to a group" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ group = Fabricate(:group)
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Group task",
+ assigned_to_name: group.name,
+ },
+ }
+
+ expect(response.status).to eq(201)
+ card = response.parsed_body["card"]
+ expect(card["assigned_to"]["type"]).to eq("Group")
+ expect(card["assigned_to"]["name"]).to eq(group.name)
+ end
+
+ it "rejects an unknown assignee name" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Bad assignee",
+ assigned_to_name: "nonexistent_user_or_group",
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects assigning a group the user cannot see" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ hidden_group = Fabricate(:group, visibility_level: Group.visibility_levels[:staff])
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ title: "Hidden group",
+ assigned_to_name: hidden_group.name,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "applies constraint_fix when creating a topic card" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ ford_tag = Fabricate(:tag, name: "create-ford")
+ car_cat = Fabricate(:category, name: "CreateCars")
+ board.update!(category_ids: [car_cat.id], tag_ids: [ford_tag.id])
+ col_ford = board.columns.create!(title: "CreateFord", position: 2, tag_id: ford_tag.id)
+
+ other_cat = Fabricate(:category, name: "CreateOther")
+ mismatched_topic = Fabricate(:topic, category: other_cat, user: admin)
+ Fabricate(:post, topic: mismatched_topic, user: admin)
+
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ topic_id: mismatched_topic.id,
+ },
+ constraint_fix: {
+ category_id: car_cat.id,
+ tag_names: %w[create-ford],
+ },
+ }
+
+ expect(response.status).to eq(201)
+ expect(mismatched_topic.reload.category_id).to eq(car_cat.id)
+ expect(mismatched_topic.tags.map(&:name)).to include("create-ford")
+ end
+
+ it "rejects constraint_fix when creating a card without topic edit access" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ ford_tag = Fabricate(:tag, name: "create-protected-ford")
+ car_cat = Fabricate(:category, name: "CreateProtectedCars")
+ other_cat = Fabricate(:category, name: "CreateProtectedOther")
+ board.update!(category_ids: [car_cat.id], tag_ids: [ford_tag.id])
+ col_ford =
+ board.columns.create!(title: "CreateProtectedFord", position: 2, tag_id: ford_tag.id)
+
+ protected_topic = Fabricate(:topic, category: other_cat, user: admin)
+ Fabricate(:post, topic: protected_topic, user: admin)
+
+ sign_in(writer)
+
+ expect {
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ topic_id: protected_topic.id,
+ },
+ constraint_fix: {
+ category_id: car_cat.id,
+ tag_names: [ford_tag.name],
+ },
+ }
+ }.not_to change { Boards::Card.count }
+
+ expect(response.status).to eq(403)
+ expect(protected_topic.reload.category_id).to eq(other_cat.id)
+ expect(protected_topic.tags).to be_empty
+ end
+
+ it "rolls back topic changes when constraint_fix is insufficient and card creation is rejected" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ car_cat = Fabricate(:category, name: "RollbackCars")
+ other_cat = Fabricate(:category, name: "RollbackOther")
+ rollback_tag = Fabricate(:tag, name: "rollback-tag")
+ rb_tag = Fabricate(:tag, name: "rb-create-#{SecureRandom.hex(4)}")
+ board.update!(category_ids: [car_cat.id], tag_ids: [rb_tag.id])
+
+ mismatched_topic = Fabricate(:topic, category: other_cat, user: admin)
+ Fabricate(:post, topic: mismatched_topic, user: admin)
+
+ sign_in(admin)
+
+ # Fix category but not tags β€” topic still won't match on an untagged column
+ post "/boards/api/boards/#{board.id}/cards.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ topic_id: mismatched_topic.id,
+ },
+ constraint_fix: {
+ category_id: car_cat.id,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(mismatched_topic.reload.category_id).to eq(other_cat.id)
+ end
+ end
+
+ describe "PUT /boards/api/boards/:board_id/cards/:id" do
+ it "moves a floater card between columns" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card.update_column(:column_changed_at, 2.days.ago)
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_done.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.column_id).to eq(col_done.id)
+ expect(card.column_changed_at).to be > 1.day.ago
+ expect(response.parsed_body.dig("card", "column_changed_at")).to be_present
+ end
+
+ it "publishes refreshed topic memberships after moving a topic card" do
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ messages =
+ MessageBus.track_publish("/topic/#{topic.id}") do
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ client_id: "test-client",
+ card: {
+ column_id: col_done.id,
+ },
+ }
+ end
+
+ expect(response.status).to eq(200)
+ membership_message = messages.find { |message| message.data[:reload_topic] }
+ expect(membership_message.data).to eq(reload_topic: true, client_id: "test-client")
+ expect(membership_message.data).not_to have_key(:board_memberships)
+ end
+
+ it "updates a floater card title" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Old title",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ title: "New title",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.title).to eq("New title")
+ expect(response.parsed_body["card"]["title"]).to eq("New title")
+ end
+
+ it "clears stale data and enqueues post-processing for a URL-only title update" do
+ url = "https://github.com/discourse/discourse/pull/42462"
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "https://example.com/old",
+ inline_onebox_data: {
+ "url" => "https://example.com/old",
+ "title" => "Old title",
+ },
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ sign_in(writer)
+
+ expect_enqueued_with(
+ job: Jobs::Boards::CardPostProcess,
+ args: {
+ card_id: card.id,
+ title: url,
+ },
+ ) do
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json", params: { card: { title: url } }
+ end
+
+ expect(response.status).to eq(200)
+ expect(card.reload.inline_onebox_data).to be_nil
+ expect(response.parsed_body.dig("card", "inline_onebox_data")).to be_nil
+ end
+
+ it "updates floater card tag ids" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Tag me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ tag_ids: [urgent_tag.id],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.tag_ids).to eq([urgent_tag.id])
+ expect(response.parsed_body.dig("card", "tag_ids")).to eq([urgent_tag.id])
+ expect(response.parsed_body.dig("card", "tags").pluck("name")).to eq([urgent_tag.name])
+ end
+
+ it "omits restricted tags from update broadcasts" do
+ hidden_tag = Fabricate(:tag, name: "secret-boards")
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_category.update!(allowed_tags: [hidden_tag.name])
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Retitle me",
+ column_id: col_todo.id,
+ position: 0,
+ tag_ids: [urgent_tag.id, hidden_tag.id],
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") do
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ title: "Retitled",
+ },
+ }
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("card", "tags").pluck("name")).to contain_exactly(
+ urgent_tag.name,
+ hidden_tag.name,
+ )
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:type]).to eq("card_updated")
+ expect(messages.first.data[:card][:tag_ids]).to contain_exactly(urgent_tag.id)
+ expect(messages.first.data[:card][:tags].map { |tag| tag[:name] }).to contain_exactly(
+ urgent_tag.name,
+ )
+ end
+
+ it "rejects unknown floater card tag ids on update" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Bad update",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ tag_ids: [urgent_tag.id + 1000],
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects hidden floater card tag ids on update" do
+ hidden_tag = Fabricate(:tag, name: "staff-update")
+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Bad update",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ tag_ids: [hidden_tag.id],
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(card.reload.tag_ids).to be_empty
+ end
+
+ it "preserves notes when omitted from floater updates" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Keep details",
+ notes: "Keep this note",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ title: "Updated title only",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.notes).to eq("Keep this note")
+ end
+
+ it "returns 404 when updating a topic card whose topic is hidden from the user" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ private_card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: private_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{private_card.id}.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ },
+ }
+
+ expect(response.status).to eq(404)
+ expect(response.body).not_to include(private_topic.title)
+ end
+
+ it "applies topic mutations when moving a topic card to a new column" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_done.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.column_id).to eq(col_done.id)
+ expect(topic.reload.tags.map(&:name)).to include("done")
+ end
+
+ it "reorders within the same column" do
+ card1 =
+ board.cards.create!(
+ card_type: :floater,
+ title: "First",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card2 =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Second",
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card1.id}.json",
+ params: {
+ card: {
+ column_id: col_todo.id,
+ after_card_id: card2.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card2.reload.position).to be < card1.reload.position
+ end
+
+ it "moves cards into column sorted by recency at the top" do
+ existing =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing",
+ column_id: col_recent.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_recent.id,
+ after_card_id: existing.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.column_id).to eq(col_recent.id)
+ expect(card.position).to be < existing.reload.position
+ expect(response.parsed_body.dig("card", "recency_at")).to be_present
+ end
+
+ it "rejects same-column reordering in column sorted by recency" do
+ card1 =
+ board.cards.create!(
+ card_type: :floater,
+ title: "First",
+ column_id: col_recent.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ card2 =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Second",
+ column_id: col_recent.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card1.id}.json",
+ params: {
+ card: {
+ column_id: col_recent.id,
+ after_card_id: card2.id,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(card1.reload.position).to eq(0)
+ end
+
+ it "promotes a floater card to a topic card" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ notes: "Some notes",
+ tag_ids: [urgent_tag.id],
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body["card"]
+ expect(result["card_type"]).to eq("topic")
+ expect(result["topic_id"]).to eq(topic.id)
+ expect(result["title"]).to be_nil
+ expect(result["notes"]).to be_nil
+ expect(result["tags"]).to eq([])
+
+ card.reload
+ expect(card.topic_id).to eq(topic.id)
+ expect(card).to be_topic
+ expect(card.title).to be_nil
+ expect(card.notes).to be_nil
+ expect(card.tag_ids).to eq([])
+ end
+
+ it "adopts the existing topic card when promotion races with topic sync insertion" do
+ floater =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ inserted_competitor = false
+ allow(Boards::TopicMutator).to receive(:apply!).and_wrap_original do |original, **kwargs|
+ unless inserted_competitor
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ inserted_competitor = true
+ end
+
+ original.call(**kwargs)
+ end
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{floater.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(board.cards.where(topic_id: topic.id).count).to eq(1)
+ expect(Boards::Card.find_by(id: floater.id)).to be_nil
+ expect(response.parsed_body.dig("card", "topic_id")).to eq(topic.id)
+ end
+
+ it "promotes a floater adopting an existing topic card in the same column" do
+ existing_topic_card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ floater =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{floater.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body["card"]
+ expect(result["card_type"]).to eq("topic")
+ expect(result["topic_id"]).to eq(topic.id)
+ expect(result["column_id"]).to eq(col_todo.id)
+
+ existing_topic_card.reload
+ expect(existing_topic_card.column_id).to eq(col_todo.id)
+
+ expect(Boards::Card.find_by(id: floater.id)).to be_nil
+ end
+
+ it "includes adopted_floater_id in response when adopting an existing topic card" do
+ existing_topic_card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ floater =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{floater.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ body = response.parsed_body
+ expect(body["adopted_floater_id"]).to eq(floater.id)
+ expect(body["card"]["topic_id"]).to eq(topic.id)
+ end
+
+ it "publishes card_deleted + card_created events for adoption" do
+ existing_topic_card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ floater =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") do
+ put "/boards/api/boards/#{board.id}/cards/#{floater.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+ end
+
+ expect(response.status).to eq(200)
+ types = messages.map { |m| m.data[:type] }
+ expect(types).to contain_exactly("card_deleted", "card_created")
+ end
+
+ it "rejects promoting a floater to a topic the user cannot see" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ topic_id: private_topic.id,
+ },
+ }
+
+ expect(response.status).to eq(403)
+ expect(card.reload).to be_floater
+ end
+
+ it "includes all_assigned_users in the response after a topic card move" do
+ skip("requires discourse-assign") unless defined?(Assignment)
+
+ assignee = Fabricate(:user)
+ Assignment.create!(
+ target: topic,
+ topic_id: topic.id,
+ assigned_to: assignee,
+ assigned_by_user: admin,
+ active: true,
+ )
+
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_done.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ all_assigned = response.parsed_body.dig("card", "topic", "all_assigned_users")
+ expect(all_assigned).to be_present
+ expect(all_assigned.first["username"]).to eq(assignee.username)
+ end
+
+ it "assigns a user to a floater card" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Assign me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ assignee = Fabricate(:user)
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ assigned_to_name: assignee.username,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.assigned_to).to eq(assignee)
+ result = response.parsed_body["card"]
+ expect(result["assigned_to"]["type"]).to eq("User")
+ expect(result["assigned_to"]["username"]).to eq(assignee.username)
+ end
+
+ it "assigns a group to a floater card" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Assign group",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ group = Fabricate(:group)
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ assigned_to_name: group.name,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.assigned_to).to eq(group)
+ result = response.parsed_body["card"]
+ expect(result["assigned_to"]["type"]).to eq("Group")
+ expect(result["assigned_to"]["name"]).to eq(group.name)
+ end
+
+ it "unassigns a floater card" do
+ assignee = Fabricate(:user)
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Unassign me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ assigned_to_name: "",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.assigned_to).to be_nil
+ expect(response.parsed_body["card"]["assigned_to"]).to be_nil
+ end
+
+ it "does not silently clear assignment for unknown assignee name" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ assignee = Fabricate(:user)
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Keep assignee",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ assigned_to_name: "nonexistent_user_or_group",
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(card.reload.assigned_to).to eq(assignee)
+ end
+
+ it "rejects updating assignment to a group the user cannot see" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Hidden group",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ hidden_group = Fabricate(:group, visibility_level: Group.visibility_levels[:staff])
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ assigned_to_name: hidden_group.name,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(card.reload.assigned_to).to be_nil
+ end
+
+ it "clears card-level assignment when promoting a floater to a topic card" do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+
+ assignee = Fabricate(:user)
+ assign_group.add(assignee)
+ Fabricate(:post, topic: topic)
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ card.reload
+ expect(card.assigned_to_id).to be_nil
+ expect(card.assigned_to_type).to be_nil
+ end
+
+ it "carries over card assignment to the topic on promotion" do
+ skip("requires discourse-assign") unless defined?(Assignment)
+
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ assignee = Fabricate(:user)
+ assign_group.add(assignee)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ Fabricate(:post, topic: topic)
+
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ topic_id: topic.id,
+ },
+ }
+
+ expect(response.status).to eq(200)
+ assignment = Assignment.find_by(target: topic, active: true)
+ expect(assignment).to be_present
+ expect(assignment.assigned_to).to eq(assignee)
+ end
+
+ it "rejects requests from users without write access" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Protected",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(reader)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ title: "Hacked",
+ },
+ }
+
+ expect(response.status).to eq(403)
+ end
+ end
+
+ describe "PUT /boards/api/boards/:board_id/cards/:id with constraint_fix" do
+ fab!(:ford_tag) { Fabricate(:tag, name: "ford") }
+ fab!(:chevy_tag) { Fabricate(:tag, name: "chevy") }
+ fab!(:car_category) { Fabricate(:category, name: "Cars") }
+ fab!(:boat_category) { Fabricate(:category, name: "Boats") }
+
+ it "applies category fix and moves the card" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [car_category.id], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_ford = board.columns.create!(title: "Ford", position: 2, tag_id: ford_tag.id)
+
+ boat_topic = Fabricate(:topic, category: boat_category, tags: [ford_tag], user: admin)
+ Fabricate(:post, topic: boat_topic, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: boat_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ },
+ constraint_fix: {
+ category_id: car_category.id,
+ },
+ }
+ expect(response.status).to eq(200)
+ expect(card.reload.column_id).to eq(col_ford.id)
+ expect(boat_topic.reload.category_id).to eq(car_category.id)
+ end
+
+ it "applies tag fix and moves the card" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [category.id], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_ford = board.columns.create!(title: "Ford", position: 2, tag_id: ford_tag.id)
+
+ car_topic = Fabricate(:topic, category: category, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: car_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ },
+ constraint_fix: {
+ tag_names: %w[ford],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.column_id).to eq(col_ford.id)
+ expect(car_topic.reload.tags.map(&:name)).to include("ford")
+ end
+
+ it "rejects tag fix without topic edit access" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [category.id], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_ford = board.columns.create!(title: "ProtectedFord", position: 2, tag_id: ford_tag.id)
+
+ protected_topic = Fabricate(:topic, category: category, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: protected_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ },
+ constraint_fix: {
+ tag_names: [ford_tag.name],
+ },
+ }
+
+ expect(response.status).to eq(403)
+ expect(card.reload.column_id).to eq(col_todo.id)
+ expect(protected_topic.reload.tags).to be_empty
+ end
+
+ it "applies both category and tag fix" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [car_category.id], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_chevy = board.columns.create!(title: "Chevy", position: 2, tag_id: chevy_tag.id)
+
+ mismatched_topic = Fabricate(:topic, category: boat_category, user: admin)
+ Fabricate(:post, topic: mismatched_topic, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: mismatched_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_chevy.id,
+ },
+ constraint_fix: {
+ category_id: car_category.id,
+ tag_names: %w[chevy],
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(card.reload.column_id).to eq(col_chevy.id)
+ expect(mismatched_topic.reload.category_id).to eq(car_category.id)
+ expect(mismatched_topic.tags.map(&:name)).to include("chevy")
+ end
+
+ it "rejects constraint_fix with a category not in board constraints" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [car_category.id], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_ford = board.columns.create!(title: "Ford", position: 2, tag_id: ford_tag.id)
+
+ other_category = Fabricate(:category, name: "Planes")
+ boat_topic = Fabricate(:topic, category: boat_category, tags: [ford_tag], user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: boat_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ },
+ constraint_fix: {
+ category_id: other_category.id,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects constraint_fix with tags not in board constraints" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [category.id], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_ford = board.columns.create!(title: "Ford", position: 2, tag_id: ford_tag.id)
+
+ rogue_tag = Fabricate(:tag, name: "rogue")
+ car_topic = Fabricate(:topic, category: category, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: car_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ },
+ constraint_fix: {
+ tag_names: [rogue_tag.name],
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects category fix on a tag-only board" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [], tag_ids: [ford_tag.id, chevy_tag.id])
+ col_ford = board.columns.create!(title: "Ford", position: 2, tag_id: ford_tag.id)
+
+ car_topic = Fabricate(:topic, category: category, user: admin)
+ Fabricate(:post, topic: car_topic, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: car_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_ford.id,
+ },
+ constraint_fix: {
+ category_id: car_category.id,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects tag fix on a category-only board" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ board.update!(category_ids: [car_category.id], tag_ids: [])
+
+ car_topic = Fabricate(:topic, category: boat_category, user: admin)
+ Fabricate(:post, topic: car_topic, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: car_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_done.id,
+ },
+ constraint_fix: {
+ tag_names: %w[ford],
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "rolls back topic changes when move fails after constraint_fix" do
+ SiteSetting.tagging_enabled = true
+ allow(Boards::TopicSync).to receive(:sync_topic)
+
+ rb_tag = Fabricate(:tag, name: "rb-update-#{SecureRandom.hex(4)}")
+ board.update!(category_ids: [car_category.id], tag_ids: [rb_tag.id])
+
+ # Topic has wrong category and no board tags
+ boat_topic = Fabricate(:topic, category: boat_category, user: admin)
+ Fabricate(:post, topic: boat_topic, user: admin)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: boat_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+
+ # Fix category only β€” col_done adds done_tag (not in board.tag_ids),
+ # and topic has no board tags, so topic_will_match_after_mutation? fails on tags
+ put "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ card: {
+ column_id: col_done.id,
+ },
+ constraint_fix: {
+ category_id: car_category.id,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ expect(boat_topic.reload.category_id).to eq(boat_category.id)
+ expect(card.reload.column_id).to eq(col_todo.id)
+ end
+ end
+
+ describe "DELETE /boards/api/boards/:board_id/cards/:id" do
+ it "destroys a floater card" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Delete me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ expect { delete "/boards/api/boards/#{board.id}/cards/#{card.id}.json" }.to change {
+ Boards::Card.count
+ }.by(-1)
+
+ expect(response.status).to eq(204)
+ end
+
+ it "destroys a topic card" do
+ board.update!(category_ids: [category.id])
+
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ messages =
+ MessageBus.track_publish("/topic/#{topic.id}") do
+ expect do
+ delete "/boards/api/boards/#{board.id}/cards/#{card.id}.json",
+ params: {
+ client_id: "test-client",
+ }
+ end.to change { Boards::Card.count }.by(-1)
+ end
+
+ expect(response.status).to eq(204)
+ expect(messages.size).to eq(1)
+ expect(messages.first.data).to eq(reload_topic: true, client_id: "test-client")
+ end
+
+ it "returns 404 when deleting a topic card whose topic is hidden" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_topic = Fabricate(:topic, category: private_category)
+ private_card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: private_topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(writer)
+
+ expect {
+ delete "/boards/api/boards/#{board.id}/cards/#{private_card.id}.json"
+ }.not_to change { Boards::Card.count }
+
+ expect(response.status).to eq(404)
+ expect(response.body).not_to include(private_topic.title)
+ end
+ end
+end
diff --git a/plugins/boards/spec/requests/boards/columns_controller_spec.rb b/plugins/boards/spec/requests/boards/columns_controller_spec.rb
new file mode 100644
index 00000000000..48876ba39c2
--- /dev/null
+++ b/plugins/boards/spec/requests/boards/columns_controller_spec.rb
@@ -0,0 +1,160 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Api::ColumnsController do
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+ fab!(:board) do
+ Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+ end
+ fab!(:column) { board.columns.create!(title: "Old", position: 0) }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ end
+
+ describe "POST /boards/api/boards/:board_id/columns" do
+ it "creates a column for board managers" do
+ sign_in(manager)
+
+ post "/boards/api/boards/#{board.id}/columns.json", params: { column: { title: "Backlog" } }
+
+ expect(response.status).to eq(201)
+ expect(response.parsed_body["column"]["title"]).to eq("Backlog")
+ expect(board.columns.order(:position).last.title).to eq("Backlog")
+ end
+
+ it "rejects users who cannot manage the board" do
+ sign_in(outsider)
+
+ post "/boards/api/boards/#{board.id}/columns.json", params: { column: { title: "Backlog" } }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns not found when the board does not exist" do
+ sign_in(manager)
+
+ post "/boards/api/boards/0/columns.json", params: { column: { title: "Backlog" } }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns bad request for invalid payloads" do
+ sign_in(manager)
+
+ post "/boards/api/boards/#{board.id}/columns.json", params: { column: { title: nil } }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns service errors for invalid column settings" do
+ tag = Fabricate(:tag, name: "todo")
+ board.columns.create!(title: "Todo", position: 1, tag_id: tag.id)
+ sign_in(manager)
+
+ post "/boards/api/boards/#{board.id}/columns.json",
+ params: {
+ column: {
+ title: "Duplicate",
+ tag_name: tag.name,
+ },
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to contain_exactly(
+ I18n.t("boards.errors.cannot_use_same_tag_multiple_times", tag_name: tag.name),
+ )
+ end
+ end
+
+ describe "PUT /boards/api/boards/:board_id/columns/:id" do
+ it "updates a column for board managers" do
+ sign_in(manager)
+
+ put "/boards/api/boards/#{board.id}/columns/#{column.id}.json",
+ params: {
+ column: {
+ title: "Renamed",
+ default_sort: "recency",
+ },
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["column"]["title"]).to eq("Renamed")
+ expect(column.reload).to have_attributes(title: "Renamed", default_sort: "recency")
+ end
+
+ it "rejects users who cannot manage the board" do
+ sign_in(outsider)
+
+ put "/boards/api/boards/#{board.id}/columns/#{column.id}.json",
+ params: {
+ column: {
+ title: "Renamed",
+ },
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns not found when the column does not exist" do
+ sign_in(manager)
+
+ put "/boards/api/boards/#{board.id}/columns/0.json", params: { column: { title: "Renamed" } }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns bad request for invalid payloads" do
+ sign_in(manager)
+
+ put "/boards/api/boards/#{board.id}/columns/#{column.id}.json",
+ params: {
+ column: {
+ title: nil,
+ },
+ }
+
+ expect(response.status).to eq(400)
+ end
+ end
+
+ describe "DELETE /boards/api/boards/:board_id/columns/:id" do
+ it "deletes a column for board managers" do
+ sign_in(manager)
+
+ delete "/boards/api/boards/#{board.id}/columns/#{column.id}.json"
+
+ expect(response.status).to eq(204)
+ expect(Boards::Column.exists?(column.id)).to eq(false)
+ end
+
+ it "rejects users who cannot manage the board" do
+ sign_in(outsider)
+
+ delete "/boards/api/boards/#{board.id}/columns/#{column.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+
+ it "returns not found when the board does not exist" do
+ sign_in(manager)
+
+ delete "/boards/api/boards/0/columns/#{column.id}.json"
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the column does not exist" do
+ sign_in(manager)
+
+ delete "/boards/api/boards/#{board.id}/columns/0.json"
+
+ expect(response.status).to eq(404)
+ end
+ end
+end
diff --git a/plugins/boards/spec/requests/boards/topic_moves_controller_spec.rb b/plugins/boards/spec/requests/boards/topic_moves_controller_spec.rb
new file mode 100644
index 00000000000..8443935f179
--- /dev/null
+++ b/plugins/boards/spec/requests/boards/topic_moves_controller_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Api::TopicMovesController do
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:assignee, :user)
+ fab!(:write_group, :group)
+ fab!(:assign_group, :group)
+ fab!(:category) { Fabricate(:category, name: "Todo") }
+ fab!(:topic) { Fabricate(:topic, category: category, user: writer) }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ write_group.add(admin)
+ end
+
+ it "creates or updates a topic card on move" do
+ board = Boards::Board.create!(name: "Todo", slug: "todo-3", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ column = board.columns.create!(title: "Doing", position: 0)
+
+ sign_in(admin)
+
+ post "/boards/api/boards/#{board.id}/topic-moves.json",
+ params: {
+ topic_id: topic.id,
+ to_column_id: column.id,
+ }
+
+ expect(response.status).to eq(201)
+
+ card = board.cards.find_by(topic_id: topic.id)
+ expect(card).to be_present
+ expect(card.column_id).to eq(column.id)
+ expect(card.card_type).to eq("topic")
+ end
+
+ it "omits private assignment metadata from move response" do
+ SiteSetting.assign_enabled = true
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ writer.update!(moderator: true)
+ Fabricate(:topic_assignment, topic:, assigned_to: assignee)
+ board = Boards::Board.create!(name: "Todo", slug: "todo-assignments", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ column = board.columns.create!(title: "Doing", position: 0)
+
+ sign_in(writer)
+
+ post "/boards/api/boards/#{board.id}/topic-moves.json",
+ params: {
+ topic_id: topic.id,
+ to_column_id: column.id,
+ }
+
+ expect(response.status).to eq(201)
+ expect(response.parsed_body.dig("card", "topic").keys).not_to include(
+ "assigned_to_user",
+ "assigned_to_group",
+ "all_assigned_users",
+ "assignments",
+ )
+ end
+end
diff --git a/plugins/boards/spec/serializers/boards/board_serializer_spec.rb b/plugins/boards/spec/serializers/boards/board_serializer_spec.rb
new file mode 100644
index 00000000000..26be59b1e57
--- /dev/null
+++ b/plugins/boards/spec/serializers/boards/board_serializer_spec.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::BoardSerializer do
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:writer, :user)
+ fab!(:manage_group, :group)
+ fab!(:write_group, :group)
+ fab!(:category)
+ fab!(:visible_tag) { Fabricate(:tag, name: "visible-boards") }
+ fab!(:alpha_tag) { Fabricate(:tag, name: "alpha-boards") }
+ fab!(:hidden_tag) { Fabricate(:tag, name: "staff-boards") }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ write_group.add(writer)
+ end
+
+ it "serializes core board attributes and nested columns" do
+ board =
+ Fabricate(
+ :boards_board,
+ name: "Sprint",
+ slug: "sprint",
+ category_ids: [category.id],
+ tag_ids: [visible_tag.id],
+ require_confirmation: true,
+ show_tags: true,
+ card_style: "detailed",
+ show_topic_thumbnail: true,
+ created_by: admin,
+ )
+ Fabricate(:boards_column, board:, title: "Backlog", position: 0, tag_id: visible_tag.id)
+
+ payload =
+ described_class.new(
+ board,
+ root: false,
+ scope: Guardian.new(admin),
+ tag_name_map: {
+ visible_tag.id => visible_tag.name,
+ },
+ ).as_json
+
+ expect(payload).to include(
+ id: board.id,
+ name: "Sprint",
+ slug: "sprint",
+ category_ids: [category.id],
+ tag_ids: [visible_tag.id],
+ tag_names: [visible_tag.name],
+ anonymous_can_read: board.anonymous_can_read?,
+ require_confirmation: true,
+ show_tags: true,
+ card_style: "detailed",
+ show_topic_thumbnail: true,
+ acl: nil,
+ )
+ expect(payload[:columns].first).to include(title: "Backlog", tag_id: visible_tag.id)
+ end
+
+ it "serializes a Unicode board name when the name contains emoji codes" do
+ board = Fabricate(:boards_board, name: "Launch :rocket:", created_by: admin)
+
+ payload =
+ described_class.new(board, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json
+
+ expect(payload).to include(name: "Launch :rocket:", unicode_name: "Launch πŸš€")
+ end
+
+ it "serializes permission booleans from the scoped guardian" do
+ managed_board =
+ Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+ writable_board = Fabricate(:boards_board, created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: writable_board,
+ permission: "edit",
+ groups: [write_group],
+ )
+
+ manager_payload =
+ described_class.new(managed_board, root: false, scope: Guardian.new(manager)).as_json
+ writer_payload =
+ described_class.new(writable_board, root: false, scope: Guardian.new(writer)).as_json
+
+ expect(manager_payload).to include(can_manage: true)
+ expect(writer_payload).to include(can_write: true, can_manage: false)
+ end
+
+ it "serializes the creator username and avatar template" do
+ board = Fabricate(:boards_board, created_by: admin)
+
+ payload =
+ described_class.new(board, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json
+
+ expect(payload[:created_by]).to eq(
+ username: admin.username,
+ avatar_template: admin.avatar_template,
+ )
+ end
+
+ it "filters board tags through the tag name map and sorts tag names" do
+ board =
+ Fabricate(
+ :boards_board,
+ created_by: admin,
+ tag_ids: [visible_tag.id, hidden_tag.id, alpha_tag.id],
+ )
+
+ payload =
+ described_class.new(
+ board,
+ root: false,
+ scope: Guardian.new(admin),
+ tag_name_map: {
+ visible_tag.id => visible_tag.name,
+ alpha_tag.id => alpha_tag.name,
+ },
+ ).as_json
+
+ expect(payload[:tag_ids]).to contain_exactly(visible_tag.id, alpha_tag.id)
+ expect(payload[:tag_names]).to eq([alpha_tag.name, visible_tag.name])
+ end
+
+ it "includes acl only when requested" do
+ board = Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+
+ default_payload =
+ described_class.new(board, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json
+ acl_payload =
+ described_class.new(board, root: false, scope: Guardian.new(admin), include_acl: true).as_json
+
+ expect(default_payload).to include(acl: nil)
+ expect(acl_payload[:acl]).to eq(AccessControlList.where(target: board).flattened_list)
+ end
+end
diff --git a/plugins/boards/spec/serializers/boards/card_serializer_spec.rb b/plugins/boards/spec/serializers/boards/card_serializer_spec.rb
new file mode 100644
index 00000000000..3abb61f29ae
--- /dev/null
+++ b/plugins/boards/spec/serializers/boards/card_serializer_spec.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CardSerializer do
+ fab!(:admin)
+ fab!(:viewer, :user)
+ fab!(:allowed_group, :group)
+ fab!(:private_category) { Fabricate(:private_category, group: allowed_group) }
+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }
+ fab!(:board) { Fabricate(:boards_board, created_by: admin) }
+ fab!(:column) { Fabricate(:boards_column, board:) }
+ fab!(:card) do
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ card_type: :topic,
+ topic: private_topic,
+ created_by: admin,
+ )
+ end
+
+ before { enable_current_plugin }
+
+ it "omits topic details when the scoped user cannot see the topic" do
+ payload = described_class.new(card, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload).to include(topic_id: private_topic.id)
+ expect(payload).not_to have_key(:topic)
+ end
+
+ it "includes topic details when the scoped user can see the topic" do
+ allowed_group.add(viewer)
+
+ payload = described_class.new(card, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload[:topic]).to include(title: private_topic.title, slug: private_topic.slug)
+ end
+
+ it "serializes Unicode titles for floater cards" do
+ floater_card =
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ card_type: :floater,
+ title: "Launch :rocket:",
+ created_by: admin,
+ )
+
+ payload = described_class.new(floater_card, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload).to include(title: "Launch :rocket:", unicode_title: "Launch πŸš€")
+ end
+
+ it "serializes inline onebox data for floater cards" do
+ onebox_data = {
+ "url" => "https://github.com/discourse/discourse/pull/42462",
+ "title" => "FEATURE: Add ProseMirror tab support",
+ "css_class" => "--gh-status-approved",
+ }
+ floater_card =
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ card_type: :floater,
+ title: onebox_data["url"],
+ inline_onebox_data: onebox_data,
+ created_by: admin,
+ )
+
+ payload = described_class.new(floater_card, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload[:inline_onebox_data]).to eq(onebox_data)
+ end
+
+ it "omits floater tag metadata the scoped user cannot see" do
+ visible_tag = Fabricate(:tag, name: "visible-boards")
+ hidden_tag = Fabricate(:tag, name: "staff-boards")
+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])
+ floater_card =
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ card_type: :floater,
+ title: "Tagged floater",
+ tag_ids: [visible_tag.id, hidden_tag.id],
+ created_by: admin,
+ )
+
+ payload = described_class.new(floater_card, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload[:tag_ids]).to contain_exactly(visible_tag.id)
+ expect(payload[:tags].map { |tag| tag[:name] }).to contain_exactly(visible_tag.name)
+ end
+end
diff --git a/plugins/boards/spec/serializers/boards/card_topic_serializer_spec.rb b/plugins/boards/spec/serializers/boards/card_topic_serializer_spec.rb
new file mode 100644
index 00000000000..362457f96d2
--- /dev/null
+++ b/plugins/boards/spec/serializers/boards/card_topic_serializer_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CardTopicSerializer do
+ fab!(:assigner, :user)
+ fab!(:viewer, :user)
+ fab!(:assignee, :user)
+ fab!(:hidden_post_assignee, :user)
+ fab!(:assign_group, :group)
+ fab!(:category)
+ fab!(:topic) { Fabricate(:topic, category:) }
+ fab!(:regular_post) { Fabricate(:post, topic:) }
+ fab!(:whisper) { Fabricate(:post, topic:, post_type: Post.types[:whisper]) }
+
+ before do
+ enable_current_plugin
+ SiteSetting.assign_enabled = true
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(assigner)
+ end
+
+ it "serializes a Unicode topic title" do
+ topic.update!(title: "Launch :rocket:")
+
+ payload = described_class.new(topic, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload).to include(title: "Launch :rocket:", unicode_title: "Launch πŸš€")
+ end
+
+ it "hides assignment metadata from unauthorized users" do
+ Fabricate(:topic_assignment, topic:, assigned_to: assignee)
+
+ payload = described_class.new(topic, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload.keys).not_to include(
+ :assigned_to_user,
+ :assigned_to_group,
+ :all_assigned_users,
+ :assignments,
+ )
+ end
+
+ it "shows assignment metadata to users who can assign" do
+ topic_assignment = Fabricate(:topic_assignment, topic:, assigned_to: assignee)
+
+ payload = described_class.new(topic, root: false, scope: Guardian.new(assigner)).as_json
+
+ expect(payload).to include(
+ assigned_to_user: include(username: assignee.username),
+ all_assigned_users: contain_exactly(include(username: assignee.username)),
+ assignments:
+ contain_exactly(
+ include(
+ target_type: "Topic",
+ target_id: topic_assignment.target_id,
+ username: assignee.username,
+ ),
+ ),
+ )
+ end
+
+ it "filters post assignments by post visibility" do
+ SiteSetting.assigns_public = true
+ visible_post_assignment = Fabricate(:post_assignment, post: regular_post, assigned_to: assignee)
+ Fabricate(:post_assignment, post: whisper, assigned_to: hidden_post_assignee)
+
+ payload = described_class.new(topic, root: false, scope: Guardian.new(viewer)).as_json
+
+ expect(payload).to include(
+ all_assigned_users: contain_exactly(include(username: assignee.username)),
+ assignments:
+ contain_exactly(
+ include(
+ target_type: "Post",
+ target_id: visible_post_assignment.target_id,
+ post_number: regular_post.post_number,
+ username: assignee.username,
+ ),
+ ),
+ )
+ end
+end
diff --git a/plugins/boards/spec/serializers/boards/column_serializer_spec.rb b/plugins/boards/spec/serializers/boards/column_serializer_spec.rb
new file mode 100644
index 00000000000..b64e8c40b39
--- /dev/null
+++ b/plugins/boards/spec/serializers/boards/column_serializer_spec.rb
@@ -0,0 +1,129 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::ColumnSerializer do
+ fab!(:admin)
+ fab!(:board) { Fabricate(:boards_board, created_by: admin) }
+ fab!(:visible_tag) { Fabricate(:tag, name: "public-roadmap") }
+ fab!(:hidden_tag) { Fabricate(:tag, name: "staff-roadmap") }
+
+ before { enable_current_plugin }
+
+ it "serializes core column attributes" do
+ column =
+ Fabricate(
+ :boards_column,
+ board:,
+ title: "Doing",
+ icon: "list-check",
+ position: 2,
+ default_sort: "recency",
+ move_to_category_id: Fabricate(:category).id,
+ move_to_assigned: "nobody",
+ move_to_status: "closed",
+ )
+
+ payload =
+ described_class.new(column, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json
+
+ expect(payload).to include(
+ id: column.id,
+ title: "Doing",
+ icon: "list-check",
+ position: 2,
+ default_sort: "recency",
+ tag_id: nil,
+ tag_name: nil,
+ move_to_category_id: column.move_to_category_id,
+ move_to_assigned: "nobody",
+ move_to_status: "closed",
+ )
+ end
+
+ it "serializes a Unicode column title" do
+ column = Fabricate(:boards_column, board:, title: "Doing :rocket:")
+
+ payload =
+ described_class.new(column, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json
+
+ expect(payload).to include(title: "Doing :rocket:", unicode_title: "Doing πŸš€")
+ end
+
+ it "includes visible tag metadata from the tag name map" do
+ column = Fabricate(:boards_column, board:, tag_id: visible_tag.id)
+
+ payload =
+ described_class.new(
+ column,
+ root: false,
+ scope: Guardian.new(admin),
+ tag_name_map: {
+ visible_tag.id => visible_tag.name,
+ },
+ ).as_json
+
+ expect(payload).to include(tag_id: visible_tag.id, tag_name: visible_tag.name)
+ end
+
+ it "omits tag metadata when the tag is not in the tag name map" do
+ column = Fabricate(:boards_column, board:, tag_id: hidden_tag.id)
+
+ payload =
+ described_class.new(
+ column,
+ root: false,
+ scope: Guardian.new(admin),
+ tag_name_map: {
+ visible_tag.id => visible_tag.name,
+ },
+ ).as_json
+
+ expect(payload).to include(tag_id: nil, tag_name: nil)
+ end
+
+ it "omits cards unless card context is provided" do
+ column = Fabricate(:boards_column, board:)
+
+ payload =
+ described_class.new(column, root: false, scope: Guardian.new(admin), tag_name_map: {}).as_json
+
+ expect(payload).not_to have_key(:cards)
+ end
+
+ it "serializes cards from the provided cards_by_column context" do
+ column = Fabricate(:boards_column, board:)
+ first_card =
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ card_type: :floater,
+ title: "First",
+ position: 0,
+ created_by: admin,
+ )
+ second_card =
+ Fabricate(
+ :boards_card,
+ board:,
+ column:,
+ card_type: :floater,
+ title: "Second",
+ position: 1,
+ created_by: admin,
+ )
+
+ payload =
+ described_class.new(
+ column,
+ root: false,
+ scope: Guardian.new(admin),
+ tag_name_map: {
+ },
+ cards_by_column: {
+ column.id => [second_card, first_card],
+ },
+ ).as_json
+
+ expect(payload[:cards].map { |card| card[:id] }).to eq([first_card.id, second_card.id])
+ end
+end
diff --git a/plugins/boards/spec/serializers/boards/topic_boards_memberships_spec.rb b/plugins/boards/spec/serializers/boards/topic_boards_memberships_spec.rb
new file mode 100644
index 00000000000..0b1b4fc967e
--- /dev/null
+++ b/plugins/boards/spec/serializers/boards/topic_boards_memberships_spec.rb
@@ -0,0 +1,211 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::TopicBoardMembershipSerializer do
+ fab!(:admin)
+ fab!(:reader, :user)
+ fab!(:read_group, :group)
+ fab!(:topic)
+
+ fab!(:board) do
+ Fabricate(:boards_board, name: "Sales :dollar_banknote:", slug: "sales", created_by: admin)
+ end
+ fab!(:column) do
+ Fabricate(
+ :boards_column,
+ board:,
+ title: "In progress :hourglass_done:",
+ position: 0,
+ color: "0088cc",
+ icon: "angles-up",
+ )
+ end
+ fab!(:card) { Fabricate(:boards_topic_card, board:, column:, topic:) }
+
+ before do
+ enable_current_plugin
+ read_group.add(reader)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ end
+
+ let(:list_item_json) do
+ ->(user) { TopicListItemSerializer.new(topic, scope: Guardian.new(user), root: false).as_json }
+ end
+
+ let(:topic_view_json) do
+ lambda do |user|
+ TopicViewSerializer.new(
+ TopicView.new(topic, user),
+ scope: Guardian.new(user),
+ root: false,
+ ).as_json
+ end
+ end
+
+ describe "topic list item serializer" do
+ it "includes memberships for users who can read the board" do
+ expect(list_item_json.call(reader)[:board_memberships]).to eq(
+ [
+ {
+ board_id: board.id,
+ board_name: "Sales :dollar_banknote:",
+ board_slug: "sales",
+ unicode_board_name: "Sales πŸ’΅",
+ cards: [
+ {
+ card_id: card.id,
+ column_id: column.id,
+ column_title: "In progress :hourglass_done:",
+ column_color: "0088cc",
+ column_icon: "angles-up",
+ unicode_column_title: "In progress βŒ›",
+ },
+ ],
+ },
+ ],
+ )
+ end
+
+ it "includes a Unicode column title" do
+ column.update!(title: "In progress :rocket:")
+
+ membership = list_item_json.call(reader)[:board_memberships].sole
+
+ expect(membership[:cards].sole).to include(
+ column_title: "In progress :rocket:",
+ unicode_column_title: "In progress πŸš€",
+ )
+ end
+
+ it "includes a Unicode board name" do
+ board.update!(name: "Sales :fire:")
+
+ membership = list_item_json.call(reader)[:board_memberships].sole
+
+ expect(membership).to include(board_name: "Sales :fire:", unicode_board_name: "Sales πŸ”₯")
+ end
+
+ it "omits memberships for users who cannot read the board" do
+ other_user = Fabricate(:user)
+ expect(list_item_json.call(other_user)).not_to have_key(:board_memberships)
+ end
+
+ it "omits the attribute when the plugin is disabled" do
+ SiteSetting.boards_enabled = false
+ expect(list_item_json.call(reader)).not_to have_key(:board_memberships)
+ end
+
+ it "omits the attribute for topics without cards" do
+ card.destroy!
+ topic.board_cards_map = nil
+ expect(list_item_json.call(reader)).not_to have_key(:board_memberships)
+ end
+
+ it "groups multiple topic cards from the same board into one membership" do
+ second_column = Fabricate(:boards_column, board:, title: "Done", position: 1, color: "00aa66")
+ second_card = Fabricate(:boards_topic_card, board:, column: second_column, topic:)
+
+ membership = list_item_json.call(reader)[:board_memberships].sole
+
+ expect(membership[:board_id]).to eq(board.id)
+ expect(membership[:cards].pluck(:card_id)).to eq([card.id, second_card.id])
+ end
+
+ it "uses preloaded cards when present" do
+ result =
+ Boards::TopicBoardMemberships.call(guardian: reader.guardian, options: { topics: [topic] })
+ topic.board_cards_map = result[:cards_map].fetch(topic.id)
+ expect(topic.board_cards_map.fetch(board.id).map(&:id)).to eq([card.id])
+
+ queries =
+ track_sql_queries { list_item_json.call(reader) }.select { |q| q.include?("boards_cards") }
+ expect(queries).to be_empty
+ end
+
+ it "batches board ACL checks across topics" do
+ topics =
+ 2.times.map do |index|
+ extra_topic = Fabricate(:topic)
+ extra_board = Fabricate(:boards_board, name: "Board #{index}", created_by: admin)
+ extra_column = Fabricate(:boards_column, board: extra_board, position: 0)
+ Fabricate(
+ :boards_topic_card,
+ board: extra_board,
+ column: extra_column,
+ topic: extra_topic,
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: extra_board,
+ permission: "view",
+ groups: [read_group],
+ )
+ extra_topic
+ end
+ topics.unshift(topic)
+ topic_list = TopicList.new("latest", reader, topics)
+
+ acl_queries =
+ track_sql_queries { TopicList.preload(topics, topic_list) }.select do |query|
+ query.include?("access_control_lists")
+ end
+
+ expect(acl_queries.size).to eq(1)
+ expect(topics).to all(satisfy { |listed_topic| listed_topic.board_cards_map.present? })
+ end
+
+ it "does not run ACL queries while serializing a preloaded topic list" do
+ topics =
+ 2.times.map do
+ extra_topic = Fabricate(:topic)
+ Fabricate(:boards_topic_card, board:, column:, topic: extra_topic)
+ extra_topic
+ end
+ topics.unshift(topic)
+ TopicList.preload(topics, TopicList.new("latest", reader, topics))
+
+ acl_queries =
+ track_sql_queries do
+ topics.each do |listed_topic|
+ TopicListItemSerializer.new(
+ listed_topic,
+ scope: Guardian.new(reader),
+ root: false,
+ ).as_json
+ end
+ end.select { |query| query.include?("access_control_lists") }
+
+ expect(acl_queries).to be_empty
+ end
+ end
+
+ describe "topic view serializer" do
+ it "includes memberships for users who can read the board" do
+ memberships = topic_view_json.call(reader)[:board_memberships]
+ expect(memberships.flat_map { |membership| membership[:cards] }.pluck(:card_id)).to eq(
+ [card.id],
+ )
+ end
+
+ it "returns an empty membership list for users who cannot read the board" do
+ other_user = Fabricate(:user)
+ expect(topic_view_json.call(other_user)[:board_memberships]).to eq([])
+ end
+
+ it "returns an empty membership list when the last card is removed" do
+ card.destroy!
+
+ expect(topic_view_json.call(reader)[:board_memberships]).to eq([])
+ end
+
+ it "omits the attribute when the plugin is disabled" do
+ SiteSetting.boards_enabled = false
+
+ expect(topic_view_json.call(reader)).not_to have_key(:board_memberships)
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/action/card_inline_onebox_spec.rb b/plugins/boards/spec/services/boards/action/card_inline_onebox_spec.rb
new file mode 100644
index 00000000000..4b39043161e
--- /dev/null
+++ b/plugins/boards/spec/services/boards/action/card_inline_onebox_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Action::CardInlineOnebox do
+ subject(:result) { described_class.call(title:) }
+
+ before { enable_current_plugin }
+
+ context "when the title contains only an HTTPS URL" do
+ let(:url) { "https://github.com/discourse/discourse/pull/42462" }
+ let(:title) { " #{url} " }
+
+ it "returns the inline onebox data" do
+ InlineOneboxer
+ .expects(:lookup)
+ .with(url, invalidate: true)
+ .returns(
+ url:,
+ title: "FEATURE: Add ProseMirror tab support",
+ css_class: "--gh-status-approved",
+ ignored: "value",
+ )
+
+ expect(result).to eq(
+ "url" => url,
+ "title" => "FEATURE: Add ProseMirror tab support",
+ "css_class" => "--gh-status-approved",
+ "ignored" => "value",
+ )
+ end
+ end
+
+ context "when the title contains anything besides a URL" do
+ let(:title) { "https://example.com extra text" }
+
+ it "returns nil without looking up the title" do
+ InlineOneboxer.expects(:lookup).never
+
+ expect(result).to be_nil
+ end
+ end
+
+ context "when the title has an unsupported URL scheme" do
+ let(:title) { "http://example.com/insecure" }
+
+ it "returns nil without looking up the title" do
+ InlineOneboxer.expects(:lookup).never
+
+ expect(result).to be_nil
+ end
+ end
+
+ context "when the inline onebox has no title" do
+ let(:title) { "https://example.com/no-title" }
+
+ it "returns nil" do
+ InlineOneboxer.expects(:lookup).with(title, invalidate: true).returns(url: title, title: nil)
+
+ expect(result).to be_nil
+ end
+ end
+
+ context "when lookup fails" do
+ let(:title) { "https://example.com/failure" }
+
+ it "returns nil" do
+ InlineOneboxer
+ .expects(:lookup)
+ .with(title, invalidate: true)
+ .raises(StandardError, "network failure")
+
+ expect(result).to be_nil
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/card_ordering_spec.rb b/plugins/boards/spec/services/boards/card_ordering_spec.rb
new file mode 100644
index 00000000000..a76901ff114
--- /dev/null
+++ b/plugins/boards/spec/services/boards/card_ordering_spec.rb
@@ -0,0 +1,201 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CardOrdering do
+ fab!(:admin)
+
+ before { enable_current_plugin }
+
+ fab!(:board) do
+ Boards::Board.create!(name: "Test", slug: "test-ordering", created_by_id: admin.id)
+ end
+ fab!(:column) { board.columns.create!(title: "Col A", position: 0) }
+ fab!(:recency_column) do
+ board.columns.create!(title: "Recent", position: 1, default_sort: "recency")
+ end
+
+ let(:gap) { described_class::GAP_SIZE }
+
+ def create_card(title:, position:, column: nil)
+ board.cards.create!(
+ card_type: :floater,
+ title: title,
+ column_id: (column || self.column).id,
+ position: position,
+ created_by_id: admin.id,
+ )
+ end
+
+ describe ".place_card!" do
+ it "places a card at the end when no after_card_id given" do
+ card1 = create_card(title: "First", position: 0)
+ card2 = create_card(title: "Second", position: gap)
+ new_card = create_card(title: "New", position: 99 * gap)
+
+ described_class.place_card!(new_card, column: column)
+
+ expect(new_card.reload.position).to be > card2.reload.position
+ expect(card1.reload.position).to be < card2.position
+ end
+
+ it "places a card after the specified card" do
+ card1 = create_card(title: "First", position: 0)
+ card2 = create_card(title: "Second", position: gap)
+ card3 = create_card(title: "Third", position: 2 * gap)
+
+ described_class.place_card!(card3, column: column, after_card_id: card1.id)
+
+ expect(card3.reload.position).to be > card1.reload.position
+ expect(card3.position).to be < card2.reload.position
+ end
+
+ it "places a card at position 0 when after_card_id is absent and column is empty" do
+ new_card = create_card(title: "Solo", position: 5 * gap)
+
+ described_class.place_card!(new_card, column: column)
+
+ expect(new_card.reload.position).to eq(0)
+ end
+
+ it "moves a card from one column to another" do
+ col_b = board.columns.create!(title: "Col B", position: 1)
+ card = create_card(title: "Mover", position: 0)
+ target_card = create_card(title: "Target", position: 0, column: col_b)
+
+ described_class.place_card!(card, column: col_b, after_card_id: target_card.id)
+
+ expect(card.reload.column_id).to eq(col_b.id)
+ expect(card.position).to be > target_card.reload.position
+ end
+
+ it "reorders within the same column" do
+ card1 = create_card(title: "First", position: 0)
+ card2 = create_card(title: "Second", position: gap)
+ card3 = create_card(title: "Third", position: 2 * gap)
+
+ described_class.place_card!(card1, column: column, after_card_id: card2.id)
+
+ expect(card1.reload.position).to be > card2.reload.position
+ expect(card1.position).to be < card3.reload.position
+ end
+
+ it "excludes the card itself from siblings during reorder" do
+ card1 = create_card(title: "First", position: 0)
+ card2 = create_card(title: "Second", position: gap)
+
+ described_class.place_card!(card2, column: column, after_card_id: card1.id)
+
+ expect(card1.reload.position).to be < card2.reload.position
+ end
+
+ it "handles invalid after_card_id by appending to end" do
+ card1 = create_card(title: "First", position: 0)
+ new_card = create_card(title: "New", position: 5 * gap)
+
+ described_class.place_card!(new_card, column: column, after_card_id: -999)
+
+ expect(new_card.reload.position).to be > card1.reload.position
+ end
+
+ it "places a card at position_first when position_first is true" do
+ card1 = create_card(title: "First", position: 0)
+ card2 = create_card(title: "Second", position: gap)
+ new_card = create_card(title: "New", position: 99 * gap)
+
+ described_class.place_card!(new_card, column: column, position_first: true)
+
+ expect(new_card.reload.position).to be < card1.reload.position
+ expect(card1.position).to be < card2.reload.position
+ end
+
+ it "handles gap exhaustion by rebalancing" do
+ card1 = create_card(title: "First", position: 1000)
+ card2 = create_card(title: "Second", position: 1001)
+ new_card = create_card(title: "Squeeze", position: 99 * gap)
+
+ described_class.place_card!(new_card, column: column, after_card_id: card1.id)
+
+ expect(new_card.reload.position).to be > card1.reload.position
+ expect(new_card.position).to be < card2.reload.position
+ end
+
+ it "supports negative positions from repeated insert-at-beginning" do
+ card1 = create_card(title: "First", position: 0)
+
+ new_card1 = create_card(title: "Before1", position: 99 * gap)
+ described_class.place_card!(new_card1, column: column, position_first: true)
+ expect(new_card1.reload.position).to be < card1.reload.position
+
+ new_card2 = create_card(title: "Before2", position: 99 * gap)
+ described_class.place_card!(new_card2, column: column, position_first: true)
+ expect(new_card2.reload.position).to be < new_card1.reload.position
+ end
+
+ it "moves cards into column sorted by recency at the beginning and stamps column_changed_at" do
+ existing = create_card(title: "Existing", position: 0, column: recency_column)
+ card = create_card(title: "Mover", position: gap, column: column)
+ previous_changed_at = 2.days.ago
+ card.update_column(:column_changed_at, previous_changed_at)
+
+ freeze_time do
+ described_class.place_card!(card, column: recency_column, after_card_id: existing.id)
+
+ card.reload
+ expect(card.column_id).to eq(recency_column.id)
+ expect(card.position).to be < existing.reload.position
+ expect(card.column_changed_at.to_i).to eq(Time.zone.now.to_i)
+ expect(card.column_changed_at.to_i).not_to eq(previous_changed_at.to_i)
+ end
+ end
+
+ it "rejects manual reordering inside column sorted by recency" do
+ card = create_card(title: "First", position: 0, column: recency_column)
+ other = create_card(title: "Second", position: gap, column: recency_column)
+
+ expect do
+ described_class.place_card!(card, column: recency_column, after_card_id: other.id)
+ end.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+
+ describe ".append_to_column!" do
+ it "sets position after the last card in the column" do
+ create_card(title: "First", position: 0)
+ create_card(title: "Second", position: gap)
+ new_card = board.cards.build(card_type: :floater, title: "Appended", created_by_id: admin.id)
+
+ described_class.append_to_column!(new_card, column)
+
+ expect(new_card.column_id).to eq(column.id)
+ expect(new_card.position).to eq(2 * gap)
+ end
+
+ it "sets position to GAP_SIZE for an empty column" do
+ new_card = board.cards.build(card_type: :floater, title: "First", created_by_id: admin.id)
+
+ described_class.append_to_column!(new_card, column)
+
+ expect(new_card.position).to eq(gap)
+ end
+
+ it "does not persist the card" do
+ new_card = board.cards.build(card_type: :floater, title: "Unsaved", created_by_id: admin.id)
+
+ described_class.append_to_column!(new_card, column)
+
+ expect(new_card).to be_new_record
+ end
+
+ it "prepends new cards in column sorted by recency" do
+ existing = create_card(title: "Existing", position: 0, column: recency_column)
+ new_card = board.cards.build(card_type: :floater, title: "Recent", created_by_id: admin.id)
+
+ freeze_time do
+ described_class.append_to_column!(new_card, recency_column)
+
+ expect(new_card.column_id).to eq(recency_column.id)
+ expect(new_card.position).to be < existing.position
+ expect(new_card.column_changed_at.to_i).to eq(Time.zone.now.to_i)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/check_board_topic_constraint_mismatches_spec.rb b/plugins/boards/spec/services/boards/check_board_topic_constraint_mismatches_spec.rb
new file mode 100644
index 00000000000..45039a9392b
--- /dev/null
+++ b/plugins/boards/spec/services/boards/check_board_topic_constraint_mismatches_spec.rb
@@ -0,0 +1,251 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CheckBoardTopicConstraintMismatches do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:id) }
+ it { is_expected.to validate_presence_of(:topic_id) }
+ it { is_expected.to validate_presence_of(:target_column_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:acting_user, :admin)
+ fab!(:write_group, :group)
+ fab!(:category)
+ fab!(:other_category, :category)
+ fab!(:third_category, :category)
+ fab!(:board_tag, :tag) { Fabricate(:tag, name: "board-filter") }
+ fab!(:other_board_tag, :tag) { Fabricate(:tag, name: "other-board-filter") }
+ fab!(:sibling_tag, :tag) { Fabricate(:tag, name: "sibling-column") }
+ fab!(:target_tag, :tag) { Fabricate(:tag, name: "target-column") }
+ fab!(:topic) { Fabricate(:topic, category:) }
+ fab!(:board) do
+ Fabricate(:boards_board, created_by: acting_user, additional_manage_groups: [write_group])
+ end
+ fab!(:sibling_column) { Fabricate(:boards_column, board:, tag: sibling_tag) }
+ fab!(:target_column) { Fabricate(:boards_column, board:) }
+
+ let(:params) { { id: board.id, topic_id: topic.id, target_column_id: target_column.id } }
+ let(:dependencies) { { guardian: acting_user.guardian } }
+
+ before { enable_current_plugin }
+
+ context "when the contract is invalid" do
+ let(:params) { { id: board.id, topic_id: topic.id } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the board is not found" do
+ let(:params) { super().merge(id: 0) }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when the user cannot edit the board" do
+ fab!(:acting_user, :user)
+
+ it { is_expected.to fail_a_policy(:can_edit_board) }
+ end
+
+ context "when the topic is not found" do
+ let(:params) { super().merge(topic_id: 0) }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when the topic is not visible to the user" do
+ fab!(:acting_user, :user)
+ fab!(:private_group, :group)
+ fab!(:private_category) { Fabricate(:private_category, group: private_group) }
+ fab!(:topic) { Fabricate(:topic, category: private_category) }
+
+ before { write_group.add(acting_user) }
+
+ it { is_expected.to fail_a_policy(:can_view_topic) }
+ end
+
+ context "when the target column is not found" do
+ let(:params) { super().merge(target_column_id: 0) }
+
+ it { is_expected.to fail_to_find_a_model(:target_column) }
+ end
+
+ context "when the target column belongs to another board" do
+ fab!(:other_board, :boards_board)
+ fab!(:other_board_column) { Fabricate(:boards_column, board: other_board) }
+
+ let(:params) { super().merge(target_column_id: other_board_column.id) }
+
+ it { is_expected.to fail_to_find_a_model(:target_column) }
+ end
+
+ context "without board constraints" do
+ it { is_expected.to run_successfully }
+
+ it "returns no required constraint fixes" do
+ expect(result[:categories_needed]).to be_empty
+ expect(result[:tags_needed]).to be_empty
+ end
+ end
+
+ context "with category constraints" do
+ context "when the topic's current category matches" do
+ before { board.update!(category_ids: [category.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns no categories" do
+ expect(result[:categories_needed]).to be_empty
+ end
+ end
+
+ context "when the topic's current category does not match" do
+ before { board.update!(category_ids: [other_category.id, third_category.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns every board category" do
+ expect(result[:categories_needed]).to contain_exactly(
+ other_category.id,
+ third_category.id,
+ )
+ end
+ end
+
+ context "when the target column moves the topic to a matching category" do
+ before do
+ board.update!(category_ids: [other_category.id])
+ target_column.update!(move_to_category_id: other_category.id)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "uses the target category instead of the topic's current category" do
+ expect(result[:categories_needed]).to be_empty
+ end
+ end
+
+ context "when the target column moves a matching topic to a nonmatching category" do
+ before do
+ board.update!(category_ids: [category.id])
+ target_column.update!(move_to_category_id: other_category.id)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns every board category" do
+ expect(result[:categories_needed]).to eq([category.id])
+ end
+ end
+ end
+
+ context "with tag constraints" do
+ context "when a current non-column topic tag matches" do
+ fab!(:topic) { Fabricate(:topic, category:, tags: [board_tag]) }
+
+ before { board.update!(tag_ids: [board_tag.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns no tags" do
+ expect(result[:tags_needed]).to be_empty
+ end
+ end
+
+ context "when no effective topic tag matches" do
+ before { board.update!(tag_ids: [board_tag.id, other_board_tag.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns every board tag" do
+ expect(result[:tags_needed]).to contain_exactly(board_tag.name, other_board_tag.name)
+ end
+ end
+
+ context "when a board tag is not visible to the user" do
+ fab!(:acting_user, :user)
+ fab!(:hidden_board_tag, :tag)
+
+ before do
+ write_group.add(acting_user)
+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_board_tag.name])
+ board.update!(tag_ids: [board_tag.id, hidden_board_tag.id])
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not return the restricted tag name" do
+ expect(result[:tags_needed]).to eq([board_tag.name])
+ end
+ end
+
+ context "when the target column tag matches" do
+ before do
+ board.update!(tag_ids: [target_tag.id])
+ target_column.update!(tag_id: target_tag.id)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "includes the target column tag in the effective tags" do
+ expect(result[:tags_needed]).to be_empty
+ end
+ end
+
+ context "when only a sibling column tag matches" do
+ fab!(:topic) { Fabricate(:topic, category:, tags: [sibling_tag]) }
+
+ before do
+ board.update!(tag_ids: [sibling_tag.id])
+ target_column.update!(tag_id: target_tag.id)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns the removed sibling tag" do
+ expect(result[:tags_needed]).to eq([sibling_tag.name])
+ end
+ end
+
+ context "when an unrelated board tag remains after sibling tag removal" do
+ fab!(:topic) { Fabricate(:topic, category:, tags: [sibling_tag, board_tag]) }
+
+ before do
+ board.update!(tag_ids: [board_tag.id])
+ target_column.update!(tag_id: target_tag.id)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns no tags" do
+ expect(result[:tags_needed]).to be_empty
+ end
+ end
+
+ context "when an untagged target removes every column tag" do
+ fab!(:topic) { Fabricate(:topic, category:, tags: [sibling_tag]) }
+
+ before { board.update!(tag_ids: [sibling_tag.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns the removed column tag" do
+ expect(result[:tags_needed]).to eq([sibling_tag.name])
+ end
+ end
+ end
+
+ context "with category and tag constraints" do
+ before { board.update!(category_ids: [other_category.id], tag_ids: [board_tag.id]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns both required constraint fixes" do
+ expect(result[:categories_needed]).to eq([other_category.id])
+ expect(result[:tags_needed]).to eq([board_tag.name])
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/clear_column_spec.rb b/plugins/boards/spec/services/boards/clear_column_spec.rb
new file mode 100644
index 00000000000..e7f158a4f89
--- /dev/null
+++ b/plugins/boards/spec/services/boards/clear_column_spec.rb
@@ -0,0 +1,144 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::ClearColumn do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:column_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:reader, :user)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+ fab!(:category) { Fabricate(:category, name: "Boards") }
+ fab!(:topic1) { Fabricate(:topic, category: category) }
+ fab!(:topic2) { Fabricate(:topic, category: category) }
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board-cc", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "Col", position: 0) }
+ fab!(:other_column) { board.columns.create!(title: "Other", position: 1) }
+
+ let(:dependencies) { { guardian: writer.guardian } }
+ let(:params) { { board_id: board.id, column_id: column.id } }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ read_group.add(reader)
+ end
+
+ context "with a mix of floater and topic cards" do
+ let!(:floater1) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Floater 1",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+ let!(:floater2) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Floater 2",
+ column_id: column.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+ let!(:topic_card1) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic1.id,
+ column_id: column.id,
+ position: 2,
+ created_by_id: admin.id,
+ )
+ end
+ let!(:topic_card2) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic2.id,
+ column_id: column.id,
+ position: 3,
+ created_by_id: admin.id,
+ )
+ end
+ let!(:other_column_card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Other",
+ column_id: other_column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "destroys floater cards" do
+ result
+ expect(Boards::Card.find_by(id: floater1.id)).to be_nil
+ expect(Boards::Card.find_by(id: floater2.id)).to be_nil
+ end
+
+ it "destroys topic cards" do
+ result
+ expect(Boards::Card.find_by(id: topic_card1.id)).to be_nil
+ expect(Boards::Card.find_by(id: topic_card2.id)).to be_nil
+ end
+
+ it "does not affect cards in other columns" do
+ result
+ expect(Boards::Card.find_by(id: other_column_card.id)).to be_present
+ end
+
+ it "preserves hidden topic cards" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ hidden_topic = Fabricate(:topic, category: private_category)
+ hidden_card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: hidden_topic.id,
+ column_id: column.id,
+ position: 4,
+ created_by_id: admin.id,
+ )
+
+ result
+
+ expect(Boards::Card.exists?(hidden_card.id)).to eq(true)
+ end
+ end
+
+ context "when column is not found" do
+ let(:params) { { board_id: board.id, column_id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:column) }
+ end
+
+ context "when user cannot write" do
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_write) }
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/column_tag_resolver_spec.rb b/plugins/boards/spec/services/boards/column_tag_resolver_spec.rb
new file mode 100644
index 00000000000..8f663c6ddf7
--- /dev/null
+++ b/plugins/boards/spec/services/boards/column_tag_resolver_spec.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::ColumnTagResolver do
+ fab!(:admin)
+ fab!(:todo_tag, :tag) { Fabricate(:tag, name: "todo") }
+ fab!(:doing_tag, :tag) { Fabricate(:tag, name: "doing") }
+ fab!(:done_tag, :tag) { Fabricate(:tag, name: "done") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated") }
+ fab!(:board) do
+ Boards::Board.create!(name: "Board", slug: "resolver-board", created_by_id: admin.id)
+ end
+ fab!(:todo_column) { board.columns.create!(title: "Todo", position: 0, tag_id: todo_tag.id) }
+ fab!(:doing_column) { board.columns.create!(title: "Doing", position: 1, tag_id: doing_tag.id) }
+ fab!(:backlog_column) { board.columns.create!(title: "Backlog", position: 2) }
+
+ before { enable_current_plugin }
+
+ describe ".resolve_tag_ids" do
+ it "adds the target column tag and removes sibling column tags" do
+ resolved_tag_ids =
+ described_class.resolve_tag_ids(
+ current_tag_ids: [todo_tag.id, unrelated_tag.id],
+ column: doing_column,
+ )
+
+ expect(resolved_tag_ids).to contain_exactly(doing_tag.id, unrelated_tag.id)
+ end
+
+ it "removes all board column tags when resolving to an untagged column" do
+ resolved_tag_ids =
+ described_class.resolve_tag_ids(
+ current_tag_ids: [todo_tag.id, doing_tag.id, unrelated_tag.id],
+ column: backlog_column,
+ )
+
+ expect(resolved_tag_ids).to contain_exactly(unrelated_tag.id)
+ end
+
+ it "preserves a target column tag already present on the card" do
+ resolved_tag_ids =
+ described_class.resolve_tag_ids(
+ current_tag_ids: [doing_tag.id, unrelated_tag.id],
+ column: doing_column,
+ )
+
+ expect(resolved_tag_ids).to contain_exactly(doing_tag.id, unrelated_tag.id)
+ end
+
+ it "normalizes duplicate and string tag ids" do
+ resolved_tag_ids =
+ described_class.resolve_tag_ids(
+ current_tag_ids: [todo_tag.id.to_s, todo_tag.id, unrelated_tag.id.to_s],
+ column: doing_column,
+ )
+
+ expect(resolved_tag_ids).to contain_exactly(doing_tag.id, unrelated_tag.id)
+ end
+
+ it "does not add a stale target column tag" do
+ stale_tag_id = done_tag.id
+ done_tag.destroy!
+ doing_column.update_column(:tag_id, stale_tag_id)
+
+ resolved_tag_ids =
+ described_class.resolve_tag_ids(current_tag_ids: [unrelated_tag.id], column: doing_column)
+
+ expect(resolved_tag_ids).to contain_exactly(unrelated_tag.id)
+ end
+
+ it "ignores stale board column tags when resolving sibling tags" do
+ stale_tag_id = done_tag.id
+ done_tag.destroy!
+ board.columns.create!(title: "Stale", position: 3, tag_id: stale_tag_id)
+
+ resolved_tag_ids =
+ described_class.resolve_tag_ids(
+ current_tag_ids: [doing_tag.id, unrelated_tag.id],
+ column: todo_column,
+ )
+
+ expect(resolved_tag_ids).to contain_exactly(todo_tag.id, unrelated_tag.id)
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/columns_replacer_spec.rb b/plugins/boards/spec/services/boards/columns_replacer_spec.rb
new file mode 100644
index 00000000000..ca2bcb02459
--- /dev/null
+++ b/plugins/boards/spec/services/boards/columns_replacer_spec.rb
@@ -0,0 +1,285 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::ColumnsReplacer do
+ fab!(:admin)
+ fab!(:board) { Boards::Board.create!(name: "Test", slug: "test", created_by_id: admin.id) }
+
+ before { enable_current_plugin }
+
+ describe ".replace!" do
+ it "creates new columns from payload" do
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "title" => "Backlog" }, { "title" => "Done", "icon" => "check" }],
+ user: admin,
+ )
+
+ columns = board.columns.order(:position)
+ expect(columns.count).to eq(2)
+ expect(columns.first.title).to eq("Backlog")
+ expect(columns.first.position).to eq(0)
+ expect(columns.last.title).to eq("Done")
+ expect(columns.last.icon).to eq("check")
+ expect(columns.last.default_sort).to eq("priority")
+ expect(columns.last.position).to eq(1)
+ end
+
+ it "updates existing columns by id" do
+ col = board.columns.create!(title: "Old", position: 0)
+
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "id" => col.id, "title" => "New" }],
+ user: admin,
+ )
+
+ expect(col.reload.title).to eq("New")
+ end
+
+ it "removes columns not in the payload" do
+ col1 = board.columns.create!(title: "Keep", position: 0)
+ col2 = board.columns.create!(title: "Remove", position: 1)
+
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "id" => col1.id, "title" => "Keep" }],
+ user: admin,
+ )
+
+ expect(board.columns.reload.pluck(:id)).to contain_exactly(col1.id)
+ expect(Boards::Column.find_by(id: col2.id)).to be_nil
+ end
+
+ it "deletes floater cards in removed columns" do
+ col = board.columns.create!(title: "Gone", position: 0)
+ board.cards.create!(
+ card_type: :floater,
+ title: "Floater",
+ column_id: col.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ Boards::ColumnsReplacer.replace!(board:, columns_payload: [], user: admin)
+
+ expect(board.cards.reload.count).to eq(0)
+ end
+
+ it "deletes topic cards in removed columns" do
+ topic = Fabricate(:topic)
+ col = board.columns.create!(title: "Gone", position: 0)
+ card =
+ board
+ .cards
+ .find_or_initialize_by(topic_id: topic.id)
+ .tap do |c|
+ c.assign_attributes(
+ card_type: :topic,
+ column_id: col.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ c.save!
+ end
+
+ Boards::ColumnsReplacer.replace!(board:, columns_payload: [], user: admin)
+
+ expect(Boards::Card.find_by(id: card.id)).to be_nil
+ end
+
+ it "persists default sort" do
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "title" => "Recent", "default_sort" => "recency" }],
+ user: admin,
+ )
+
+ expect(board.columns.last.default_sort).to eq("recency")
+ end
+
+ it "rejects invalid default sort" do
+ expect {
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "title" => "Broken", "default_sort" => "random" }],
+ user: admin,
+ )
+ }.to raise_error(Discourse::InvalidParameters)
+ end
+
+ describe "when a tag is provided" do
+ fab!(:tag)
+
+ it "creates a new column with the tag" do
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "title" => "Backlog", "tag_name" => tag.name }],
+ user: admin,
+ )
+
+ expect(board.columns.last.tag).to eq(tag)
+ end
+
+ it "creates the tag when it doesn't exist and the user can create tags" do
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "title" => "Backlog", "tag_name" => "brand-new" }],
+ user: admin,
+ )
+
+ expect(board.columns.last.tag.name).to eq("brand-new")
+ end
+
+ it "raises an error if the tag is not found and the user cannot create tags" do
+ user = Fabricate(:user)
+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:staff]
+
+ expect {
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "title" => "Backlog", "tag_name" => "unknown" }],
+ user: user,
+ )
+ }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.unknown_tag_name", tag_name: "unknown"),
+ )
+ end
+
+ it "raises an error if a tag has already been used for another column" do
+ expect {
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [
+ { "title" => "Backlog", "tag_name" => tag.name },
+ { "title" => "Done", "tag_name" => tag.name },
+ ],
+ user: admin,
+ )
+ }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.cannot_use_same_tag_multiple_times", tag_name: tag.name),
+ )
+ end
+
+ it "applies a new column tag to existing floater cards" do
+ column = board.columns.create!(title: "Backlog", position: 0)
+ unrelated_tag = Fabricate(:tag, name: "unrelated")
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing floater",
+ tag_ids: [unrelated_tag.id],
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "id" => column.id, "title" => "Backlog", "tag_name" => tag.name }],
+ user: admin,
+ )
+
+ expect(card.reload.tag_ids).to contain_exactly(tag.id, unrelated_tag.id)
+ end
+
+ it "replaces a changed column tag on existing floater cards" do
+ old_tag = Fabricate(:tag, name: "old-column")
+ new_tag = Fabricate(:tag, name: "new-column")
+ column = board.columns.create!(title: "Doing", position: 0, tag_id: old_tag.id)
+ unrelated_tag = Fabricate(:tag, name: "preserved")
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing floater",
+ tag_ids: [old_tag.id, unrelated_tag.id],
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "id" => column.id, "title" => "Doing", "tag_name" => new_tag.name }],
+ user: admin,
+ )
+
+ expect(card.reload.tag_ids).to contain_exactly(new_tag.id, unrelated_tag.id)
+ end
+
+ it "normalizes floater cards in other columns when a new column tag is assigned" do
+ todo_tag = Fabricate(:tag, name: "todo")
+ blocked_tag = Fabricate(:tag, name: "blocked")
+ column = board.columns.create!(title: "Todo", position: 0, tag_id: todo_tag.id)
+ blocked_column = board.columns.create!(title: "Blocked", position: 1)
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing floater",
+ tag_ids: [todo_tag.id, blocked_tag.id],
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [
+ { "id" => column.id, "title" => "Todo", "tag_name" => todo_tag.name },
+ { "id" => blocked_column.id, "title" => "Blocked", "tag_name" => blocked_tag.name },
+ ],
+ user: admin,
+ )
+
+ expect(card.reload.tag_ids).to contain_exactly(todo_tag.id)
+ end
+
+ it "rolls back column changes when loose-card tag enforcement fails" do
+ column = board.columns.create!(title: "Doing", position: 0)
+ allow(Boards::LooseCardTagMutator).to receive(:apply_to_column!).and_raise(
+ ActiveRecord::RecordInvalid,
+ )
+
+ expect {
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [{ "id" => column.id, "title" => "Doing", "tag_name" => tag.name }],
+ user: admin,
+ )
+ }.to raise_error(ActiveRecord::RecordInvalid)
+
+ expect(column.reload.tag_id).to be_nil
+ end
+
+ it "removes board column tags when a column tag is removed" do
+ old_tag = Fabricate(:tag, name: "old-column")
+ sibling_tag = Fabricate(:tag, name: "sibling-column")
+ unrelated_tag = Fabricate(:tag, name: "preserved")
+ column = board.columns.create!(title: "Doing", position: 0, tag_id: old_tag.id)
+ sibling_column =
+ board.columns.create!(title: "Sibling", position: 1, tag_id: sibling_tag.id)
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing floater",
+ tag_ids: [old_tag.id, sibling_tag.id, unrelated_tag.id],
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ Boards::ColumnsReplacer.replace!(
+ board:,
+ columns_payload: [
+ { "id" => column.id, "title" => "Doing" },
+ { "id" => sibling_column.id, "title" => "Sibling", "tag_name" => sibling_tag.name },
+ ],
+ user: admin,
+ )
+
+ expect(card.reload.tag_ids).to contain_exactly(unrelated_tag.id)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/create_board_spec.rb b/plugins/boards/spec/services/boards/create_board_spec.rb
new file mode 100644
index 00000000000..bd9cd0c553d
--- /dev/null
+++ b/plugins/boards/spec/services/boards/create_board_spec.rb
@@ -0,0 +1,156 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CreateBoard do
+ describe Boards::CreateBoard::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:name) }
+ end
+
+ describe ".call" do
+ subject(:result) { Boards::CreateBoard.call(params:, raw_board_params: raw, **dependencies) }
+
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+
+ let(:raw) { { "name" => "New Board", "slug" => "new-board" } }
+ let(:params) { raw }
+ let(:dependencies) { { guardian: manager.guardian } }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ end
+
+ context "when contract is invalid" do
+ let(:raw) { { "slug" => "no-name" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage boards" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates the board" do
+ expect { result }.to change { Boards::Board.count }.by(1)
+ board = result[:board]
+ expect(board.name).to eq("New Board")
+ expect(board.slug).to eq("new-board")
+ expect(board.created_by_id).to eq(manager.id)
+ end
+
+ it "creates mandatory ACLs when ACL params are omitted" do
+ result
+
+ manage_acl = AccessControlList.find_by!(target: result[:board], permission: "manage")
+ expect(manage_acl.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])
+ end
+
+ it "creates mandatory ACLs when ACL params are empty" do
+ raw["acl"] = []
+
+ result
+
+ manage_acl = AccessControlList.find_by!(target: result[:board], permission: "manage")
+ expect(manage_acl.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])
+ end
+
+ it "creates a board history" do
+ expect { result }.to change { Boards::BoardHistory.count }.by(1)
+ board = Boards::Board.last
+ expect(board.history.first).to have_attributes(
+ action: "board_created",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ )
+ end
+
+ context "with tag_names" do
+ fab!(:admin)
+ fab!(:existing_tag, :tag)
+
+ let(:raw) do
+ {
+ "name" => "Tagged",
+ "slug" => "tagged",
+ "tag_names" => [existing_tag.name, "brand-new"],
+ }
+ end
+
+ context "when the user can create tags" do
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it "resolves existing tags and creates new ones" do
+ board = result[:board]
+ expect(board.tag_ids).to contain_exactly(
+ existing_tag.id,
+ Tag.find_by(name: "brand-new").id,
+ )
+ end
+ end
+
+ it "fails when the user cannot create tags and a tag is missing" do
+ expect(result).to be_failure
+ expect(result["result.model.board"].exception).to be_a(Discourse::InvalidParameters)
+ end
+
+ context "when an existing tag is not visible to the user" do
+ fab!(:restricted_tag, :tag)
+
+ let(:raw) do
+ { "name" => "Tagged", "slug" => "tagged", "tag_names" => [restricted_tag.name] }
+ end
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tags: [restricted_tag]) }
+
+ it "does not resolve the hidden tag" do
+ expect(result).to be_failure
+ expect(result["result.model.board"].exception).to be_a(Discourse::InvalidParameters)
+ end
+ end
+ end
+
+ context "with columns" do
+ let(:raw) do
+ {
+ "name" => "With Columns",
+ "columns" => [{ "title" => "Backlog" }, { "title" => "Done" }],
+ }
+ end
+
+ it "creates columns" do
+ result
+ board = result[:board]
+ expect(board.columns.count).to eq(2)
+ expect(board.columns.order(:position).pluck(:title)).to eq(%w[Backlog Done])
+ end
+
+ context "when a column tag is not visible to the user" do
+ fab!(:restricted_tag, :tag)
+
+ let(:raw) do
+ {
+ "name" => "With Columns",
+ "columns" => [{ "title" => "Restricted", "tag_name" => restricted_tag.name }],
+ }
+ end
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tags: [restricted_tag]) }
+
+ it "does not resolve the hidden tag" do
+ expect { result }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.unknown_tag_name", tag_name: restricted_tag.name),
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/create_card_spec.rb b/plugins/boards/spec/services/boards/create_card_spec.rb
new file mode 100644
index 00000000000..5a6df4349a4
--- /dev/null
+++ b/plugins/boards/spec/services/boards/create_card_spec.rb
@@ -0,0 +1,217 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CreateCard do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:column_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:reader, :user)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+ fab!(:category)
+ fab!(:tag)
+ fab!(:topic) { Fabricate(:topic, category: category) }
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "To Do", position: 0) }
+ fab!(:recency_column) do
+ board.columns.create!(title: "Recent", position: 1, default_sort: "recency")
+ end
+
+ let(:dependencies) { { guardian: writer.guardian } }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ write_group.add(admin)
+ read_group.add(reader)
+ end
+
+ context "when creating a floater card" do
+ let(:params) { { board_id: board.id, column_id: column.id, title: "New Task" } }
+
+ it { is_expected.to run_successfully }
+
+ it "creates a floater card" do
+ card = result[:card]
+ expect(card.card_type).to eq("floater")
+ expect(card.title).to eq("New Task")
+ expect(card.column_id).to eq(column.id)
+ expect(card.column_changed_at).to be_present
+ expect(card.created_by_id).to eq(writer.id)
+ end
+
+ it "creates a card history record" do
+ expect { result }.to change { Boards::CardHistory.where(action: :card_created).count }.by(1)
+ expect(Boards::CardHistory.where(action: :card_created).last).to have_attributes(
+ acting_user_id: writer.id,
+ board_id: board.id,
+ )
+ end
+ end
+
+ context "when creating a floater card with a URL-only title" do
+ let(:url) { "https://github.com/discourse/discourse/pull/42462" }
+ let(:params) { { board_id: board.id, column_id: column.id, title: url } }
+
+ it "creates the card without resolving the onebox inline" do
+ Boards::Action::CardInlineOnebox.expects(:call).never
+
+ expect(result[:card].inline_onebox_data).to be_nil
+ end
+ end
+
+ context "when creating a floater card in a column sorted by recency" do
+ let(:params) { { board_id: board.id, column_id: recency_column.id, title: "Recent Task" } }
+
+ before do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing",
+ column_id: recency_column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ it "places it at the beginning" do
+ expect(result[:card].position).to be < 0
+ expect(result[:card].column_changed_at).to be_present
+ end
+ end
+
+ context "when creating a floater card with tag ids" do
+ let(:params) do
+ { board_id: board.id, column_id: column.id, title: "Tagged", tag_ids: [tag.id] }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "persists tag ids" do
+ expect(result[:card].tag_ids).to eq([tag.id])
+ end
+ end
+
+ context "when creating a floater card with a hidden tag id" do
+ fab!(:hidden_tag, :tag) { Fabricate(:tag, name: "staff-boards") }
+
+ let(:params) do
+ { board_id: board.id, column_id: column.id, title: "Tagged", tag_ids: [hidden_tag.id] }
+ end
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name]) }
+
+ it "raises InvalidParameters" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+
+ context "when creating a floater card in a tagged column" do
+ fab!(:column_tag, :tag) { Fabricate(:tag, name: "column-tag") }
+ fab!(:sibling_tag, :tag) { Fabricate(:tag, name: "sibling-tag") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated-tag") }
+ fab!(:tagged_column) do
+ board.columns.create!(title: "Tagged", position: 3, tag_id: column_tag.id)
+ end
+
+ let(:params) do
+ {
+ board_id: board.id,
+ column_id: tagged_column.id,
+ title: "Tagged floater",
+ tag_ids: [sibling_tag.id, unrelated_tag.id],
+ }
+ end
+
+ before { board.columns.create!(title: "Sibling", position: 4, tag_id: sibling_tag.id) }
+
+ it "applies the column tag using the column tag resolution rules" do
+ expect(result[:card].tag_ids).to contain_exactly(column_tag.id, unrelated_tag.id)
+ end
+ end
+
+ context "when creating a topic card" do
+ let(:params) { { board_id: board.id, column_id: column.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it { is_expected.to run_successfully }
+
+ it "creates a topic card" do
+ card = result[:card]
+ expect(card.card_type).to eq("topic")
+ expect(card.topic_id).to eq(topic.id)
+ expect(card.column_id).to eq(column.id)
+ end
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, column_id: column.id, title: "Test" } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when column is not found" do
+ let(:params) { { board_id: board.id, column_id: 0, title: "Test" } }
+
+ it { is_expected.to fail_to_find_a_model(:column) }
+ end
+
+ context "when user cannot write" do
+ let(:params) { { board_id: board.id, column_id: column.id, title: "Test" } }
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_write) }
+ end
+
+ context "when topic does not exist" do
+ let(:params) { { board_id: board.id, column_id: column.id, topic_id: -1 } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it "raises NotFound" do
+ expect { result }.to raise_error(Discourse::NotFound)
+ end
+ end
+
+ context "when user cannot see the topic" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }
+ let(:params) { { board_id: board.id, column_id: column.id, topic_id: private_topic.id } }
+
+ it "raises NotFound" do
+ expect { result }.to raise_error(Discourse::NotFound)
+ end
+ end
+
+ context "when creating a card for a category definition topic" do
+ fab!(:category_with_def, :category_with_definition)
+ let(:params) do
+ { board_id: board.id, column_id: column.id, topic_id: category_with_def.topic_id }
+ end
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it "raises an error" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/create_column_spec.rb b/plugins/boards/spec/services/boards/create_column_spec.rb
new file mode 100644
index 00000000000..83673432c81
--- /dev/null
+++ b/plugins/boards/spec/services/boards/create_column_spec.rb
@@ -0,0 +1,152 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::CreateColumn do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:title) }
+ it { is_expected.to allow_value(nil, "f0a", "1A2B3C").for(:color) }
+ it { is_expected.not_to allow_value("#1A2B3C", "purple").for(:color) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+ fab!(:board) do
+ Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+ end
+
+ let(:params) do
+ { board_id: board.id, title: "Backlog", color: "1A2B3C", default_sort: "priority" }
+ end
+ let(:dependencies) { { guardian: manager.guardian } }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { board_id: board.id, title: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, title: "Backlog" } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when user cannot manage boards" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a column at the next position" do
+ board.columns.create!(title: "Existing", position: 0)
+
+ expect { result }.to change { board.columns.count }.by(1)
+ expect(result[:column]).to have_attributes(title: "Backlog", color: "1A2B3C", position: 1)
+ end
+
+ it "tracks the column added history" do
+ result
+
+ expect(board.history.last).to have_attributes(
+ action: "column_added",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ column_id: result[:column].id,
+ details: {
+ "title" => "Backlog",
+ "color" => "1A2B3C",
+ "tag_id" => nil,
+ "move_to_category_id" => nil,
+ "move_to_assigned" => nil,
+ "move_to_status" => nil,
+ },
+ )
+ end
+
+ it "publishes a board_updated event" do
+ messages = MessageBus.track_publish("/boards/#{board.id}") { result }
+
+ expect(messages.map { |message| message.data[:type] }).to include("board_updated")
+ end
+
+ context "with a tag name" do
+ fab!(:tag)
+
+ let(:params) { { board_id: board.id, title: "Tagged", tag_name: tag.name } }
+
+ it "assigns the visible tag" do
+ result
+
+ expect(result[:column].reload.tag_id).to eq(tag.id)
+ end
+
+ it "rejects duplicate sibling tags" do
+ board.columns.create!(title: "Existing", position: 0, tag_id: tag.id)
+
+ expect(result).to fail_to_find_a_model(:column)
+ expect(result["result.model.column"].exception).to be_a(Discourse::InvalidParameters)
+ expect(result["result.model.column"].exception.message).to eq(
+ I18n.t("boards.errors.cannot_use_same_tag_multiple_times", tag_name: tag.name),
+ )
+ end
+ end
+
+ context "when a tag is not visible to the user" do
+ fab!(:restricted_tag, :tag)
+
+ let(:params) { { board_id: board.id, title: "Hidden", tag_name: restricted_tag.name } }
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tags: [restricted_tag]) }
+
+ it "does not resolve the hidden tag" do
+ expect(result).to fail_to_find_a_model(:column)
+ expect(result["result.model.column"].exception).to be_a(Discourse::InvalidParameters)
+ expect(result["result.model.column"].exception.message).to eq(
+ I18n.t("boards.errors.unknown_tag_name", tag_name: restricted_tag.name),
+ )
+ end
+ end
+
+ context "when default sort is invalid" do
+ let(:params) { { board_id: board.id, title: "Broken", default_sort: "random" } }
+
+ it "raises an invalid parameters error" do
+ expect(result).to fail_to_find_a_model(:column)
+ expect(result["result.model.column"].exception).to be_a(Discourse::InvalidParameters)
+ end
+ end
+
+ context "when loose-card tag enforcement fails" do
+ fab!(:tag)
+
+ let(:params) { { board_id: board.id, title: "Tagged", tag_name: tag.name } }
+
+ before do
+ allow(Boards::LooseCardTagMutator).to receive(:apply_to_column!).and_raise(
+ ActiveRecord::RecordInvalid,
+ )
+ end
+
+ it "rolls back the created column" do
+ expect(result).to fail_to_find_a_model(:column)
+ expect(result["result.model.column"].exception).to be_a(ActiveRecord::RecordInvalid)
+ expect(board.columns.where(title: "Tagged")).to be_empty
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/destroy_board_spec.rb b/plugins/boards/spec/services/boards/destroy_board_spec.rb
new file mode 100644
index 00000000000..f0074fe25fe
--- /dev/null
+++ b/plugins/boards/spec/services/boards/destroy_board_spec.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::DestroyBoard do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+ fab!(:board) do
+ Boards::Board.create!(name: "Delete Me", slug: "delete-me", created_by_id: admin.id)
+ end
+
+ let(:params) { { id: board.id } }
+ let(:dependencies) { { guardian: manager.guardian } }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when board is not found" do
+ let(:params) { { id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when user cannot destroy the board based on the ACL" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_destroy) }
+ end
+
+ context "when everything is valid" do
+ before do
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "manage",
+ groups: [manage_group],
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "destroys the board" do
+ result
+ expect(Boards::Board.find_by(id: board.id)).to be_nil
+ end
+
+ it "creates a board deletion history" do
+ result
+ expect(board.history.first).to have_attributes(
+ action: "board_deleted",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/destroy_card_spec.rb b/plugins/boards/spec/services/boards/destroy_card_spec.rb
new file mode 100644
index 00000000000..df0f4e091e6
--- /dev/null
+++ b/plugins/boards/spec/services/boards/destroy_card_spec.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::DestroyCard do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:reader, :user)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+ fab!(:category) { Fabricate(:category, name: "Boards") }
+ fab!(:topic) { Fabricate(:topic, category: category) }
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board-dc", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "Col", position: 0) }
+
+ let(:dependencies) { { guardian: writer.guardian } }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ read_group.add(reader)
+ end
+
+ context "when destroying a floater card" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Delete",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id } }
+
+ it { is_expected.to run_successfully }
+
+ it "destroys the card" do
+ result
+ expect(Boards::Card.find_by(id: card.id)).to be_nil
+ end
+ end
+
+ context "when destroying a topic card that doesn't match filter" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id } }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when topic card is hidden from the user" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }
+
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: private_topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id } }
+
+ it { is_expected.to fail_a_policy(:can_see_card_topic) }
+ end
+
+ context "when topic card is covered by board filter" do
+ before { board.update!(category_ids: [category.id]) }
+
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id } }
+
+ it { is_expected.to run_successfully }
+
+ it "destroys the card" do
+ result
+ expect(Boards::Card.find_by(id: card.id)).to be_nil
+ end
+ end
+
+ context "when card is not found" do
+ let(:params) { { board_id: board.id, id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:card) }
+ end
+
+ context "when user cannot write" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Protected",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id } }
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_write) }
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/destroy_column_spec.rb b/plugins/boards/spec/services/boards/destroy_column_spec.rb
new file mode 100644
index 00000000000..4b6a8cd3a7c
--- /dev/null
+++ b/plugins/boards/spec/services/boards/destroy_column_spec.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::DestroyColumn do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+ fab!(:board) do
+ Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+ end
+ fab!(:first_column) { board.columns.create!(title: "First", position: 0) }
+ fab!(:column) { board.columns.create!(title: "Second", position: 1) }
+ fab!(:third_column) { board.columns.create!(title: "Third", position: 2) }
+
+ let(:params) { { board_id: board.id, id: column.id } }
+ let(:dependencies) { { guardian: manager.guardian } }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { board_id: board.id, id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, id: column.id } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when column is not found" do
+ let(:params) { { board_id: board.id, id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:column) }
+ end
+
+ context "when user cannot manage boards" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "deletes the column and its cards" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Card",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ result
+
+ expect(Boards::Column.exists?(column.id)).to eq(false)
+ expect(Boards::Card.exists?(card.id)).to eq(false)
+ end
+
+ it "compacts remaining column positions" do
+ result
+
+ expect(first_column.reload.position).to eq(0)
+ expect(third_column.reload.position).to eq(1)
+ end
+
+ it "tracks the column deleted history" do
+ result
+
+ expect(board.history.last).to have_attributes(
+ action: "column_deleted",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ column_id: column.id,
+ details: {
+ "title" => "Second",
+ },
+ )
+ end
+
+ it "publishes a board_updated event" do
+ messages = MessageBus.track_publish("/boards/#{board.id}") { result }
+
+ expect(messages.map { |message| message.data[:type] }).to include("board_updated")
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/move_column_spec.rb b/plugins/boards/spec/services/boards/move_column_spec.rb
new file mode 100644
index 00000000000..9800c0ff238
--- /dev/null
+++ b/plugins/boards/spec/services/boards/move_column_spec.rb
@@ -0,0 +1,145 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::MoveColumn do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:column_id) }
+ it { is_expected.to validate_presence_of(:direction) }
+ it { is_expected.to validate_inclusion_of(:direction).in_array([-1, 1]) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:user)
+ fab!(:sales_tag, :tag) { Fabricate(:tag, name: "sales") }
+ fab!(:star_tag, :tag) { Fabricate(:tag, name: "star") }
+ fab!(:board) do
+ Boards::Board.create!(
+ name: "Sales",
+ slug: "sales-mc",
+ tag_ids: [sales_tag.id],
+ created_by_id: admin.id,
+ )
+ end
+ fab!(:managers, :group) { Fabricate(:group) }
+ fab!(:col_star) { board.columns.create!(title: "Star", position: 0, tag_id: star_tag.id) }
+ fab!(:col_progress) { board.columns.create!(title: "In Progress", position: 1) }
+ fab!(:col_done) { board.columns.create!(title: "Done", position: 2) }
+
+ let(:params) { { board_id: board.id, column_id: col_progress.id, direction: 1 } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ enable_current_plugin
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "manage",
+ groups: [managers],
+ )
+ SiteSetting.boards_manage_board_allowed_groups = managers.id.to_s
+ managers.add(admin)
+ end
+
+ context "when moving a column right" do
+ it { is_expected.to run_successfully }
+
+ it "swaps positions with the right neighbor" do
+ result
+ expect(col_progress.reload.position).to eq(2)
+ expect(col_done.reload.position).to eq(1)
+ end
+
+ it "does not change the unaffected column" do
+ result
+ expect(col_star.reload.position).to eq(0)
+ end
+
+ it "returns the new column order" do
+ expect(result[:column_order]).to eq([col_star.id, col_done.id, col_progress.id])
+ end
+ end
+
+ context "when moving a column left" do
+ let(:params) { { board_id: board.id, column_id: col_progress.id, direction: -1 } }
+
+ it { is_expected.to run_successfully }
+
+ it "swaps positions with the left neighbor" do
+ result
+ expect(col_progress.reload.position).to eq(0)
+ expect(col_star.reload.position).to eq(1)
+ end
+
+ it "returns the new column order" do
+ expect(result[:column_order]).to eq([col_progress.id, col_star.id, col_done.id])
+ end
+ end
+
+ context "when moving leftmost column left" do
+ let(:params) { { board_id: board.id, column_id: col_star.id, direction: -1 } }
+
+ it { is_expected.to fail_a_step(:swap_positions) }
+ end
+
+ context "when moving rightmost column right" do
+ let(:params) { { board_id: board.id, column_id: col_done.id, direction: 1 } }
+
+ it { is_expected.to fail_a_step(:swap_positions) }
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, column_id: col_progress.id, direction: 1 } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when column is not found" do
+ let(:params) { { board_id: board.id, column_id: 0, direction: 1 } }
+
+ it { is_expected.to fail_to_find_a_model(:column) }
+ end
+
+ context "when user cannot manage boards" do
+ let(:dependencies) { { guardian: user.guardian } }
+
+ before do
+ managers.remove(user)
+ user.reload
+ end
+
+ it { is_expected.to fail_a_policy(:can_manage) }
+ end
+
+ context "when direction is invalid" do
+ let(:params) { { board_id: board.id, column_id: col_progress.id, direction: 2 } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ it "does not reassign topic cards" do
+ topic = Fabricate(:topic)
+ card =
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_progress.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ result
+ expect(card.reload.column_id).to eq(col_progress.id)
+ end
+
+ it "publishes a columns_reordered event" do
+ messages = MessageBus.track_publish("/boards/#{board.id}") { result }
+
+ reorder_msg = messages.find { |m| m.data[:type] == "columns_reordered" }
+ expect(reorder_msg).to be_present
+ expect(reorder_msg.data[:column_order]).to eq([col_star.id, col_done.id, col_progress.id])
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/move_topic_to_column_spec.rb b/plugins/boards/spec/services/boards/move_topic_to_column_spec.rb
new file mode 100644
index 00000000000..dcaf9d32deb
--- /dev/null
+++ b/plugins/boards/spec/services/boards/move_topic_to_column_spec.rb
@@ -0,0 +1,204 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::MoveTopicToColumn do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:topic_id) }
+ it { is_expected.to validate_presence_of(:to_column_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:reader, :user)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+ fab!(:category)
+ fab!(:topic) { Fabricate(:topic, category: category, user: writer) }
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board-mtc", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "Doing", position: 0) }
+ fab!(:recency_column) do
+ board.columns.create!(title: "Recent", position: 1, default_sort: "recency")
+ end
+
+ let(:channel) { "/boards/#{board.id}" }
+ let(:client_id) { "test-123" }
+ let(:messages) { MessageBus.track_publish(channel) { result } }
+ let(:params) do
+ { board_id: board.id, topic_id: topic.id, to_column_id: column.id, client_id: client_id }
+ end
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ write_group.add(admin)
+ read_group.add(reader)
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { board_id: board.id } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, topic_id: topic.id, to_column_id: column.id } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when user cannot write to board" do
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_write) }
+ end
+
+ context "when topic is not found" do
+ let(:params) { { board_id: board.id, topic_id: 0, to_column_id: column.id } }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when user cannot see topic" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }
+
+ let(:params) { { board_id: board.id, topic_id: private_topic.id, to_column_id: column.id } }
+ let(:dependencies) { { guardian: writer.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_see_topic) }
+ end
+
+ context "when user cannot edit topic" do
+ fab!(:other_user, :user)
+
+ let(:dependencies) { { guardian: other_user.guardian } }
+
+ before { write_group.add(other_user) }
+
+ it { is_expected.to fail_a_policy(:can_edit_topic) }
+ end
+
+ context "when column is not found" do
+ let(:params) { { board_id: board.id, topic_id: topic.id, to_column_id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:column) }
+ end
+
+ context "when topic has no existing card" do
+ it { is_expected.to run_successfully }
+
+ it "creates a topic card on the column" do
+ expect(result[:card]).to be_previously_new_record.and have_attributes(
+ topic_id: topic.id,
+ column_id: column.id,
+ card_type: "topic",
+ )
+ end
+
+ it "sets creator and updater to the acting user" do
+ expect(result[:card]).to have_attributes(created_by_id: admin.id, updated_by_id: admin.id)
+ end
+
+ it "sets column_changed_at" do
+ expect(result[:card].column_changed_at).to be_present
+ end
+
+ it "publishes a card_created event scoped to board read groups" do
+ expect(messages).to contain_exactly(
+ have_attributes(
+ data:
+ include(
+ type: "card_created",
+ client_id: client_id,
+ card: include(topic_id: topic.id),
+ ),
+ group_ids: contain_exactly(write_group.id, read_group.id),
+ ),
+ )
+ end
+ end
+
+ context "when topic already has a card on the column" do
+ fab!(:existing_card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: column.id,
+ position: 0,
+ created_by_id: writer.id,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns the existing card" do
+ expect(result[:card]).not_to be_previously_new_record
+ expect(result[:card]).to have_attributes(id: existing_card.id, created_by_id: writer.id)
+ end
+
+ it "publishes a card_moved event" do
+ expect(messages).to contain_exactly(
+ have_attributes(data: include(type: "card_moved", client_id: client_id)),
+ )
+ end
+ end
+
+ context "when moving a topic to a column sorted by recency" do
+ let(:params) do
+ {
+ board_id: board.id,
+ topic_id: topic.id,
+ to_column_id: recency_column.id,
+ after_card_id: existing_card.id,
+ client_id: client_id,
+ }
+ end
+
+ fab!(:existing_card) do
+ other_topic = Fabricate(:topic, category: category)
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: other_topic.id,
+ column_id: recency_column.id,
+ position: 0,
+ created_by_id: writer.id,
+ )
+ end
+
+ it "places the new card at the beginning" do
+ expect(result[:card].position).to be < existing_card.reload.position
+ expect(result[:card].column_changed_at).to be_present
+ end
+ end
+
+ context "when column has a tag_id mutation" do
+ fab!(:tag) { Fabricate(:tag, name: "in-progress") }
+
+ before { column.update!(tag_id: tag.id) }
+
+ it "applies the tag to the topic" do
+ result
+ expect(topic.reload.tags.map(&:name)).to include("in-progress")
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/publisher_spec.rb b/plugins/boards/spec/services/boards/publisher_spec.rb
new file mode 100644
index 00000000000..e87e330bc14
--- /dev/null
+++ b/plugins/boards/spec/services/boards/publisher_spec.rb
@@ -0,0 +1,180 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::Publisher do
+ fab!(:admin)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+
+ before { enable_current_plugin }
+
+ fab!(:board) do
+ board =
+ Boards::Board.create!(name: "Test Board", slug: "test-publisher", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "To Do", position: 0) }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Test card",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:card_data) { { id: card.id, column_id: column.id, title: "Test card" } }
+ let(:channel) { "/boards/#{board.id}" }
+ let(:test_client_id) { "abc123" }
+
+ describe ".publish_card_created!" do
+ it "publishes a card_created message with group_ids and client_id" do
+ messages =
+ MessageBus.track_publish(channel) do
+ described_class.publish_card_created!(board, card_data, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ msg = messages.first
+ expect(msg.data[:type]).to eq("card_created")
+ expect(msg.data[:client_id]).to eq(test_client_id)
+ expect(msg.data[:card]).to eq(card_data)
+ expect(msg.group_ids).to contain_exactly(write_group.id, read_group.id)
+ end
+ end
+
+ describe ".publish_topic_memberships_changed!" do
+ fab!(:topic)
+
+ it "publishes a reload without board membership data" do
+ messages =
+ MessageBus.track_publish("/topic/#{topic.id}") do
+ described_class.publish_topic_memberships_changed!(topic, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ message = messages.first
+ expect(message.data).to eq(reload_topic: true, client_id: test_client_id)
+ expect(message.data).not_to have_key(:board_memberships)
+ end
+
+ it "optionally refreshes the post stream" do
+ messages =
+ MessageBus.track_publish("/topic/#{topic.id}") do
+ described_class.publish_topic_memberships_changed!(
+ topic,
+ client_id: test_client_id,
+ refresh_stream: true,
+ )
+ end
+
+ expect(messages.first.data).to eq(
+ reload_topic: true,
+ client_id: test_client_id,
+ refresh_stream: true,
+ )
+ end
+
+ context "when the topic is in a private category" do
+ fab!(:private_group, :group)
+ fab!(:private_category) { Fabricate(:private_category, group: private_group) }
+ fab!(:topic) { Fabricate(:topic, category: private_category) }
+
+ it "restricts the reload to the topic's audience" do
+ messages =
+ MessageBus.track_publish("/topic/#{topic.id}") do
+ described_class.publish_topic_memberships_changed!(topic, client_id: test_client_id)
+ end
+
+ expect(messages.first.group_ids).to contain_exactly(private_group.id)
+ end
+ end
+ end
+
+ describe ".publish_card_updated!" do
+ it "publishes a card_updated message" do
+ messages =
+ MessageBus.track_publish(channel) do
+ described_class.publish_card_updated!(board, card_data, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:type]).to eq("card_updated")
+ expect(messages.first.data[:card]).to eq(card_data)
+ end
+ end
+
+ describe ".publish_card_moved!" do
+ it "publishes a card_moved message" do
+ messages =
+ MessageBus.track_publish(channel) do
+ described_class.publish_card_moved!(board, card_data, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:type]).to eq("card_moved")
+ expect(messages.first.data[:card]).to eq(card_data)
+ end
+ end
+
+ describe ".publish_card_deleted!" do
+ it "publishes a card_deleted message with card_id" do
+ messages =
+ MessageBus.track_publish(channel) do
+ described_class.publish_card_deleted!(board, card.id, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ msg = messages.first
+ expect(msg.data[:type]).to eq("card_deleted")
+ expect(msg.data[:client_id]).to eq(test_client_id)
+ expect(msg.data[:card_id]).to eq(card.id)
+ end
+ end
+
+ describe ".publish_board_updated!" do
+ it "publishes a board_updated message" do
+ messages =
+ MessageBus.track_publish(channel) do
+ described_class.publish_board_updated!(board, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ msg = messages.first
+ expect(msg.data[:type]).to eq("board_updated")
+ expect(msg.data[:client_id]).to eq(test_client_id)
+ end
+ end
+
+ context "with a public board" do
+ fab!(:public_board) do
+ Boards::Board.create!(
+ name: "Public Board",
+ slug: "test-publisher-public",
+ created_by_id: admin.id,
+ )
+ end
+
+ it "publishes without group_ids restriction" do
+ messages =
+ MessageBus.track_publish("/boards/#{public_board.id}") do
+ described_class.publish_board_updated!(public_board, client_id: test_client_id)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.group_ids).to be_nil
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/topic_board_memberships_spec.rb b/plugins/boards/spec/services/boards/topic_board_memberships_spec.rb
new file mode 100644
index 00000000000..a51a8a93511
--- /dev/null
+++ b/plugins/boards/spec/services/boards/topic_board_memberships_spec.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::TopicBoardMemberships do
+ subject(:result) { described_class.call(guardian:, options: { topics: }) }
+
+ fab!(:admin)
+ fab!(:reader, :user)
+ fab!(:outsider, :user)
+ fab!(:read_group, :group)
+ fab!(:topic)
+ fab!(:board) { Fabricate(:boards_board, created_by: admin) }
+ fab!(:column) { Fabricate(:boards_column, board:) }
+ fab!(:card) { Fabricate(:boards_topic_card, board:, column:, topic:) }
+
+ let(:topics) { [topic] }
+ let(:guardian) { reader.guardian }
+
+ before do
+ enable_current_plugin
+ read_group.add(reader)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns readable cards grouped by topic and board" do
+ expect(result[:cards_map]).to eq(topic.id => { board.id => [card] })
+ end
+
+ context "when the topic has no board memberships" do
+ fab!(:topic_without_memberships, :topic)
+
+ let(:topics) { [topic_without_memberships] }
+
+ it { is_expected.to run_successfully }
+
+ it "returns an empty membership list" do
+ expect(result[:single_topic_memberships]).to eq([])
+ end
+ end
+
+ context "when the board is not readable" do
+ let(:guardian) { outsider.guardian }
+
+ it "does not return the board's cards" do
+ expect(result[:cards_map]).to be_empty
+ end
+ end
+
+ context "when the board is readable anonymously" do
+ before do
+ AccessControlList.find_by!(target: board, permission: "view").update!(
+ allowed_group_ids: [read_group.id, Group::AUTO_GROUPS[:anonymous_users]],
+ )
+ end
+
+ let(:guardian) { Guardian.new }
+
+ it "returns the board's cards" do
+ expect(result[:cards_map]).to eq(topic.id => { board.id => [card] })
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/topic_mutator_spec.rb b/plugins/boards/spec/services/boards/topic_mutator_spec.rb
new file mode 100644
index 00000000000..65cdfb00e4f
--- /dev/null
+++ b/plugins/boards/spec/services/boards/topic_mutator_spec.rb
@@ -0,0 +1,253 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::TopicMutator do
+ fab!(:admin)
+ fab!(:user, :trust_level_1)
+ fab!(:category) { Fabricate(:category, name: "General") }
+ fab!(:target_category) { Fabricate(:category, name: "Done") }
+ fab!(:post) do
+ Fabricate(:post, user: user, topic: Fabricate(:topic, category: category, user: user))
+ end
+ fab!(:topic) { post.topic }
+
+ before { enable_current_plugin }
+
+ fab!(:board) do
+ Boards::Board.create!(name: "Test", slug: "test-mutator", created_by_id: admin.id)
+ end
+
+ describe ".apply!" do
+ it "raises InvalidAccess when user is nil" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_status: "closed")
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: Guardian.new(nil))
+ }.to raise_error(Discourse::InvalidAccess)
+ end
+
+ it "raises InvalidAccess when user cannot edit the topic" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_status: "closed")
+ other_user = Fabricate(:user)
+
+ topic.update!(category: Fabricate(:private_category, group: Fabricate(:group)))
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: other_user.guardian)
+ }.to raise_error(Discourse::InvalidAccess)
+ end
+
+ context "with tag_id" do
+ before { SiteSetting.tagging_enabled = true }
+
+ it "adds the configured tag to the topic" do
+ tag = Fabricate(:tag, name: "in-progress")
+ column = board.columns.create!(title: "In Progress", position: 0, tag_id: tag.id)
+
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+
+ expect(topic.reload.tags.map(&:name)).to include("in-progress")
+ end
+
+ it "preserves existing tags" do
+ existing_tag = Fabricate(:tag, name: "existing")
+ new_tag = Fabricate(:tag, name: "new-tag")
+ topic.tags << existing_tag
+
+ column = board.columns.create!(title: "Col", position: 0, tag_id: new_tag.id)
+
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+
+ tag_names = topic.reload.tags.map(&:name)
+ expect(tag_names).to include("existing")
+ expect(tag_names).to include("new-tag")
+ end
+
+ it "removes tags from other columns on the same board" do
+ todo_tag = Fabricate(:tag, name: "todo")
+ doing_tag = Fabricate(:tag, name: "doing")
+ done_tag = Fabricate(:tag, name: "done")
+ unrelated_tag = Fabricate(:tag, name: "unrelated")
+
+ board.columns.create!(title: "Todo", position: 0, tag_id: todo_tag.id)
+ doing_column = board.columns.create!(title: "Doing", position: 1, tag_id: doing_tag.id)
+ board.columns.create!(title: "Done", position: 2, tag_id: done_tag.id)
+
+ topic.tags = [todo_tag, unrelated_tag]
+
+ described_class.apply!(topic: topic, column: doing_column, guardian: admin.guardian)
+
+ tag_names = topic.reload.tags.map(&:name)
+ expect(tag_names).to contain_exactly("doing", "unrelated")
+ end
+
+ it "does nothing when tag_id is nil" do
+ column = board.columns.create!(title: "Col", position: 0, tag_id: nil)
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.not_to change { topic.reload.tags.count }
+ end
+
+ it "removes the source column tag when moving to a column with no tag" do
+ ford_tag = Fabricate(:tag, name: "ford")
+ board.columns.create!(title: "Ford", position: 0, tag_id: ford_tag.id)
+ catchall_column = board.columns.create!(title: "Backlog", position: 1)
+
+ topic.tags = [ford_tag]
+
+ described_class.apply!(topic: topic, column: catchall_column, guardian: admin.guardian)
+
+ expect(topic.reload.tags.map(&:name)).not_to include("ford")
+ end
+
+ it "removes only sibling column tags when moving to a column with no tag" do
+ ford_tag = Fabricate(:tag, name: "ford-tag")
+ chevy_tag = Fabricate(:tag, name: "chevy-tag")
+ unrelated_tag = Fabricate(:tag, name: "unrelated-tag")
+
+ board.columns.create!(title: "Ford", position: 0, tag_id: ford_tag.id)
+ board.columns.create!(title: "Chevy", position: 1, tag_id: chevy_tag.id)
+ catchall_column = board.columns.create!(title: "Backlog", position: 2)
+
+ topic.tags = [ford_tag, unrelated_tag]
+
+ described_class.apply!(topic: topic, column: catchall_column, guardian: admin.guardian)
+
+ expect(topic.reload.tags.map(&:name)).to contain_exactly("unrelated-tag")
+ end
+ end
+
+ context "with move_to_category_id" do
+ it "moves the topic to the target category" do
+ column =
+ board.columns.create!(title: "Done", position: 0, move_to_category_id: target_category.id)
+
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+
+ expect(topic.reload.category_id).to eq(target_category.id)
+ end
+
+ it "raises NotFound for a missing category" do
+ doomed_category = Fabricate(:category)
+ column =
+ board.columns.create!(title: "Col", position: 0, move_to_category_id: doomed_category.id)
+ doomed_category.destroy!
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.to raise_error(Discourse::NotFound)
+ end
+
+ it "does nothing when move_to_category_id is blank" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_category_id: nil)
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.not_to change { topic.reload.category_id }
+ end
+ end
+
+ context "with move_to_status" do
+ it "raises InvalidAccess when a user with edit access cannot close the topic" do
+ column = board.columns.create!(title: "Closed", position: 0, move_to_status: "closed")
+
+ expect(Guardian.new(user).can_edit?(topic)).to eq(true)
+ expect(Guardian.new(user).can_close_topic?(topic)).to eq(false)
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: user.guardian)
+ }.to raise_error(Discourse::InvalidAccess)
+ expect(topic.reload.closed).to eq(false)
+ end
+
+ it "raises InvalidAccess when a user with edit access cannot open the topic" do
+ topic.update_status("closed", true, admin)
+ column = board.columns.create!(title: "Open", position: 0, move_to_status: "open")
+
+ expect(Guardian.new(user).can_edit?(topic)).to eq(true)
+ expect(Guardian.new(user).can_open_topic?(topic)).to eq(false)
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: user.guardian)
+ }.to raise_error(Discourse::InvalidAccess)
+ expect(topic.reload.closed).to eq(true)
+ end
+
+ it "closes the topic when status is 'closed'" do
+ column = board.columns.create!(title: "Closed", position: 0, move_to_status: "closed")
+
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+
+ expect(topic.reload.closed).to eq(true)
+ end
+
+ it "opens the topic when status is not 'closed'" do
+ topic.update_status("closed", true, admin)
+ expect(topic.reload.closed).to eq(true)
+
+ column = board.columns.create!(title: "Open", position: 0, move_to_status: "open")
+
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+
+ expect(topic.reload.closed).to eq(false)
+ end
+
+ it "does nothing when move_to_status is blank" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_status: "")
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.not_to change { topic.reload.closed }
+ end
+ end
+
+ context "with move_to_assigned" do
+ it "raises InvalidAccess when a user with edit access cannot change assignment" do
+ skip("requires discourse-assign") unless defined?(Assignment)
+
+ SiteSetting.assign_enabled = true
+ SiteSetting.assign_allowed_on_groups = ""
+ Assignment.create!(
+ target: topic,
+ topic_id: topic.id,
+ assigned_to: admin,
+ assigned_by_user: admin,
+ active: true,
+ )
+ column = board.columns.create!(title: "Unassigned", position: 0, move_to_assigned: "nobody")
+
+ expect(Guardian.new(user).can_edit?(topic)).to eq(true)
+ expect(Guardian.new(user).can_assign?(topic)).to eq(false)
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: user.guardian)
+ }.to raise_error(Discourse::InvalidAccess)
+ expect(topic.reload.assignment).to be_present
+ end
+
+ it "does nothing when Assigner is not defined" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_assigned: "someone")
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.not_to raise_error
+ end
+
+ it "does nothing when move_to_assigned is blank" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_assigned: "")
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.not_to raise_error
+ end
+
+ it "does nothing when move_to_assigned is '*'" do
+ column = board.columns.create!(title: "Col", position: 0, move_to_assigned: "*")
+
+ expect {
+ described_class.apply!(topic: topic, column: column, guardian: admin.guardian)
+ }.not_to raise_error
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/topic_sync_spec.rb b/plugins/boards/spec/services/boards/topic_sync_spec.rb
new file mode 100644
index 00000000000..f1dac24de82
--- /dev/null
+++ b/plugins/boards/spec/services/boards/topic_sync_spec.rb
@@ -0,0 +1,740 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::TopicSync do
+ fab!(:admin)
+ fab!(:category) { Fabricate(:category, name: "Todo") }
+ fab!(:tag_a) { Fabricate(:tag, name: "sync-alpha") }
+ fab!(:tag_b) { Fabricate(:tag, name: "sync-beta") }
+ fab!(:topic) { Fabricate(:topic, category: category) }
+ fab!(:read_group, :group)
+ fab!(:write_group, :group)
+
+ before { enable_current_plugin }
+
+ it "ignores topics before they are persisted" do
+ board =
+ Boards::Board.create!(
+ name: "Unsaved Topic Board",
+ slug: "unsaved-topic-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ unsaved_topic = Topic.new(category: category, tags: [tag_a])
+
+ expect { described_class.sync_topic(unsaved_topic) }.not_to change { Boards::Card.count }
+ end
+
+ it "does not auto-create cards in unconstrained columns" do
+ board =
+ Boards::Board.create!(
+ name: "Todo Board",
+ slug: "todo-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Backlog", position: 0)
+
+ expect { described_class.sync_topic(topic) }.not_to change { Boards::Card.count }
+ end
+
+ it "creates an auto card when board tag matches and column tag matches" do
+ tagged_topic = Fabricate(:topic, tags: [tag_a])
+ board =
+ Boards::Board.create!(
+ name: "Tag Board",
+ slug: "tag-board",
+ tag_ids: [tag_a.id],
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ expect { described_class.sync_topic(tagged_topic) }.to change { Boards::Card.count }.by(1)
+
+ card = Boards::Card.last
+ expect(card.column_id).to eq(column.id)
+ expect(card.column_changed_at).to be_present
+ end
+
+ it "publishes created topic cards to board ACL groups" do
+ tagged_topic = Fabricate(:topic, tags: [tag_a])
+ board =
+ Boards::Board.create!(
+ name: "ACL Tag Board",
+ slug: "acl-tag-board",
+ tag_ids: [tag_a.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") { described_class.sync_topic(tagged_topic) }
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:type]).to eq("card_created")
+ expect(messages.first.group_ids).to contain_exactly(read_group.id, write_group.id)
+ end
+
+ it "publishes created topic cards without group restrictions for anonymous board ACLs" do
+ tagged_topic = Fabricate(:topic, tags: [tag_a])
+ board =
+ Boards::Board.create!(
+ name: "Anonymous ACL Tag Board",
+ slug: "anonymous-acl-tag-board",
+ tag_ids: [tag_a.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ Fabricate(
+ :access_control_list,
+ target: board,
+ permission: "view",
+ allowed_group_ids: [Group::AUTO_GROUPS[:anonymous_users]],
+ )
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") { described_class.sync_topic(tagged_topic) }
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:type]).to eq("card_created")
+ expect(messages.first.group_ids).to be_nil
+ end
+
+ it "does not match topics when board has no constraints" do
+ board =
+ Boards::Board.create!(
+ name: "No Filter Board",
+ slug: "no-filter-board",
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Backlog", position: 0)
+
+ expect { described_class.sync_topic(topic) }.not_to change { Boards::Card.count }
+ end
+
+ it "does not delete existing cards on unconstrained boards" do
+ board =
+ Boards::Board.create!(name: "Manual Board", slug: "manual-board", created_by_id: admin.id)
+ column = board.columns.create!(title: "Backlog", position: 0)
+
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect { described_class.sync_topic(topic) }.not_to change { Boards::Card.count }
+ end
+
+ it "does not match topics in wrong category" do
+ other_category = Fabricate(:category)
+ board =
+ Boards::Board.create!(
+ name: "Wrong Cat Board",
+ slug: "wrong-cat-board",
+ category_ids: [other_category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Backlog", position: 0)
+
+ expect { described_class.sync_topic(topic) }.not_to change { Boards::Card.count }
+ end
+
+ it "places a topic in multiple columns when it matches multiple column tags" do
+ multi_topic = Fabricate(:topic, category: category, tags: [tag_a, tag_b])
+
+ board =
+ Boards::Board.create!(
+ name: "Multi Column Board",
+ slug: "multi-column-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col_a = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ col_b = board.columns.create!(title: "Beta", position: 1, tag_id: tag_b.id)
+
+ expect { described_class.sync_topic(multi_topic) }.to change { Boards::Card.count }.by(2)
+
+ expect(board.cards.where(topic_id: multi_topic.id).pluck(:column_id)).to contain_exactly(
+ col_a.id,
+ col_b.id,
+ )
+ end
+
+ it "removes a manually-placed card when the board category no longer matches" do
+ board =
+ Boards::Board.create!(
+ name: "Remove Auto Board",
+ slug: "remove-auto-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Backlog", position: 0)
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ other_category = Fabricate(:category)
+ board.update!(category_ids: [other_category.id])
+
+ expect { described_class.sync_topic(topic) }.to change {
+ board.cards.where(topic_id: topic.id).count
+ }.from(1).to(0)
+ end
+
+ it "removes cards when board constraints no longer match" do
+ board =
+ Boards::Board.create!(
+ name: "Constraint Board",
+ slug: "constraint-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Backlog", position: 0)
+
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ other_category = Fabricate(:category)
+ board.update!(category_ids: [other_category.id])
+ described_class.sync_topic(topic)
+
+ expect(board.cards.where(topic_id: topic.id).count).to eq(0)
+ end
+
+ it "removes an auto card when column tag no longer matches topic" do
+ tagged_topic = Fabricate(:topic, category: category, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "Tag Miss Board",
+ slug: "tag-miss-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ described_class.sync_topic(tagged_topic)
+ expect(board.cards.where(topic_id: tagged_topic.id, column_id: col.id).count).to eq(1)
+
+ col.update!(tag_id: tag_b.id)
+
+ expect { described_class.sync_topic(tagged_topic) }.to change {
+ board.cards.where(topic_id: tagged_topic.id).count
+ }.from(1).to(0)
+ end
+
+ it "rolls back sync changes when apply fails part way through" do
+ tagged_topic = Fabricate(:topic, category: category, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "Atomic Board",
+ slug: "atomic-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ described_class.sync_topic(tagged_topic)
+ expect(board.cards.where(topic_id: tagged_topic.id).count).to eq(1)
+
+ other_category = Fabricate(:category)
+ board.update!(category_ids: [other_category.id])
+
+ described_class.stubs(:execute_sync_changes).raises(StandardError.new("create boom"))
+
+ expect { described_class.sync_topic(tagged_topic) }.to raise_error(StandardError, "create boom")
+ expect(board.cards.where(topic_id: tagged_topic.id).count).to eq(1)
+ end
+
+ it "retries once when a unique topic-card violation happens" do
+ attempts = 0
+
+ described_class.send(:with_topic_sync_retry) do
+ attempts += 1
+ if attempts == 1
+ raise ActiveRecord::RecordNotUnique.new("idx_kanban_cards_unique_topic_per_column")
+ end
+ end
+
+ expect(attempts).to eq(2)
+ end
+
+ it "removes cards when topic is removed" do
+ board = Boards::Board.create!(name: "Todo Board", slug: "todo-board-3", created_by_id: admin.id)
+ column = board.columns.create!(title: "Backlog", position: 0)
+
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect { described_class.remove_topic(topic.id) }.to change { Boards::Card.count }.by(-1)
+ end
+
+ it "publishes topic card removals to board ACL groups" do
+ board =
+ Boards::Board.create!(
+ name: "ACL Remove Board",
+ slug: "acl-remove-board",
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Backlog", position: 0)
+ card =
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+
+ messages =
+ MessageBus.track_publish("/boards/#{board.id}") { described_class.remove_topic(topic.id) }
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:type]).to eq("card_deleted")
+ expect(messages.first.data[:card_id]).to eq(card.id)
+ expect(messages.first.group_ids).to contain_exactly(read_group.id)
+ end
+
+ describe "multi-column card semantics" do
+ it "creates auto cards in other columns when a card exists in one column" do
+ multi_topic = Fabricate(:topic, category: category, tags: [tag_a, tag_b])
+
+ board =
+ Boards::Board.create!(
+ name: "Manual In Multi Board",
+ slug: "manual-in-multi-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col_a = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ col_b = board.columns.create!(title: "Beta", position: 1, tag_id: tag_b.id)
+
+ board.cards.create!(
+ topic_id: multi_topic.id,
+ card_type: :topic,
+ column_id: col_a.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect { described_class.sync_topic(multi_topic) }.to change { Boards::Card.count }.by(1)
+
+ expect(board.cards.where(topic_id: multi_topic.id).pluck(:column_id)).to contain_exactly(
+ col_a.id,
+ col_b.id,
+ )
+ end
+
+ it "cleans up auto cards while preserving manually created cards after tag change" do
+ tagged_topic = Fabricate(:topic, category: category, tags: [tag_a, tag_b])
+
+ board =
+ Boards::Board.create!(
+ name: "Preserve Manual Board",
+ slug: "preserve-manual-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col_a = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ col_b = board.columns.create!(title: "Beta", position: 1, tag_id: tag_b.id)
+
+ board.cards.create!(
+ topic_id: tagged_topic.id,
+ card_type: :topic,
+ column_id: col_a.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ described_class.sync_topic(tagged_topic)
+ expect(board.cards.where(topic_id: tagged_topic.id).count).to eq(2)
+
+ other_tag = Fabricate(:tag, name: "sync-other")
+ col_b.update!(tag_id: other_tag.id)
+ described_class.sync_topic(tagged_topic)
+
+ expect(board.cards.where(topic_id: tagged_topic.id).count).to eq(1)
+ remaining = board.cards.find_by(topic_id: tagged_topic.id)
+ expect(remaining.column_id).to eq(col_a.id)
+ end
+ end
+
+ describe "sticky catch-all columns" do
+ it "does not relocate a card between catch-all columns on re-sync" do
+ board =
+ Boards::Board.create!(
+ name: "Sticky Board",
+ slug: "sticky-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+
+ col_a = board.columns.create!(title: "Column A", position: 0)
+ col_b = board.columns.create!(title: "Column B", position: 1)
+
+ # Manually place in column B (not the lowest-ID catch-all)
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: col_b.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ described_class.sync_topic(topic)
+
+ card = board.cards.find_by(topic_id: topic.id)
+ expect(card.column_id).to eq(col_b.id)
+ end
+
+ it "does not auto-place a topic in unconstrained columns" do
+ board =
+ Boards::Board.create!(
+ name: "First Catchall Board",
+ slug: "first-catchall-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+
+ board.columns.create!(title: "Column A", position: 0)
+ board.columns.create!(title: "Column B", position: 1)
+
+ expect { described_class.sync_topic(topic) }.not_to change { Boards::Card.count }
+ end
+
+ it "does not place a tagged topic in a catch-all column" do
+ tagged_topic = Fabricate(:topic, category: category, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "No Catchall Board",
+ slug: "no-catchall-for-tagged",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col_tagged = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ board.columns.create!(title: "Backlog", position: 1)
+
+ described_class.sync_topic(tagged_topic)
+
+ cards = board.cards.where(topic_id: tagged_topic.id)
+ expect(cards.count).to eq(1)
+ expect(cards.first.column_id).to eq(col_tagged.id)
+ end
+
+ it "removes a card when a topic loses its column tag instead of falling to unconstrained" do
+ tagged_topic = Fabricate(:topic, category: category, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "Fallback Board",
+ slug: "fallback-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col_tagged = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ board.columns.create!(title: "Backlog", position: 1)
+
+ described_class.sync_topic(tagged_topic)
+ cards = board.cards.where(topic_id: tagged_topic.id)
+ expect(cards.count).to eq(1)
+ expect(cards.first.column_id).to eq(col_tagged.id)
+
+ # Remove the tag β€” topic no longer matches the tagged column
+ tagged_topic.tags = []
+ tagged_topic.save!
+
+ described_class.sync_topic(tagged_topic)
+
+ expect(board.cards.where(topic_id: tagged_topic.id).count).to eq(0)
+ end
+ end
+
+ describe ".backfill_board" do
+ it "creates cards for matching topics in tagged columns" do
+ tagged_topic = Fabricate(:topic, category: category, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "Backfill Board",
+ slug: "backfill-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ expect { described_class.backfill_board(board) }.to change { Boards::Card.count }.by(1)
+
+ card = board.cards.where(topic_id: tagged_topic.id).first
+ expect(card.column_id).to eq(column.id)
+ expect(card.column_changed_at).to be_present
+ end
+
+ it "does not auto-create cards in unconstrained columns during backfill" do
+ board =
+ Boards::Board.create!(
+ name: "Backfill Catchall Board",
+ slug: "backfill-catchall-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Backlog", position: 0)
+
+ expect { described_class.backfill_board(board) }.not_to change { Boards::Card.count }
+ end
+
+ it "does not duplicate cards for topics that already have one" do
+ board =
+ Boards::Board.create!(
+ name: "No Dup Board",
+ slug: "no-dup-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Backlog", position: 0)
+
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect { described_class.backfill_board(board) }.not_to change {
+ board.cards.where(topic_id: topic.id).count
+ }
+ end
+
+ it "excludes category definition topics" do
+ Fabricate(:topic, category: category, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "No Defs Board",
+ slug: "no-defs-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ described_class.backfill_board(board)
+
+ carded_topic_ids = board.cards.pluck(:topic_id)
+ expect(carded_topic_ids).not_to include(category.topic_id)
+ end
+
+ it "discovers topics by column tag" do
+ tagged_topic = Fabricate(:topic, tags: [tag_a])
+
+ board =
+ Boards::Board.create!(
+ name: "Tag Backfill Board",
+ slug: "tag-backfill-board",
+ tag_ids: [tag_a.id],
+ created_by_id: admin.id,
+ )
+ col = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ described_class.backfill_board(board)
+
+ card = board.cards.find_by(topic_id: tagged_topic.id)
+ expect(card).to be_present
+ expect(card.column_id).to eq(col.id)
+ end
+
+ it "discovers topics from muted categories" do
+ muted_category = Fabricate(:category)
+ tagged_topic = Fabricate(:topic, category: muted_category, tags: [tag_a])
+ CategoryUser.set_notification_level_for_category(
+ Discourse.system_user,
+ CategoryUser.notification_levels[:muted],
+ muted_category.id,
+ )
+
+ board =
+ Boards::Board.create!(
+ name: "Muted Category Backfill Board",
+ slug: "muted-category-backfill-board",
+ tag_ids: [tag_a.id],
+ created_by_id: admin.id,
+ )
+ col = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ described_class.backfill_board(board)
+
+ card = board.cards.find_by(topic_id: tagged_topic.id)
+ expect(card).to be_present
+ expect(card.column_id).to eq(col.id)
+ end
+
+ it "limits the number of topics per column to MAX_CARDS_PER_COLUMN" do
+ 4.times { Fabricate(:topic, category: category, tags: [tag_a]) }
+
+ board =
+ Boards::Board.create!(
+ name: "Limit Board",
+ slug: "limit-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ stub_const(Boards::TopicSync, :MAX_CARDS_PER_COLUMN, 3) do
+ described_class.backfill_board(board)
+ end
+
+ expect(board.cards.count).to be <= 3
+ end
+
+ it "evicts oldest topic cards when a column exceeds MAX_CARDS_PER_COLUMN via sync" do
+ board =
+ Boards::Board.create!(
+ name: "Eviction Board",
+ slug: "eviction-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+
+ stub_const(Boards::TopicSync, :MAX_CARDS_PER_COLUMN, 3) do
+ topics = 4.times.map { Fabricate(:topic, category: category, tags: [tag_a]) }
+ topics.each { |t| described_class.sync_topic(t) }
+
+ cards = board.cards.where(column_id: col.id).order(:position)
+ expect(cards.count).to eq(3)
+ expect(cards.pluck(:topic_id)).to eq(topics.last(3).map(&:id))
+ end
+ end
+
+ it "does not discover topics when board has no constraints" do
+ board =
+ Boards::Board.create!(
+ name: "No Filter Backfill Board",
+ slug: "no-filter-backfill-board",
+ created_by_id: admin.id,
+ )
+ board.columns.create!(title: "Backlog", position: 0)
+
+ expect { described_class.backfill_board(board) }.not_to change { Boards::Card.count }
+ end
+
+ it "does not delete existing cards on unconstrained boards" do
+ board =
+ Boards::Board.create!(
+ name: "No Filter Preserve Board",
+ slug: "no-filter-preserve-board",
+ created_by_id: admin.id,
+ )
+ column = board.columns.create!(title: "Backlog", position: 0)
+
+ board.cards.create!(
+ topic_id: topic.id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect { described_class.backfill_board(board) }.not_to change { Boards::Card.count }
+ end
+
+ it "places a topic in multiple columns when it matches multiple column tags" do
+ multi_topic = Fabricate(:topic, category: category, tags: [tag_a, tag_b])
+
+ board =
+ Boards::Board.create!(
+ name: "Backfill Multi Board",
+ slug: "backfill-multi-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ col_a = board.columns.create!(title: "Alpha", position: 0, tag_id: tag_a.id)
+ col_b = board.columns.create!(title: "Beta", position: 1, tag_id: tag_b.id)
+
+ described_class.backfill_board(board)
+
+ cards = board.cards.where(topic_id: multi_topic.id)
+ expect(cards.count).to eq(2)
+ expect(cards.pluck(:column_id)).to contain_exactly(col_a.id, col_b.id)
+ end
+ end
+
+ describe "PostCreator integration" do
+ it "does not interfere with topic creation" do
+ Boards::Board
+ .create!(
+ name: "Board",
+ slug: "post-creator-board",
+ category_ids: [category.id],
+ created_by_id: admin.id,
+ )
+ .columns
+ .create!(title: "Backlog", position: 0)
+
+ post =
+ PostCreator.create!(
+ admin,
+ title: "A topic created while boards is active",
+ raw: "This should succeed without any errors from the plugin.",
+ category: category.id,
+ archetype: Archetype.default,
+ )
+
+ expect(post).to be_persisted
+ expect(post.topic).to be_persisted
+ end
+
+ it "does not break topic creation when sync raises an error" do
+ Boards::TopicSync.stubs(:sync_topic).raises(StandardError.new("sync boom"))
+
+ post =
+ PostCreator.create!(
+ admin,
+ title: "A topic created while sync is broken",
+ raw: "This should still succeed despite sync errors.",
+ category: category.id,
+ archetype: Archetype.default,
+ )
+
+ expect(post).to be_persisted
+ expect(post.topic).to be_persisted
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/update_board_spec.rb b/plugins/boards/spec/services/boards/update_board_spec.rb
new file mode 100644
index 00000000000..0e0750d10af
--- /dev/null
+++ b/plugins/boards/spec/services/boards/update_board_spec.rb
@@ -0,0 +1,219 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::UpdateBoard do
+ describe Boards::UpdateBoard::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:id) }
+ end
+
+ describe ".call" do
+ subject(:result) { Boards::UpdateBoard.call(params:, raw_board_params: raw, **dependencies) }
+
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Old", slug: "old", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "manage",
+ groups: [manage_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "Col", position: 0) }
+
+ let(:raw) { { "name" => "Updated" } }
+ let(:params) { raw.merge("id" => board.id) }
+ let(:dependencies) { { guardian: manager.guardian } }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ manage_group.add(admin)
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when board is not found" do
+ let(:params) { { "id" => 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when user cannot manage boards" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "updates the board" do
+ result
+ board.reload
+ expect(board.name).to eq("Updated")
+ expect(board.updated_by_id).to eq(manager.id)
+ end
+
+ it "tracks the board rename history" do
+ result
+ board.reload
+ expect(board.history.first).to have_attributes(
+ action: "board_renamed",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ details: {
+ "previous_value" => "Old",
+ "new_value" => "Updated",
+ },
+ )
+ end
+
+ it "replaces existing ACLs with mandatory ACLs when ACL params are empty" do
+ raw["acl"] = []
+
+ result
+
+ manage_acl = AccessControlList.find_by!(target: board, permission: "manage")
+ expect(manage_acl.allowed_group_ids).to contain_exactly(Group::AUTO_GROUPS[:admins])
+ end
+
+ it "does not delete topic cards on unconstrained boards" do
+ let_raw = { "name" => "Updated", "columns" => [{ "id" => column.id, "title" => "Col" }] }
+ let_params = let_raw.merge("id" => board.id)
+
+ board.cards.create!(
+ topic_id: Fabricate(:topic).id,
+ card_type: :topic,
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ expect {
+ described_class.call(
+ params: let_params,
+ raw_board_params: let_raw,
+ guardian: manager.guardian,
+ )
+ }.not_to change { board.cards.where(card_type: :topic).count }
+ end
+
+ context "with tag_names" do
+ fab!(:existing_tag, :tag)
+
+ let(:raw) { { "name" => "Updated", "tag_names" => [existing_tag.name, "brand-new"] } }
+
+ context "when the user can create tags" do
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it "resolves existing tags and creates new ones" do
+ result
+ board.reload
+ expect(board.tag_ids).to contain_exactly(
+ existing_tag.id,
+ Tag.find_by(name: "brand-new").id,
+ )
+ end
+ end
+
+ it "fails when the user cannot create tags and a tag is missing" do
+ expect { result }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.unknown_tag_names", tag_names: "brand-new"),
+ )
+ end
+
+ context "when an existing tag is not visible to the user" do
+ fab!(:restricted_tag, :tag)
+
+ let(:raw) { { "name" => "Updated", "tag_names" => [restricted_tag.name] } }
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tags: [restricted_tag]) }
+
+ it "does not resolve the hidden tag" do
+ expect { result }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.unknown_tag_names", tag_names: restricted_tag.name),
+ )
+ end
+ end
+ end
+
+ context "with column changes" do
+ let(:raw) do
+ {
+ "name" => "Updated",
+ "columns" => [{ "id" => column.id, "title" => "Renamed" }, { "title" => "New Col" }],
+ }
+ end
+
+ it "does not update columns" do
+ result
+ board.reload
+ expect(board.columns.count).to eq(1)
+ expect(column.reload.title).to eq("Col")
+ end
+ end
+
+ context "with permission changes" do
+ fab!(:new_group, :group)
+ let(:raw) { { "acl" => [{ type: "group", id: new_group.id, permission: "manage" }] } }
+
+ it "tracks the permission change history" do
+ result
+ board.reload
+ expect(board.history.first).to have_attributes(
+ action: "board_permissions_changed",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ details: {
+ "previous_permissions" => {
+ "manage" => {
+ "group_ids" => [manage_group.id],
+ "user_ids" => [],
+ },
+ },
+ "new_permissions" => {
+ "manage" => {
+ "group_ids" => [new_group.id, Group::AUTO_GROUPS[:admins]],
+ "user_ids" => [],
+ },
+ },
+ },
+ )
+ end
+ end
+
+ context "with constraint changes" do
+ fab!(:category)
+ fab!(:tag)
+ let(:raw) { { "category_ids" => [category.id], "tag_ids" => [tag.id] } }
+
+ it "tracks the constraint change history" do
+ result
+ board.reload
+ expect(board.history.first).to have_attributes(
+ action: "board_constraints_changed",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ details: {
+ "previous_category_ids" => [],
+ "new_category_ids" => [category.id],
+ "previous_tag_ids" => [],
+ "new_tag_ids" => [tag.id],
+ },
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/update_card_spec.rb b/plugins/boards/spec/services/boards/update_card_spec.rb
new file mode 100644
index 00000000000..c587b225769
--- /dev/null
+++ b/plugins/boards/spec/services/boards/update_card_spec.rb
@@ -0,0 +1,1000 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::UpdateCard do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:id) }
+ end
+
+ describe ".call" do
+ subject(:result) do
+ described_class.call(params:, raw_card_params: raw_card_params, **dependencies)
+ end
+
+ fab!(:admin)
+ fab!(:writer, :user)
+ fab!(:reader, :user)
+ fab!(:write_group, :group)
+ fab!(:read_group, :group)
+ fab!(:category)
+ fab!(:tag)
+ fab!(:topic) { Fabricate(:topic, category: category, user: writer) }
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board-uc", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:col_todo) { board.columns.create!(title: "To Do", position: 0) }
+ fab!(:col_done) { board.columns.create!(title: "Done", position: 1) }
+ fab!(:col_recent) do
+ board.columns.create!(title: "Recent", position: 2, default_sort: "recency")
+ end
+
+ let(:raw_card_params) { {} }
+ let(:dependencies) { { guardian: writer.guardian } }
+
+ before do
+ enable_current_plugin
+ write_group.add(writer)
+ write_group.add(admin)
+ read_group.add(reader)
+ end
+
+ context "when updating a floater card title" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Old",
+ inline_onebox_data: {
+ "url" => "https://example.com/old",
+ "title" => "Old page title",
+ },
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "title" => "New" } }
+ let(:params) { { board_id: board.id, id: card.id, title: "New" } }
+
+ it { is_expected.to run_successfully }
+
+ it "updates the title" do
+ result
+ expect(card.reload.title).to eq("New")
+ expect(card.inline_onebox_data).to be_nil
+ end
+
+ it "does not change column_changed_at" do
+ previous_changed_at = 2.days.ago
+ card.update_column(:column_changed_at, previous_changed_at)
+
+ result
+ expect(card.reload.column_changed_at.to_i).to eq(previous_changed_at.to_i)
+ end
+
+ it "logs a card edited history record" do
+ expect { result }.to change {
+ Boards::CardHistory.where(action: Boards::CardHistory.actions[:card_edited]).count
+ }.by(1)
+ end
+ end
+
+ context "when updating a floater card title to a URL" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Old",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:url) { "https://github.com/discourse/discourse/pull/42462" }
+ let(:raw_card_params) { { "title" => url } }
+ let(:params) { { board_id: board.id, id: card.id, title: url } }
+ let(:onebox_data) do
+ {
+ "url" => url,
+ "title" => "FEATURE: Add ProseMirror tab support",
+ "css_class" => "--gh-status-approved",
+ }
+ end
+
+ it "clears stale data without resolving inline" do
+ card.update!(inline_onebox_data: onebox_data)
+ Boards::Action::CardInlineOnebox.expects(:call).never
+
+ result
+
+ expect(card.reload.inline_onebox_data).to be_nil
+ end
+ end
+
+ context "when updating a floater card without changing its title" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "https://example.com",
+ inline_onebox_data: {
+ "url" => "https://example.com",
+ "title" => "Example Domain",
+ },
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "notes" => "Updated notes" } }
+ let(:params) { { board_id: board.id, id: card.id, notes: "Updated notes" } }
+
+ it "preserves the existing inline onebox data without resolving it again" do
+ Boards::Action::CardInlineOnebox.expects(:call).never
+ result
+
+ expect(card.reload.inline_onebox_data).to eq(
+ "url" => "https://example.com",
+ "title" => "Example Domain",
+ )
+ end
+ end
+
+ context "when moving a card between columns" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id, column_id: col_done.id } }
+
+ it { is_expected.to run_successfully }
+
+ it "moves the card to the new column" do
+ result
+ expect(card.reload.column_id).to eq(col_done.id)
+ end
+
+ it "updates column_changed_at" do
+ previous_changed_at = 2.days.ago
+ card.update_column(:column_changed_at, previous_changed_at)
+
+ freeze_time do
+ result
+ expect(card.reload.column_changed_at.to_i).to eq(Time.current.to_i)
+ end
+ end
+
+ it "records the original column id" do
+ expect(result[:original_column_id]).to eq(col_todo.id)
+ end
+
+ it "creates a card history record" do
+ expect { result }.to change {
+ Boards::CardHistory.where(action: Boards::CardHistory.actions[:card_moved]).count
+ }.by(1)
+ expect(
+ Boards::CardHistory.where(action: Boards::CardHistory.actions[:card_moved]).last.details,
+ ).to eq("from" => col_todo.title, "to" => col_done.title)
+ end
+ end
+
+ context "when moving a floater card between tagged columns" do
+ fab!(:todo_tag, :tag) { Fabricate(:tag, name: "todo") }
+ fab!(:done_tag, :tag) { Fabricate(:tag, name: "done") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated") }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move tagged card",
+ tag_ids: [todo_tag.id, unrelated_tag.id],
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id, column_id: col_done.id } }
+
+ before do
+ col_todo.update!(tag_id: todo_tag.id)
+ col_done.update!(tag_id: done_tag.id)
+ end
+
+ it "replaces the source column tag with the destination column tag" do
+ result
+ expect(card.reload.tag_ids).to contain_exactly(done_tag.id, unrelated_tag.id)
+ end
+ end
+
+ context "when moving a floater card to an untagged column" do
+ fab!(:todo_tag, :tag) { Fabricate(:tag, name: "todo") }
+ fab!(:done_tag, :tag) { Fabricate(:tag, name: "done") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated") }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move to untagged",
+ tag_ids: [todo_tag.id, done_tag.id, unrelated_tag.id],
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id, column_id: col_done.id } }
+
+ before do
+ col_todo.update!(tag_id: todo_tag.id)
+ board.columns.create!(title: "Tagged sibling", position: 3, tag_id: done_tag.id)
+ end
+
+ it "removes board column tags and preserves unrelated tags" do
+ result
+ expect(card.reload.tag_ids).to contain_exactly(unrelated_tag.id)
+ end
+ end
+
+ context "when reordering a floater card within the same tagged column" do
+ fab!(:column_tag, :tag) { Fabricate(:tag, name: "same-column") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated") }
+ fab!(:other_card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Other",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Reorder me",
+ tag_ids: [unrelated_tag.id],
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) do
+ { "column_id" => col_todo.id.to_s, "after_card_id" => other_card.id.to_s }
+ end
+ let(:params) do
+ { board_id: board.id, id: card.id, column_id: col_todo.id, after_card_id: other_card.id }
+ end
+
+ before { col_todo.update!(tag_id: column_tag.id) }
+
+ it "does not apply column tag resolution" do
+ result
+ expect(card.reload.tag_ids).to contain_exactly(unrelated_tag.id)
+ end
+ end
+
+ context "when editing tags on a floater card in a tagged column" do
+ fab!(:column_tag, :tag) { Fabricate(:tag, name: "column-tag") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated") }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Edit tags",
+ tag_ids: [column_tag.id],
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "tag_ids" => [unrelated_tag.id] } }
+ let(:params) { { board_id: board.id, id: card.id, tag_ids: [unrelated_tag.id] } }
+
+ before { col_todo.update!(tag_id: column_tag.id) }
+
+ it "re-applies the column tag" do
+ result
+ expect(card.reload.tag_ids).to contain_exactly(column_tag.id, unrelated_tag.id)
+ end
+ end
+
+ context "when editing tags on a floater card to include a hidden tag" do
+ fab!(:hidden_tag, :tag) { Fabricate(:tag, name: "staff-boards") }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Edit hidden tag",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "tag_ids" => [hidden_tag.id] } }
+ let(:params) { { board_id: board.id, id: card.id, tag_ids: [hidden_tag.id] } }
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name]) }
+
+ it "raises InvalidParameters" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+
+ context "when editing tags on a floater card to include a sibling column tag" do
+ fab!(:column_tag, :tag) { Fabricate(:tag, name: "column-tag") }
+ fab!(:sibling_tag, :tag) { Fabricate(:tag, name: "sibling-tag") }
+ fab!(:unrelated_tag, :tag) { Fabricate(:tag, name: "unrelated") }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Edit sibling tag",
+ tag_ids: [column_tag.id],
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "tag_ids" => [sibling_tag.id, unrelated_tag.id] } }
+ let(:params) do
+ { board_id: board.id, id: card.id, tag_ids: [sibling_tag.id, unrelated_tag.id] }
+ end
+
+ before do
+ col_todo.update!(tag_id: column_tag.id)
+ col_done.update!(tag_id: sibling_tag.id)
+ end
+
+ it "removes the sibling column tag and preserves unrelated tags" do
+ result
+ expect(card.reload.tag_ids).to contain_exactly(column_tag.id, unrelated_tag.id)
+ end
+ end
+
+ context "when preserving notes when not provided" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Keep details",
+ notes: "Important note",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "title" => "Updated" } }
+ let(:params) { { board_id: board.id, id: card.id, title: "Updated" } }
+
+ it "preserves notes" do
+ original_notes = card.notes
+ result
+ card.reload
+ expect(card.notes).to eq(original_notes)
+ end
+ end
+
+ context "when promoting a floater to a topic card" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ notes: "Some notes",
+ tag_ids: [tag.id],
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it { is_expected.to run_successfully }
+
+ it "converts the card to a topic card" do
+ result_card = result[:card]
+ expect(result_card).to be_topic
+ expect(result_card.topic_id).to eq(topic.id)
+ expect(result_card.title).to be_nil
+ expect(result_card.notes).to be_nil
+ expect(result_card.tag_ids).to eq([])
+ end
+ end
+
+ context "when adopting an existing topic card" do
+ fab!(:existing_topic_card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ it { is_expected.to run_successfully }
+
+ it "sets original_column_id to the adopted card's original column" do
+ expect(result[:original_column_id]).to eq(col_todo.id)
+ end
+
+ it "sets adopted_floater_id to the floater's id" do
+ expect(result[:adopted_floater_id]).to eq(card.id)
+ end
+
+ it "destroys the floater" do
+ result
+ expect(Boards::Card.find_by(id: card.id)).to be_nil
+ end
+ end
+
+ context "when adopting an existing topic card from an assigned floater" do
+ fab!(:assignee, :user)
+ fab!(:existing_topic_card) do
+ board.cards.create!(
+ card_type: :topic,
+ topic_id: topic.id,
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 1,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(assignee)
+ Fabricate(:post, topic: topic)
+ end
+
+ it "carries over the assignment to the topic" do
+ result
+ assignment = Assignment.find_by(target: topic, active: true)
+ expect(assignment).to be_present
+ expect(assignment.assigned_to).to eq(assignee)
+ end
+ end
+
+ context "when moving a card to position 0 in a column" do
+ fab!(:card_a) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Card A",
+ column_id: col_done.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:card_b) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Card B",
+ column_id: col_done.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move to first",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "column_id" => col_done.id.to_s, "after_card_id" => "" } }
+ let(:params) { { board_id: board.id, id: card.id, column_id: col_done.id } }
+
+ it { is_expected.to run_successfully }
+
+ it "places the card first in the column" do
+ result
+ card.reload
+ card_a.reload
+ card_b.reload
+ expect(card.column_id).to eq(col_done.id)
+ expect(card.position).to be < card_a.position
+ expect(card_a.position).to be < card_b.position
+ end
+ end
+
+ context "when moving a card into a column sorted by recency" do
+ fab!(:existing_card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Existing",
+ column_id: col_recent.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Move to recent",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) do
+ { "column_id" => col_recent.id.to_s, "after_card_id" => existing_card.id.to_s }
+ end
+ let(:params) do
+ {
+ board_id: board.id,
+ id: card.id,
+ column_id: col_recent.id,
+ after_card_id: existing_card.id,
+ }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "ignores the requested position and places the card first" do
+ result
+ expect(card.reload.position).to be < existing_card.reload.position
+ end
+ end
+
+ context "when reordering within a column sorted by recency" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "First",
+ column_id: col_recent.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ fab!(:other_card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Second",
+ column_id: col_recent.id,
+ position: 1,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) do
+ { "column_id" => col_recent.id.to_s, "after_card_id" => other_card.id.to_s }
+ end
+ let(:params) do
+ { board_id: board.id, id: card.id, column_id: col_recent.id, after_card_id: other_card.id }
+ end
+
+ it "raises InvalidParameters" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ expect(card.reload.position).to eq(0)
+ end
+ end
+
+ context "when assigning a user to a floater card" do
+ fab!(:assignee, :user)
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Assign me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "assigned_to_name" => assignee.username } }
+ let(:params) { { board_id: board.id, id: card.id, assigned_to_name: assignee.username } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "assigns the user" do
+ result
+ expect(card.reload.assigned_to).to eq(assignee)
+ end
+ end
+
+ context "when assigning a group to a floater card" do
+ fab!(:assignee_group, :group)
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Assign group",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "assigned_to_name" => assignee_group.name } }
+ let(:params) { { board_id: board.id, id: card.id, assigned_to_name: assignee_group.name } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "assigns the group" do
+ result
+ expect(card.reload.assigned_to).to eq(assignee_group)
+ end
+ end
+
+ context "when unassigning a floater card" do
+ fab!(:assignee, :user)
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Unassign me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+ end
+
+ let(:raw_card_params) { { "assigned_to_name" => "" } }
+ let(:params) { { board_id: board.id, id: card.id, assigned_to_name: "" } }
+
+ it { is_expected.to run_successfully }
+
+ it "clears the assignment" do
+ result
+ expect(card.reload.assigned_to).to be_nil
+ end
+ end
+
+ context "when assigning an unknown name" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Unknown assignee",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "assigned_to_name" => "nonexistent_name" } }
+ let(:params) { { board_id: board.id, id: card.id, assigned_to_name: "nonexistent_name" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ end
+
+ it "raises InvalidParameters" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+
+ context "when assigning a group the user cannot see" do
+ fab!(:hidden_group) { Fabricate(:group, visibility_level: Group.visibility_levels[:staff]) }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Hidden group",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "assigned_to_name" => hidden_group.name } }
+ let(:params) { { board_id: board.id, id: card.id, assigned_to_name: hidden_group.name } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(writer)
+ end
+
+ it "raises InvalidParameters" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+
+ context "when writer without assign permissions tries to assign a floater" do
+ fab!(:assignee, :user)
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "No perms",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:raw_card_params) { { "assigned_to_name" => assignee.username } }
+ let(:params) { { board_id: board.id, id: card.id, assigned_to_name: assignee.username } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ end
+
+ it "raises InvalidAccess" do
+ expect { result }.to raise_error(Discourse::InvalidAccess)
+ end
+ end
+
+ context "when writer without assign permissions promotes an assigned floater" do
+ fab!(:assignee, :user)
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Assigned floater",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ end
+
+ it "raises InvalidAccess instead of silently dropping the assignment" do
+ expect { result }.to raise_error(Discourse::InvalidAccess)
+ expect(card.reload).to be_floater
+ end
+ end
+
+ context "when promoting a floater with assignment to a topic card" do
+ fab!(:assignee, :user)
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Promote me",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(assignee)
+ Fabricate(:post, topic: topic)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "clears the card-level assignment on promotion" do
+ result_card = result[:card]
+ expect(result_card.assigned_to_id).to be_nil
+ expect(result_card.assigned_to_type).to be_nil
+ end
+
+ it "assigns the card's assignee to the topic" do
+ result
+ assignment = Assignment.find_by(target: topic, active: true)
+ expect(assignment).to be_present
+ expect(assignment.assigned_to).to eq(assignee)
+ end
+ end
+
+ context "when promoting an assigned floater and column has move_to_assigned" do
+ fab!(:assignee, :user)
+ fab!(:column_assignee, :user)
+ fab!(:col_assigned) do
+ board.columns.create!(
+ title: "Assigned Col",
+ position: 2,
+ move_to_assigned: column_assignee.username,
+ )
+ end
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Column overrides",
+ column_id: col_assigned.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(column_assignee)
+ Fabricate(:post, topic: topic)
+ end
+
+ it "uses the column's assignment rule instead of the card assignee" do
+ result
+ assignment = Assignment.find_by(target: topic, active: true)
+ expect(assignment).to be_present
+ expect(assignment.assigned_to).to eq(column_assignee)
+ end
+ end
+
+ context "when promoting an assigned floater and column has move_to_assigned '*'" do
+ fab!(:assignee, :user)
+ fab!(:col_star) do
+ board.columns.create!(title: "Star Col", position: 2, move_to_assigned: "*")
+ end
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Star keeps card assignee",
+ column_id: col_star.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ assign_group = Fabricate(:group)
+ SiteSetting.assign_allowed_on_groups = assign_group.id.to_s
+ assign_group.add(assignee)
+ Fabricate(:post, topic: topic)
+ end
+
+ it "carries over the card's assignee" do
+ result
+ assignment = Assignment.find_by(target: topic, active: true)
+ expect(assignment).to be_present
+ expect(assignment.assigned_to).to eq(assignee)
+ end
+ end
+
+ context "when promoting a floater with group assignment" do
+ fab!(:assignee_group) { Fabricate(:group, assignable_level: Group::ALIAS_LEVELS[:everyone]) }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Group assign",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ assigned_to: assignee_group,
+ )
+ end
+
+ let(:raw_card_params) { { "topic_id" => topic.id.to_s } }
+ let(:params) { { board_id: board.id, id: card.id, topic_id: topic.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before do
+ skip("requires discourse-assign") unless defined?(::Assigner)
+ SiteSetting.assign_enabled = true
+ SiteSetting.assign_allowed_on_groups = assignee_group.id.to_s
+ Fabricate(:post, topic: topic)
+ end
+
+ it "assigns the group to the topic" do
+ result
+ assignment = Assignment.find_by(target: topic, active: true)
+ expect(assignment).to be_present
+ expect(assignment.assigned_to).to eq(assignee_group)
+ end
+ end
+
+ context "when card is not found" do
+ let(:params) { { board_id: board.id, id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:card) }
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, id: 1 } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when user cannot write" do
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "Protected",
+ column_id: col_todo.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { board_id: board.id, id: card.id } }
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_write) }
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/update_column_spec.rb b/plugins/boards/spec/services/boards/update_column_spec.rb
new file mode 100644
index 00000000000..4c0d4686f62
--- /dev/null
+++ b/plugins/boards/spec/services/boards/update_column_spec.rb
@@ -0,0 +1,211 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::UpdateColumn do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:board_id) }
+ it { is_expected.to validate_presence_of(:id) }
+ it { is_expected.to validate_presence_of(:title) }
+ it { is_expected.to allow_value(nil, "f0a", "1A2B3C").for(:color) }
+ it { is_expected.not_to allow_value("#1A2B3C", "purple").for(:color) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:outsider, :user)
+ fab!(:manage_group, :group)
+ fab!(:board) do
+ Fabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])
+ end
+ fab!(:column) { board.columns.create!(title: "Old", position: 0) }
+
+ let(:params) do
+ { board_id: board.id, id: column.id, title: "New", color: "1A2B3C", default_sort: "priority" }
+ end
+ let(:dependencies) { { guardian: manager.guardian } }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { board_id: board.id, id: column.id, title: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when board is not found" do
+ let(:params) { { board_id: 0, id: column.id, title: "New" } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when column is not found" do
+ let(:params) { { board_id: board.id, id: 0, title: "New" } }
+
+ it { is_expected.to fail_to_find_a_model(:column) }
+ end
+
+ context "when user cannot manage boards" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "updates the column without changing position" do
+ result
+
+ expect(column.reload).to have_attributes(title: "New", color: "1A2B3C", position: 0)
+ end
+
+ it "tracks the column renamed history" do
+ result
+
+ expect(board.history.find_by(action: :column_renamed)).to have_attributes(
+ action: "column_renamed",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ column_id: column.id,
+ details: {
+ "previous_value" => "Old",
+ "new_value" => "New",
+ },
+ )
+ end
+
+ context "with non-title changes" do
+ let(:params) do
+ {
+ board_id: board.id,
+ id: column.id,
+ title: "Old",
+ icon: "check",
+ color: "f0a",
+ default_sort: "recency",
+ }
+ end
+
+ it "tracks the column edited history" do
+ result
+
+ expect(board.history.last).to have_attributes(
+ action: "column_edited",
+ acting_user_id: manager.id,
+ board_id: board.id,
+ column_id: column.id,
+ details: {
+ "previous_values" => {
+ "icon" => nil,
+ "color" => nil,
+ "default_sort" => "priority",
+ },
+ "new_values" => {
+ "icon" => "check",
+ "color" => "f0a",
+ "default_sort" => "recency",
+ },
+ },
+ )
+ end
+ end
+
+ context "with title and non-title changes" do
+ let(:params) do
+ { board_id: board.id, id: column.id, title: "New", default_sort: "recency" }
+ end
+
+ it "tracks the renamed and edited histories separately" do
+ result
+
+ expect(board.history.map(&:action)).to eq(%w[column_renamed column_edited])
+ end
+ end
+
+ it "publishes a board_updated event" do
+ messages = MessageBus.track_publish("/boards/#{board.id}") { result }
+
+ expect(messages.map { |message| message.data[:type] }).to include("board_updated")
+ end
+
+ context "with a tag name" do
+ fab!(:tag)
+
+ let(:params) { { board_id: board.id, id: column.id, title: "New", tag_name: tag.name } }
+
+ it "assigns the visible tag and updates loose cards" do
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Loose",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ result
+
+ expect(column.reload.tag_id).to eq(tag.id)
+ expect(card.reload.tag_ids).to contain_exactly(tag.id)
+ end
+
+ it "rejects duplicate sibling tags" do
+ board.columns.create!(title: "Sibling", position: 1, tag_id: tag.id)
+
+ expect { result }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.cannot_use_same_tag_multiple_times", tag_name: tag.name),
+ )
+ end
+ end
+
+ context "when a tag is not visible to the user" do
+ fab!(:restricted_tag, :tag)
+
+ let(:params) do
+ { board_id: board.id, id: column.id, title: "Hidden", tag_name: restricted_tag.name }
+ end
+
+ before { Fabricate(:tag_group, permissions: { "staff" => 1 }, tags: [restricted_tag]) }
+
+ it "does not resolve the hidden tag" do
+ expect { result }.to raise_error(
+ Discourse::InvalidParameters,
+ I18n.t("boards.errors.unknown_tag_name", tag_name: restricted_tag.name),
+ )
+ end
+ end
+
+ context "when default sort is invalid" do
+ let(:params) { { board_id: board.id, id: column.id, title: "Broken", default_sort: "x" } }
+
+ it "raises an invalid parameters error" do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end
+ end
+
+ context "when loose-card tag enforcement fails" do
+ fab!(:tag)
+
+ let(:params) { { board_id: board.id, id: column.id, title: "New", tag_name: tag.name } }
+
+ before do
+ allow(Boards::LooseCardTagMutator).to receive(:apply_to_column!).and_raise(
+ ActiveRecord::RecordInvalid,
+ )
+ end
+
+ it "rolls back the column update" do
+ expect { result }.to raise_error(ActiveRecord::RecordInvalid)
+ expect(column.reload.tag_id).to be_nil
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/view_board_spec.rb b/plugins/boards/spec/services/boards/view_board_spec.rb
new file mode 100644
index 00000000000..a286d673592
--- /dev/null
+++ b/plugins/boards/spec/services/boards/view_board_spec.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::ViewBoard do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:reader, :user)
+ fab!(:outsider, :user)
+ fab!(:read_group, :group)
+ fab!(:write_group, :group)
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board-view", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+
+ let(:params) { { id: board.id } }
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ before do
+ enable_current_plugin
+ read_group.add(reader)
+ end
+
+ context "when user is not logged in" do
+ let(:dependencies) { { guardian: Guardian.new } }
+
+ it { is_expected.to fail_a_policy(:is_logged_in) }
+ end
+
+ context "when board is not found" do
+ let(:params) { { id: 0 } }
+
+ it { is_expected.to fail_to_find_a_model(:board) }
+ end
+
+ context "when board was already viewed today" do
+ before { Boards::BoardHistory.create!(board:, acting_user: reader, action: :board_viewed) }
+
+ it { is_expected.to run_successfully }
+
+ it "does not create a duplicate history record" do
+ expect { result }.not_to change {
+ Boards::BoardHistory.where(action: :board_viewed, board_id: board.id).count
+ }
+ end
+ end
+
+ context "when user cannot read the board" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_read_board) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a board view history record" do
+ expect { result }.to change {
+ Boards::BoardHistory.where(action: :board_viewed, board_id: board.id).count
+ }.by(1)
+ expect(
+ Boards::BoardHistory.where(action: :board_viewed, board_id: board.id).last,
+ ).to have_attributes(acting_user_id: reader.id, board_id: board.id)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/services/boards/view_card_spec.rb b/plugins/boards/spec/services/boards/view_card_spec.rb
new file mode 100644
index 00000000000..7eaab7d7e6b
--- /dev/null
+++ b/plugins/boards/spec/services/boards/view_card_spec.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+RSpec.describe Boards::ViewCard do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:reader, :user)
+ fab!(:outsider, :user)
+ fab!(:read_group, :group)
+ fab!(:write_group, :group)
+ fab!(:board) do
+ board = Boards::Board.create!(name: "Board", slug: "board-view", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { board.columns.create!(title: "Col", position: 0) }
+ fab!(:card) do
+ board.cards.create!(
+ card_type: :floater,
+ title: "View Me",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ end
+
+ let(:params) { { id: card.id } }
+ let(:dependencies) { { guardian: reader.guardian } }
+
+ before do
+ enable_current_plugin
+ read_group.add(reader)
+ end
+
+ context "when user is not logged in" do
+ let(:dependencies) { { guardian: Guardian.new } }
+
+ it { is_expected.to fail_a_policy(:is_logged_in) }
+ end
+
+ context "when card is not found" do
+ before { card.destroy! }
+
+ it { is_expected.to fail_to_find_a_model(:card) }
+ end
+
+ context "when user cannot view the card" do
+ let(:dependencies) { { guardian: outsider.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_view_card) }
+ end
+
+ context "when view history was already recorded today" do
+ before do
+ Boards::CardHistory.create!(
+ card:,
+ acting_user: reader,
+ action: :card_viewed,
+ board_id: board.id,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not create a duplicate history record" do
+ expect { result }.not_to change {
+ Boards::CardHistory.where(action: :card_viewed, card_id: card.id).count
+ }
+ end
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a card view history record" do
+ expect { result }.to change {
+ Boards::CardHistory.where(action: :card_viewed, card_id: card.id).count
+ }.by(1)
+ end
+
+ it "records the acting user and board" do
+ result
+ history = Boards::CardHistory.where(action: :card_viewed, card_id: card.id).last
+ expect(history).to have_attributes(acting_user_id: reader.id, board_id: board.id)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/add_topic_to_board_spec.rb b/plugins/boards/spec/system/add_topic_to_board_spec.rb
new file mode 100644
index 00000000000..e4cefad5f0e
--- /dev/null
+++ b/plugins/boards/spec/system/add_topic_to_board_spec.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+describe "Add topic to board from topic footer menu" do
+ fab!(:admin)
+ fab!(:viewer, :user)
+ fab!(:view_group, :group)
+ fab!(:original_category, :category)
+ fab!(:target_category, :category)
+ fab!(:topic) { Fabricate(:topic_with_op, category: original_category) }
+ fab!(:product_board) { Fabricate(:boards_board, name: "Product", column_names: %w[Backlog Done]) }
+ fab!(:engineering_board) do
+ Fabricate(:boards_board, name: "Engineering", column_names: ["Doing"])
+ end
+ fab!(:roadmap_board) do
+ Fabricate(
+ :boards_board,
+ name: "Roadmap",
+ column_names: ["Next"],
+ category_ids: [target_category.id],
+ )
+ end
+ fab!(:product_board_view_acl) do
+ Fabricate(
+ :access_control_list_with_groups,
+ target: product_board,
+ permission: "view",
+ groups: [view_group],
+ )
+ end
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+ let(:add_from_topic) { PageObjects::Components::BoardsAddFromTopic.new }
+ let(:category_badge) { PageObjects::Components::CategoryBadge.new }
+ let(:toasts) { PageObjects::Components::Toasts.new }
+ let(:constraint_modal) do
+ PageObjects::Modals::Base.new(body_selector: ".discourse-boards-constraint-fix-modal")
+ end
+
+ before { enable_current_plugin }
+
+ context "when logged in" do
+ it "adds the topic to a board column" do
+ column = product_board.columns.first
+
+ sign_in(admin)
+ topic_page.visit_topic(topic)
+ add_from_topic.add_to_column(product_board, column)
+
+ expect(add_from_topic).to have_membership(product_board, column)
+ expect(product_board.cards.topic.find_by(topic: topic, column: column)).to be_present
+ end
+
+ it "removes the topic from a board column" do
+ column = product_board.columns.first
+ card = Fabricate(:boards_topic_card, board: product_board, column:, topic:)
+
+ sign_in(admin)
+ topic_page.visit_topic(topic)
+ expect(add_from_topic).to have_membership(product_board, column)
+
+ add_from_topic.remove_from_column(product_board, column)
+
+ expect(toasts).to have_success(
+ I18n.t(
+ "js.boards.board.removed_topic_from_board",
+ boardName: product_board.unicode_name,
+ columnName: column.unicode_title,
+ ),
+ )
+ expect(Boards::Card).not_to exist(card.id)
+ end
+
+ xit "fixes constraints and updates the topic header through MessageBus" do
+ existing_column = engineering_board.columns.first
+ Fabricate(:boards_topic_card, board: engineering_board, column: existing_column, topic: topic)
+ target_column = roadmap_board.columns.first
+
+ sign_in(admin)
+ topic_page.visit_topic(topic)
+ expect(add_from_topic).to have_membership(engineering_board, existing_column)
+
+ add_from_topic.add_to_column(roadmap_board, target_column)
+
+ expect(constraint_modal).to be_open
+ constraint_modal.click_primary_button
+
+ expect(topic.reload.category).to eq(target_category)
+ within("#topic-title") { category_badge.find_for_category(target_category) }
+ expect(add_from_topic).to have_membership_count(2)
+
+ add_from_topic.open_memberships
+ expect(add_from_topic).to have_membership_in_menu(engineering_board, existing_column)
+ expect(add_from_topic).to have_membership_in_menu(roadmap_board, target_column)
+ end
+
+ it "hides the button from users without edit or manage access to any board" do
+ view_group.add(viewer)
+ sign_in(viewer)
+
+ topic_page.visit_topic(topic)
+
+ expect(add_from_topic).to have_no_add_to_board_button
+ end
+ end
+
+ context "when anonymous" do
+ it "hides the button" do
+ topic_page.visit_topic(topic)
+
+ expect(add_from_topic).to have_no_add_to_board_button
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/boards_board_viewer_spec.rb b/plugins/boards/spec/system/boards_board_viewer_spec.rb
new file mode 100644
index 00000000000..b1b75025869
--- /dev/null
+++ b/plugins/boards/spec/system/boards_board_viewer_spec.rb
@@ -0,0 +1,774 @@
+# frozen_string_literal: true
+
+describe "Boards Board Viewer" do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:manage_group, :group)
+ fab!(:write_group, :group)
+ fab!(:category)
+ fab!(:tag1, :tag) { Fabricate(:tag, name: "priority") }
+ fab!(:tag2, :tag) { Fabricate(:tag, name: "frontend") }
+
+ let(:board_viewer) { PageObjects::Pages::BoardsBoardViewer.new }
+ let(:dialog) { PageObjects::Components::Dialog.new }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ write_group.add(user)
+ write_group.add(admin)
+ end
+
+ class CreateBoardResult
+ attr_reader :board, :columns
+
+ def initialize(board, columns = {})
+ @board = board
+ @columns = columns
+ end
+
+ def column(title)
+ columns[title]
+ end
+ end
+
+ def create_board(
+ attrs = {},
+ with_columns: [],
+ read_groups: [write_group, manage_group],
+ write_groups: []
+ )
+ board =
+ Fabricate(
+ :boards_board,
+ {
+ name: "Sprint Board",
+ slug: "sprint-board",
+ created_by_id: admin.id,
+ require_confirmation: true,
+ show_tags: true,
+ category_ids: [category.id],
+ additional_manage_groups: [manage_group],
+ }.merge(attrs),
+ )
+
+ # Make the board readable by the signed-in actors (a write_group
+ # member and a manage_group member). Move tests override write access.
+ if read_groups.present?
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: read_groups,
+ )
+ end
+ if write_groups.present?
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: write_groups,
+ )
+ end
+
+ columns =
+ with_columns.each_with_object({}) do |column_attrs, hash|
+ title = column_attrs[:title] || column_attrs["title"]
+ hash[title] = board.columns.create!(column_attrs)
+ end
+
+ CreateBoardResult.new(board, columns)
+ end
+
+ def add_topic_card(board, column, topic)
+ card = board.cards.find_by(topic_id: topic.id)
+ if card
+ card.update!(column_id: column.id) if card.column_id != column.id
+ return card
+ end
+ board.cards.create!(
+ topic_id: topic.id,
+ column_id: column.id,
+ card_type: :topic,
+ position: column.cards.count,
+ created_by_id: admin.id,
+ )
+ end
+
+ context "when viewing a board" do
+ it "uses the full available page width" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+ RemoteTheme.import_theme_from_directory(Rails.root.join("themes/horizon")).set_default!
+
+ sign_in(user)
+ page.current_window.resize_to(1800, 1000)
+ board_viewer.visit_board(result.board)
+
+ expect(board_viewer).to have_board_title("Sprint Board")
+
+ layout = page.evaluate_script(<<~JS)
+ (() => {
+ const viewer = document.querySelector(".discourse-boards-board-viewer");
+ const rect = viewer.getBoundingClientRect();
+
+ return {
+ bodyHasBoardClass: document.body.classList.contains("discourse-boards-board"),
+ viewerRight: Math.round(rect.right),
+ viewportWidth: window.innerWidth,
+ };
+ })()
+ JS
+
+ expect(layout["bodyHasBoardClass"]).to eq(true)
+ expect(layout["viewerRight"]).to eq(layout["viewportWidth"])
+ end
+
+ it "displays columns and cards" do
+ result =
+ create_board(
+ { tag_ids: [tag1.id, tag2.id] },
+ with_columns: [
+ { title: "To Do", position: 0, icon: "list", tag_id: tag1.id },
+ { title: "Done", position: 1, icon: "check", tag_id: tag2.id },
+ ],
+ )
+ board = result.board
+
+ topic_1 = Fabricate(:topic, title: "Implement login page", category: category, tags: [tag1])
+ topic2 =
+ Fabricate(
+ :topic,
+ title: "Write integration test coverage",
+ category: category,
+ tags: [tag1],
+ )
+ topic3 = Fabricate(:topic, title: "Deploy to staging", category: category, tags: [tag2])
+
+ add_topic_card(board, result.column("To Do"), topic_1)
+ add_topic_card(board, result.column("To Do"), topic2)
+ add_topic_card(board, result.column("Done"), topic3)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_board_title("Sprint Board")
+ expect(board_viewer).to have_column("To Do")
+ expect(board_viewer).to have_column("Done")
+ expect(board_viewer).to have_card_in_column("To Do", "Implement login page")
+ expect(board_viewer).to have_card_in_column("To Do", "Write integration test coverage")
+ expect(board_viewer).to have_card_in_column("Done", "Deploy to staging")
+ expect(board_viewer.card_count_in_column("To Do")).to eq(2)
+ expect(board_viewer.card_count_in_column("Done")).to eq(1)
+ end
+ end
+
+ context "when visiting a board with the wrong slug" do
+ it "redirects to the correct slug without losing the linked card" do
+ result =
+ create_board(with_columns: [{ title: "To Do", position: 0, default_sort: "recency" }])
+ column = result.column("To Do")
+ linked_topic = Fabricate(:topic, title: "Keep linked card", category:)
+ stale_topic = Fabricate(:topic, title: "Hidden by recency", category:)
+ linked_card = add_topic_card(result.board, column, linked_topic)
+ stale_card = add_topic_card(result.board, column, stale_topic)
+
+ # Age both cards out of the recency column's window, so the linked card
+ # only stays rendered because the URL points at it.
+ [linked_topic, stale_topic].each { |t| t.update_columns(bumped_at: 3.weeks.ago) }
+ [linked_card, stale_card].each { |c| c.update_columns(column_changed_at: 3.weeks.ago) }
+
+ sign_in(user)
+ page.visit "/boards/wrong-slug/#{result.board.id}?card=#{linked_card.id}"
+
+ expect(board_viewer).to have_board_title("Sprint Board")
+ expect(page).to have_current_path(
+ "/boards/sprint-board/#{result.board.id}?card=#{linked_card.id}",
+ )
+ expect(board_viewer).to have_card_in_column("To Do", "Keep linked card")
+ expect(board_viewer).to have_no_card_in_column("To Do", "Hidden by recency")
+ end
+ end
+
+ context "when dragging cards with confirmation" do
+ it "moves card after confirming" do
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }, { title: "Done", position: 1 }],
+ )
+ board = result.board
+
+ topic_1 = Fabricate(:topic, title: "Fix critical checkout regression", category: category)
+ add_topic_card(board, result.column("To Do"), topic_1)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_card_in_column("To Do", "Fix critical checkout regression")
+
+ board_viewer.drag_card_to_column("Fix critical checkout regression", "Done")
+ dialog.click_yes
+
+ expect(board_viewer).to have_card_in_column("Done", "Fix critical checkout regression")
+ expect(board_viewer).to have_no_card_in_column("To Do", "Fix critical checkout regression")
+ end
+ end
+
+ context "when dragging cards without confirmation" do
+ it "moves card immediately" do
+ result =
+ create_board(
+ { require_confirmation: false },
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }, { title: "Done", position: 1 }],
+ )
+ board = result.board
+
+ topic_1 = Fabricate(:topic, title: "Polish release checklist", category: category)
+ add_topic_card(board, result.column("To Do"), topic_1)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.drag_card_to_column("Polish release checklist", "Done")
+
+ expect(board_viewer).to have_card_in_column("Done", "Polish release checklist")
+ expect(board_viewer).to have_no_card_in_column("To Do", "Polish release checklist")
+ end
+ end
+
+ context "when user has read-only access" do
+ it "cards are not draggable" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+ board = result.board
+
+ topic_1 = Fabricate(:topic, title: "Read only topic", category: category)
+ add_topic_card(board, result.column("To Do"), topic_1)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_card_in_column("To Do", "Read only topic")
+ expect(board_viewer.card_draggable?("Read only topic")).to eq(false)
+ end
+ end
+
+ context "when cards have tags" do
+ it "shows tags but filters column tags" do
+ result =
+ create_board(
+ { show_tags: true },
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0, tag_id: tag1.id }],
+ )
+ board = result.board
+
+ topic_1 =
+ Fabricate(
+ :topic,
+ title: "Refine frontend labeling workflow",
+ category: category,
+ tags: [tag1, tag2],
+ )
+ add_topic_card(board, result.column("To Do"), topic_1)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_tag_on_card("Refine frontend labeling workflow", "frontend")
+ expect(board_viewer).to have_no_tag_on_card("Refine frontend labeling workflow", "priority")
+ end
+ end
+
+ context "with floater cards" do
+ it "creates a floater card via the add card button" do
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_add_card_button_in_column("To Do")
+ board_viewer.click_add_card("To Do")
+ board_viewer.fill_card_title("My new task")
+ board_viewer.submit_card
+
+ expect(board_viewer).to have_floater_card_in_column("To Do", "My new task")
+ expect(Boards::Card.find_by(title: "My new task")).to be_present
+ end
+
+ it "persists tags when creating a floater card" do
+ SiteSetting.tagging_enabled = true
+
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_card("To Do")
+ board_viewer.fill_card_title("Tagged task")
+ board_viewer.select_card_detail_tag(tag1.name)
+ board_viewer.submit_card
+
+ expect(board_viewer).to have_floater_card_in_column("To Do", "Tagged task")
+ expect(board_viewer).to have_card_tag("Tagged task", tag1.name)
+ expect(Boards::Card.find_by!(title: "Tagged task").tag_ids).to eq([tag1.id])
+ end
+
+ it "renders stored floater-card titles as text for read-only users" do
+ payload =
+ 'Read this <img src="data:image/png;base64,invalid" onerror="document.body.dataset.boardsXss=\'executed\'">'
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+ board_viewer.click_add_card("To Do")
+ board_viewer.fill_card_title(payload)
+ board_viewer.submit_card
+
+ expect(Boards::Card.find_by!(title: payload)).to be_present
+
+ sign_in(manager)
+ board_viewer.visit_board(board)
+ board_viewer.click_floater_card(payload)
+
+ expect(board_viewer).to have_card_detail_modal
+ expect(page).to have_css(
+ ".discourse-boards-card-detail-modal .discourse-boards-editable-title__text",
+ text: "Read this",
+ )
+ expect(page).to have_text(payload)
+ sleep 2
+ expect(page).to have_no_css(".discourse-boards-card-detail-modal img[onerror]")
+ expect(page).to have_no_css("body[data-boards-xss='executed']")
+ end
+
+ it "opens the card detail modal when clicking a floater card" do
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+ board.cards.create!(
+ card_type: :floater,
+ title: "Old task name",
+ column_id: result.column("To Do").id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_floater_card_in_column("To Do", "Old task name")
+
+ board_viewer.click_floater_card("Old task name")
+ expect(board_viewer).to have_card_detail_modal
+ board_viewer.fill_card_detail_title("Updated task name")
+ board_viewer.save_card_detail
+
+ expect(board_viewer).to have_floater_card_in_column("To Do", "Updated task name")
+ expect(Boards::Card.find_by(title: "Updated task name")).to be_present
+ end
+
+ it "shows an edit action in the floater card menu" do
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+ board.cards.create!(
+ card_type: :floater,
+ title: "Old task name",
+ column_id: result.column("To Do").id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+
+ board_viewer.open_card_actions("Old task name")
+ expect(board_viewer).to have_edit_card_action
+ board_viewer.click_edit_card
+ expect(board_viewer).to have_card_detail_modal
+ board_viewer.cancel_card_detail
+ end
+
+ it "adds tags to a card via the tag chooser" do
+ SiteSetting.tagging_enabled = true
+ Tag.find_or_create_by!(name: "urgent")
+
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+ board.cards.create!(
+ card_type: :floater,
+ title: "Tag me",
+ column_id: result.column("To Do").id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_floater_card("Tag me")
+ expect(board_viewer).to have_card_detail_modal
+
+ board_viewer.select_card_detail_tag("urgent")
+ expect(board_viewer).to have_card_detail_tag("urgent")
+
+ board_viewer.save_card_detail
+ expect(board_viewer).to have_card_tag("Tag me", "urgent")
+ end
+
+ it "creates a new tag from the card detail modal" do
+ SiteSetting.tagging_enabled = true
+ SiteSetting.create_tag_allowed_groups = Group::AUTO_GROUPS[:logged_in_users]
+
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+ board.cards.create!(
+ card_type: :floater,
+ title: "Needs new tag",
+ column_id: result.column("To Do").id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_floater_card("Needs new tag")
+ expect(board_viewer).to have_card_detail_modal
+
+ board_viewer.create_card_detail_tag("brand-new-tag")
+ expect(board_viewer).to have_card_detail_tag("brand-new-tag")
+
+ board_viewer.save_card_detail
+
+ expect(board_viewer).to have_card_tag("Needs new tag", "brand-new-tag")
+ card = Boards::Card.find_by!(title: "Needs new tag")
+ tag = Tag.find_by(name: "brand-new-tag")
+ expect(tag).to be_present
+ expect(card.tag_ids).to include(tag.id)
+ end
+
+ it "tabs from the title to notes and leaves close last" do
+ result =
+ create_board(
+ {},
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_card("To Do")
+ expect(board_viewer).to have_card_detail_modal
+
+ find(".discourse-boards-card-detail-modal .discourse-boards-editable-title__input").send_keys(
+ :tab,
+ )
+ expect(page.active_element).to eq(
+ first(
+ ".discourse-boards-card-detail-modal .form-kit__field[data-name='notes'] .d-editor-button-bar button[tabindex='0']",
+ minimum: 1,
+ ),
+ )
+
+ page.active_element.send_keys(:tab)
+ expect(page.active_element).to eq(
+ first(
+ ".discourse-boards-card-detail-modal .form-kit__field[data-name='notes'] .ProseMirror.d-editor-input",
+ minimum: 1,
+ ),
+ )
+
+ find(".discourse-boards-card-detail-modal .d-modal-cancel").send_keys(:tab)
+
+ expect(page.active_element).to eq(
+ find(".discourse-boards-card-detail-modal .discourse-boards-card-detail-modal__close"),
+ )
+ end
+
+ it "does not show add card button for read-only users" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+
+ sign_in(user)
+ board_viewer.visit_board(result.board)
+
+ expect(board_viewer).to have_no_add_card_button_in_column("To Do")
+ end
+ end
+
+ context "with topic card detail modal" do
+ it "opens the topic at the latest unread post" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Review unread replies", category: category)
+ 4.times { Fabricate(:post, topic:) }
+ TopicUser.change(user.id, topic.id, last_read_post_number: 2)
+
+ add_topic_card(board, result.column("To Do"), topic)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+ board_viewer.click_topic_card("Review unread replies")
+ board_viewer.click_topic_card_view_topic
+
+ expect(page).to have_current_path("/t/#{topic.slug}/#{topic.id}/3")
+ end
+
+ it "opens the topic detail modal when clicking a topic card" do
+ result = create_board({ show_tags: true }, with_columns: [{ title: "To Do", position: 0 }])
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Implement search feature", category: category, tags: [tag1])
+ Fabricate(:post, topic: topic, raw: "Here is the **plan** for implementing search.")
+ Fabricate(:post, topic: topic, raw: "Looks great, let's do it!")
+
+ add_topic_card(board, result.column("To Do"), topic)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_topic_card("Implement search feature")
+ expect(board_viewer).to have_topic_card_detail_modal
+ expect(board_viewer).to have_topic_card_detail_cooked
+ expect(board_viewer).to have_topic_card_detail_category
+ expect(board_viewer).to have_topic_card_detail_tags
+ expect(board_viewer).to have_topic_card_detail_reply_count
+ expect(page).to have_current_path(
+ "/boards/sprint-board/#{board.id}/cards/#{board.cards.last.id}",
+ )
+
+ find(".modal-close").click
+ expect(board_viewer).to have_no_topic_card_detail_modal
+ expect(page).to have_current_path("/boards/sprint-board/#{board.id}")
+ end
+
+ it "opens the topic detail modal when visiting a card URL directly" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Fix the login bug on mobile", category: category)
+ Fabricate(:post, topic: topic, raw: "Login is broken on mobile.")
+
+ card = add_topic_card(board, result.column("To Do"), topic)
+
+ sign_in(user)
+ board_viewer.visit_card(board, card)
+
+ expect(board_viewer).to have_board_title("Sprint Board")
+ expect(board_viewer).to have_topic_card_detail_modal
+ expect(board_viewer).to have_topic_card_detail_cooked
+ end
+ end
+
+ context "when adding a topic as card via URL" do
+ it "adds the topic as a card when pasting a URL and clicking submit" do
+ result =
+ create_board(
+ { require_confirmation: false },
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Add dark mode toggle", category: category)
+ Fabricate(:post, topic: topic)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_topic_as_card("To Do")
+ board_viewer.fill_topic_search("/t/#{topic.slug}/#{topic.id}")
+ board_viewer.submit_topic_search
+
+ expect(board_viewer).to have_no_add_topic_as_card_modal
+ expect(board_viewer).to have_card_in_column("To Do", "Add dark mode toggle")
+ expect(board.cards.where(topic_id: topic.id)).to exist
+ end
+
+ it "adds the topic as a card when pasting a URL and pressing Enter" do
+ result =
+ create_board(
+ { require_confirmation: false },
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Ship onboarding tour", category: category)
+ Fabricate(:post, topic: topic)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_topic_as_card("To Do")
+ board_viewer.fill_topic_search("/t/#{topic.slug}/#{topic.id}")
+ board_viewer.submit_topic_search_with_enter
+
+ expect(board_viewer).to have_no_add_topic_as_card_modal
+ expect(board_viewer).to have_card_in_column("To Do", "Ship onboarding tour")
+ expect(board.cards.where(topic_id: topic.id)).to exist
+ end
+
+ it "does not add a card when pasting an external URL that shares a local topic id" do
+ result =
+ create_board(
+ { require_confirmation: false },
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Legit local topic", category: category)
+ Fabricate(:post, topic: topic)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_topic_as_card("To Do")
+ board_viewer.fill_topic_search("https://other-discourse.example/t/imposter-slug/#{topic.id}")
+ board_viewer.submit_topic_search
+
+ expect(page).to have_css(".discourse-boards-add-topic-as-card-modal")
+ expect(board_viewer).to have_no_card_in_column("To Do", "Legit local topic")
+ expect(board.cards.where(topic_id: topic.id)).not_to exist
+ end
+
+ it "does not add a card when an external topic URL is embedded in surrounding text" do
+ result =
+ create_board(
+ { require_confirmation: false },
+ write_groups: [write_group],
+ with_columns: [{ title: "To Do", position: 0 }],
+ )
+ board = result.board
+
+ topic = Fabricate(:topic, title: "Other legit topic", category: category)
+ Fabricate(:post, topic: topic)
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_topic_as_card("To Do")
+ board_viewer.fill_topic_search(
+ "see https://other-discourse.example/t/imposter-slug/#{topic.id}",
+ )
+ board_viewer.submit_topic_search
+
+ expect(page).to have_css(".discourse-boards-add-topic-as-card-modal")
+ expect(board_viewer).to have_no_card_in_column("To Do", "Other legit topic")
+ expect(board.cards.where(topic_id: topic.id)).not_to exist
+ end
+ end
+
+ context "with controls menu" do
+ it "toggles fullscreen mode" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+
+ sign_in(user)
+ board_viewer.visit_board(result.board)
+
+ expect(board_viewer).to have_no_fullscreen
+ board_viewer.click_fullscreen
+
+ expect(board_viewer).to have_fullscreen
+ board_viewer.click_exit_fullscreen
+ expect(board_viewer).to have_no_fullscreen
+ end
+
+ it "shows board settings option for users in the manage group" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+
+ sign_in(manager)
+ board_viewer.visit_board(result.board)
+
+ board_viewer.open_controls_menu
+ expect(board_viewer).to have_board_settings_option
+ end
+
+ it "hides board settings option for users not in the manage group" do
+ result = create_board(with_columns: [{ title: "To Do", position: 0 }])
+
+ sign_in(user)
+ board_viewer.visit_board(result.board)
+
+ board_viewer.open_controls_menu
+ expect(board_viewer).to have_no_board_settings_option
+ end
+ end
+
+ context "when board tag filter excludes topics that match column tag" do
+ fab!(:tag_car, :tag) { Fabricate(:tag, name: "car") }
+ fab!(:tag_animal, :tag) { Fabricate(:tag, name: "animal") }
+ fab!(:tag_fast, :tag) { Fabricate(:tag, name: "fast") }
+
+ it "does not show topics missing the board tag even if they have the column tag" do
+ result =
+ create_board(
+ { tag_ids: [tag_car.id], category_ids: [], slug: "car-board", name: "Car Board" },
+ with_columns: [{ title: "Fast", position: 0, tag_id: tag_fast.id }],
+ )
+
+ Fabricate(
+ :topic,
+ title: "My fast car topic for testing",
+ category: category,
+ tags: [tag_car, tag_fast],
+ )
+ Fabricate(
+ :topic,
+ title: "My fast animal topic for testing",
+ category: category,
+ tags: [tag_animal, tag_fast],
+ )
+
+ sign_in(user)
+ board_viewer.visit_board(result.board)
+
+ expect(board_viewer).to have_card_in_column("Fast", "My fast car topic for testing")
+ expect(board_viewer).to have_no_card_in_column("Fast", "My fast animal topic for testing")
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/boards_card_url_spec.rb b/plugins/boards/spec/system/boards_card_url_spec.rb
new file mode 100644
index 00000000000..56f29ab6961
--- /dev/null
+++ b/plugins/boards/spec/system/boards_card_url_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+describe "Boards Card URL" do
+ fab!(:admin)
+ fab!(:write_group, :group)
+ fab!(:manage_group, :group)
+
+ let(:board_viewer) { PageObjects::Pages::BoardsBoardViewer.new }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ write_group.add(admin)
+ manage_group.add(admin)
+ end
+
+ def create_board_with_floater
+ board =
+ Boards::Board.create!(name: "URL Test Board", slug: "url-test-board", created_by_id: admin.id)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ column = board.columns.create!(title: "To Do", position: 0)
+ card =
+ board.cards.create!(
+ card_type: :floater,
+ title: "Deep link card",
+ column_id: column.id,
+ position: 0,
+ created_by_id: admin.id,
+ )
+ [board, column, card]
+ end
+
+ it "updates URL when clicking a floater card and restores on close" do
+ board, _, card = create_board_with_floater
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+ board_viewer.click_floater_card("Deep link card")
+
+ expect(board_viewer).to have_card_detail_modal
+ expect(page).to have_current_path("/boards/url-test-board/#{board.id}/cards/#{card.id}")
+
+ board_viewer.cancel_card_detail
+
+ expect(board_viewer).to have_no_card_detail_modal
+ expect(page).to have_current_path("/boards/url-test-board/#{board.id}")
+ end
+
+ it "opens modal when visiting a card URL directly" do
+ board, _, _ = create_board_with_floater
+
+ sign_in(admin)
+ board_viewer.visit_card(board, Boards::Card.last)
+
+ expect(board_viewer).to have_board_title("URL Test Board")
+ expect(board_viewer).to have_card_detail_modal
+ end
+
+ it "falls back to board URL for a non-existent card" do
+ board, _, _ = create_board_with_floater
+
+ sign_in(admin)
+ page.visit "/boards/url-test-board/#{board.id}/cards/999999"
+
+ expect(board_viewer).to have_board_title("URL Test Board")
+ expect(board_viewer).to have_no_card_detail_modal
+ expect(page).to have_current_path("/boards/url-test-board/#{board.id}")
+ end
+
+ it "updates URL when opening card from the actions menu" do
+ board, _, card = create_board_with_floater
+
+ sign_in(admin)
+ board_viewer.visit_board(board)
+ board_viewer.open_card_actions("Deep link card")
+ board_viewer.click_edit_card
+
+ expect(board_viewer).to have_card_detail_modal
+ expect(page).to have_current_path("/boards/url-test-board/#{board.id}/cards/#{card.id}")
+ end
+end
diff --git a/plugins/boards/spec/system/boards_keyboard_shortcuts_spec.rb b/plugins/boards/spec/system/boards_keyboard_shortcuts_spec.rb
new file mode 100644
index 00000000000..15b750be0ff
--- /dev/null
+++ b/plugins/boards/spec/system/boards_keyboard_shortcuts_spec.rb
@@ -0,0 +1,225 @@
+# frozen_string_literal: true
+
+describe "Boards Keyboard Shortcuts" do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:write_group, :group)
+
+ let(:board_viewer) { PageObjects::Pages::BoardsBoardViewer.new }
+
+ before do
+ enable_current_plugin
+ write_group.add(user)
+ end
+
+ def create_board(attrs = {})
+ board =
+ Boards::Board.create!(
+ { name: "Sprint Board", slug: "sprint-board", created_by_id: admin.id }.merge(attrs),
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ board
+ end
+
+ def add_floater_card(board, column, title)
+ board.cards.create!(
+ card_type: :floater,
+ title: title,
+ column_id: column.id,
+ position: column.cards.count,
+ created_by_id: admin.id,
+ )
+ end
+
+ def press_key(*keys)
+ find("body").send_keys(*keys)
+ end
+
+ context "when navigating cards on a board" do
+ fab!(:board) do
+ Fabricate(:user) # ensure admin exists
+ b =
+ Boards::Board.create!(
+ name: "Sprint Board",
+ slug: "sprint-board",
+ created_by_id: User.last.id,
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: b,
+ permission: "edit",
+ groups: [write_group],
+ )
+ col1 = b.columns.create!(title: "To Do", position: 0)
+ col2 = b.columns.create!(title: "Done", position: 1)
+ 3.times do |i|
+ b.cards.create!(
+ card_type: :floater,
+ title: "Todo #{i + 1}",
+ column_id: col1.id,
+ position: i,
+ created_by_id: User.last.id,
+ )
+ end
+ 2.times do |i|
+ b.cards.create!(
+ card_type: :floater,
+ title: "Done #{i + 1}",
+ column_id: col2.id,
+ position: i,
+ created_by_id: User.last.id,
+ )
+ end
+ b
+ end
+
+ it "selects first card with j" do
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ press_key("j")
+
+ expect(page).to have_css(".discourse-boards-card--kb-selected")
+ end
+
+ it "moves selection down with j and up with k" do
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ press_key("j")
+ first_selected = find(".discourse-boards-card--kb-selected").text
+
+ press_key("j")
+ second_selected = find(".discourse-boards-card--kb-selected").text
+
+ expect(first_selected).not_to eq(second_selected)
+
+ press_key("k")
+ back_to_first = find(".discourse-boards-card--kb-selected").text
+
+ expect(back_to_first).to eq(first_selected)
+ end
+
+ it "moves between columns with h and l" do
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ # Start in first column
+ press_key("j")
+ first_col_card = find(".discourse-boards-card--kb-selected")
+ first_column = first_col_card.ancestor(".discourse-boards-column")
+
+ # Move to second column
+ press_key("l")
+ second_col_card = find(".discourse-boards-card--kb-selected")
+ second_column = second_col_card.ancestor(".discourse-boards-column")
+
+ expect(first_column).not_to eq(second_column)
+
+ # Move back
+ press_key("h")
+ back_card = find(".discourse-boards-card--kb-selected")
+ back_column = back_card.ancestor(".discourse-boards-column")
+
+ expect(back_column).to eq(first_column)
+ end
+
+ it "clears selection with Escape" do
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ press_key("j")
+ expect(page).to have_css(".discourse-boards-card--kb-selected")
+
+ press_key(:escape)
+ expect(page).to have_no_css(".discourse-boards-card--kb-selected")
+ end
+
+ it "does not interfere with input fields" do
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ board_viewer.click_add_card("To Do")
+ find(".discourse-boards-editable-title__input").send_keys("hjkl")
+
+ expect(find(".discourse-boards-editable-title__input").value).to eq("hjkl")
+ expect(page).to have_no_css(".discourse-boards-card--kb-selected")
+ end
+ end
+
+ context "when navigating the boards list" do
+ before do
+ 3.times do |i|
+ board =
+ Boards::Board.create!(
+ name: "Board #{i + 1}",
+ slug: "board-#{i + 1}",
+ created_by_id: admin.id,
+ )
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "edit",
+ groups: [write_group],
+ )
+ end
+ end
+
+ it "selects boards with h/l and opens with Enter" do
+ sign_in(user)
+ visit "/boards"
+
+ expect(page).to have_css(".discourse-boards-board-card", count: 3)
+
+ press_key("l")
+ expect(page).to have_css(".discourse-boards-board-card--kb-selected")
+
+ first_selected = find(".discourse-boards-board-card--kb-selected")
+ first_name = first_selected.find(".discourse-boards-board-card__name").text
+
+ press_key("l")
+ second_name =
+ find(".discourse-boards-board-card--kb-selected .discourse-boards-board-card__name").text
+
+ expect(second_name).not_to eq(first_name)
+
+ press_key("h")
+ back_name =
+ find(".discourse-boards-board-card--kb-selected .discourse-boards-board-card__name").text
+
+ expect(back_name).to eq(first_name)
+
+ press_key(:enter)
+ expect(page).to have_current_path(%r{/boards/})
+ end
+ end
+
+ context "when moving cards with Shift shortcuts" do
+ it "moves card to next column with Shift+l" do
+ board = create_board
+ col_todo = board.columns.create!(title: "To Do", position: 0)
+ col_done = board.columns.create!(title: "Done", position: 1)
+ add_floater_card(board, col_todo, "Move me")
+
+ sign_in(user)
+ board_viewer.visit_board(board)
+
+ expect(board_viewer).to have_card_in_column("To Do", "Move me")
+
+ # Select the card
+ press_key("j")
+ expect(page).to have_css(".discourse-boards-card--kb-selected")
+
+ # Move it right
+ press_key(:shift, "l")
+
+ expect(board_viewer).to have_card_in_column("Done", "Move me")
+ expect(board_viewer).to have_no_card_in_column("To Do", "Move me")
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/category_constraints_spec.rb b/plugins/boards/spec/system/category_constraints_spec.rb
new file mode 100644
index 00000000000..d361395b85b
--- /dev/null
+++ b/plugins/boards/spec/system/category_constraints_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+describe "Board Category Constraints" do
+ fab!(:current_user, :admin)
+ fab!(:board) { Fabricate(:boards_board, column_names: ["To Do", "In Progress", "Done"]) }
+
+ let(:board_viewer) { PageObjects::Pages::BoardsBoardViewer.new }
+ let(:board_component) { PageObjects::Components::BoardsBoard.new }
+ let(:board_manage_page) { PageObjects::Pages::BoardsManageBoards.new }
+ let(:dialog) { PageObjects::Components::Dialog.new }
+ let(:toasts) { PageObjects::Components::Toasts.new }
+
+ before do
+ enable_current_plugin
+ sign_in(current_user)
+ end
+
+ context "when a board has a single category constraint" do
+ fab!(:category)
+ fab!(:topic) { Fabricate(:topic_with_op, category: category) }
+ fab!(:topic_2, :topic) { Fabricate(:topic_with_op) }
+
+ before do
+ board.update!(category_ids: [category.id])
+ SearchIndexer.enable
+ SearchIndexer.index(topic, force: true)
+ SearchIndexer.index(topic_2, force: true)
+ end
+
+ after { SearchIndexer.disable }
+
+ it "allows topics in the category to be added to the board" do
+ board_viewer.visit_board(board)
+ board_viewer.click_add_topic_as_card("To Do")
+ board_viewer.fill_topic_search(topic.title)
+ board_viewer.select_topic_search_result(topic.id)
+
+ expect(board_viewer).to have_card_in_column("To Do", topic.title)
+ end
+
+ it "prompts to move the topic to the correct constraint category if it's not in the category" do
+ board_viewer.visit_board(board)
+ board_viewer.click_add_topic_as_card("To Do")
+ board_viewer.fill_topic_search(topic_2.title)
+ board_viewer.select_topic_search_result(topic_2.id)
+
+ expect(board_viewer).to have_constraint_fix_modal
+
+ board_viewer.click_constraint_fix_category(category.id)
+ board_viewer.click_constraint_fix_confirm
+
+ expect(board_viewer).to have_card_in_column("To Do", topic_2.title)
+ expect(topic_2.reload.category_id).to eq(category.id)
+ end
+
+ describe "adding a column to the board" do
+ fab!(:tag_group) { Fabricate(:tag_group, name: "Support Tags") }
+ fab!(:tag) { Fabricate(:tag, name: "support") }
+ fab!(:tag_group_membership) { TagGroupMembership.create!(tag: tag, tag_group: tag_group) }
+
+ before { category.update!(tag_groups: [tag_group]) }
+
+ it "allows tags in tag groups restricted to the category to be used for the column" do
+ board_viewer.visit_board(board)
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+ board_manage_page.select_modal_column_tag(tag.name)
+ board_manage_page.save_column_modal
+
+ expect(board_viewer).to have_column(tag.name)
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/core_features_spec.rb b/plugins/boards/spec/system/core_features_spec.rb
new file mode 100644
index 00000000000..0870cf3a9b4
--- /dev/null
+++ b/plugins/boards/spec/system/core_features_spec.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+# Parts of the core features examples can be skipped like so:
+# it_behaves_like "having working core features", skip_examples: %i[login likes]
+#
+# List of keywords for skipping examples:
+# login, likes, profile, topics, topics:read, topics:reply, topics:create,
+# search, search:quick_search, search:full_page
+#
+# For more details, see https://meta.discourse.org/t/-/361381
+describe "Core features" do
+ before { enable_current_plugin }
+
+ it_behaves_like "having working core features", skip_examples: %i[topics:read]
+end
diff --git a/plugins/boards/spec/system/manage_boards_spec.rb b/plugins/boards/spec/system/manage_boards_spec.rb
new file mode 100644
index 00000000000..b71b91103b9
--- /dev/null
+++ b/plugins/boards/spec/system/manage_boards_spec.rb
@@ -0,0 +1,339 @@
+# frozen_string_literal: true
+
+describe "Manage Boards Boards" do
+ fab!(:admin)
+ fab!(:manager, :user)
+ fab!(:regular_user, :user)
+ fab!(:manage_group, :group)
+ fab!(:todo_tag, :tag) { Fabricate(:tag, name: "todo") }
+
+ let(:boards_page) { PageObjects::Pages::BoardsManageBoards.new }
+ let(:dialog) { PageObjects::Components::Dialog.new }
+ let(:permanently_delete_confirm) { PageObjects::Modals::PermanentlyDeleteConfirm.new }
+ let(:access_control) { PageObjects::Components::DAccessControl.new }
+ let(:toasts) { PageObjects::Components::Toasts.new }
+
+ before do
+ enable_current_plugin
+ SiteSetting.boards_manage_board_allowed_groups = manage_group.id.to_s
+ manage_group.add(manager)
+ manage_group.add(admin)
+ end
+
+ context "when user is in the manage group" do
+ before { sign_in(manager) }
+
+ it "warns the user when they create a board they will not be able to manage" do
+ boards_page.visit_page
+ boards_page.click_new_board
+ boards_page.fill_modal_board_name("Self-lockout Board")
+ access_control.remove_permission_row(type: "group", id: manage_group.id)
+ boards_page.save_board_modal
+
+ expect(access_control).to have_loss_warning(
+ I18n.t("access_control_list.errors.Boards::Board_user_will_lose_permission_on_create"),
+ )
+
+ access_control.confirm_loss_warning
+
+ expect(boards_page.board_settings_modal).to be_closed
+ expect(PageObjects::Components::BoardsBoard.new).to have_name("Self-lockout Board")
+ end
+
+ it "supports the full board lifecycle" do
+ boards_page.visit_page
+ expect(boards_page).to have_empty_state
+
+ boards_page.click_new_board
+ boards_page.fill_modal_board_name("Sprint Board")
+ boards_page.toggle_modal_advanced_settings
+ boards_page.board_settings_form.field("require_confirmation").toggle
+ boards_page.save_board_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ board = Boards::Board.last
+ expect(board.name).to eq("Sprint Board")
+ expect(board.require_confirmation).to eq(true)
+ expect(board.permission_acl.permission_group_ids("manage")).to contain_exactly(
+ Group::AUTO_GROUPS[:admins],
+ manage_group.id,
+ )
+
+ boards_page.visit_page
+ expect(boards_page).to have_board_listed("Sprint Board")
+
+ boards_page.click_board("Sprint Board")
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_board_settings_menu_item
+ boards_page.fill_modal_board_name("Updated Board")
+ boards_page.save_board_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+ expect(board.reload.name).to eq("Updated Board")
+
+ boards_page.visit_page
+ expect(boards_page).to have_board_listed("Updated Board")
+
+ boards_page.click_board("Updated Board")
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_board_settings_menu_item
+ boards_page.delete_from_board_modal
+ dialog.click_yes
+
+ expect(boards_page).to have_empty_state
+ expect(Boards::Board.count).to eq(0)
+
+ boards_page.visit_page
+ boards_page.click_new_board
+ boards_page.save_board_modal
+ expect(boards_page.board_settings_form.field("name")).to have_errors("Required")
+ end
+
+ it "can add columns to a board" do
+ boards_page.visit_page
+ boards_page.click_new_board
+ boards_page.fill_modal_board_name("Workflow Board")
+ boards_page.save_board_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+ boards_page.fill_modal_column_title("To Do")
+ boards_page.fill_modal_column_color("C97CF4")
+ boards_page.save_column_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+ boards_page.fill_modal_column_title("Done")
+ boards_page.save_column_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ board = Boards::Board.last
+ expect(board.name).to eq("Workflow Board")
+ expect(board.columns.order(:position).pluck(:title)).to eq(["To Do", "Done"])
+
+ expect(boards_page).to have_column("To Do")
+ expect(boards_page).to have_column("Done")
+ expect(boards_page.column_by_title("To Do")).to have_color("C97CF4")
+ end
+
+ it "can delete a column with no cards without confirmation" do
+ board = Fabricate(:boards_board, additional_manage_groups: [manage_group])
+ column = Fabricate(:boards_column, board: board)
+ boards_page.visit_page
+ boards_page.click_board(board.name)
+ column_component = boards_page.column_by_title(column.title)
+ column_component.open_menu
+ column_component.click_delete
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+ end
+
+ it "requires confirmation when deleting a column with cards" do
+ board = Fabricate(:boards_board, additional_manage_groups: [manage_group])
+ column = Fabricate(:boards_column, board: board)
+ Fabricate(:boards_card, board: board, column: column)
+ boards_page.visit_page
+ boards_page.click_board(board.name)
+ column_component = boards_page.column_by_title(column.title)
+ column_component.open_menu
+ column_component.click_delete
+ dialog.click_yes
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+ end
+
+ it "requires entering the column name as delete confirmation when deleting a column with more than 5 cards" do
+ board = Fabricate(:boards_board, additional_manage_groups: [manage_group])
+ column = Fabricate(:boards_column, board: board)
+ 6.times { Fabricate(:boards_card, board: board, column: column) }
+ boards_page.visit_page
+ boards_page.click_board(board.name)
+ column_component = boards_page.column_by_title(column.title)
+ column_component.open_menu
+ column_component.click_delete
+ permanently_delete_confirm.fill_in_confirmation_phrase(column.title)
+ permanently_delete_confirm.click_danger
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+ end
+
+ it "persists board tag filter when creating a board with a tag" do
+ Fabricate(:tag, name: "a11y")
+
+ boards_page.visit_page
+ boards_page.click_new_board
+ boards_page.fill_modal_board_name("Accessibility Board")
+ boards_page.board_settings_form.field("constraint_type").select("tags")
+ boards_page.select_modal_board_tag("a11y")
+ boards_page.save_board_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ board = Boards::Board.find_by(name: "Accessibility Board")
+ expect(board).to be_present
+ expect(board.tag_ids).to contain_exactly(Tag.find_by(name: "a11y").id)
+ end
+
+ describe "for an existing board" do
+ let(:trust_level_4_group) { Group.find(Group::AUTO_GROUPS[:trust_level_4]) }
+
+ fab!(:board) do
+ Fabricate(
+ :boards_board,
+ name: "Simple Board",
+ created_by: admin,
+ additional_manage_groups: [manage_group],
+ )
+ end
+
+ it "creates a column with a tag" do
+ boards_page.visit_page
+ boards_page.click_board("Simple Board")
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+
+ boards_page.fill_modal_column_title("Todo")
+ boards_page.select_modal_column_tag(todo_tag.name)
+ boards_page.save_column_modal
+
+ column = board.reload.columns.find_by(title: "Todo")
+ expect(column.tag_id).to eq(todo_tag.id)
+ end
+
+ it "can create a column using only the tag as the title" do
+ boards_page.visit_page
+ boards_page.click_board("Simple Board")
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+ boards_page.select_modal_column_tag(todo_tag.name)
+ boards_page.save_column_modal
+ end
+
+ it "does not allow creating a column for the same tag twice" do
+ boards_page.visit_page
+ boards_page.click_board("Simple Board")
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+ boards_page.select_modal_column_tag(todo_tag.name)
+ boards_page.save_column_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+ boards_page.select_modal_column_tag(todo_tag.name)
+ boards_page.save_column_modal
+ expect(page).to have_content(
+ I18n.t("boards.errors.cannot_use_same_tag_multiple_times", tag_name: todo_tag.name),
+ )
+ end
+
+ it "warns the user when they are removing Manage permissions from themselves" do
+ visit board.url
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_board_settings_menu_item
+ access_control.remove_permission_row(type: "group", id: manage_group.id)
+ boards_page.save_board_modal
+ expect(access_control).to have_loss_warning(
+ I18n.t("access_control_list.errors.Boards::Board_user_will_lose_permission"),
+ )
+ access_control.confirm_loss_warning
+ expect(boards_page.board_settings_modal).to be_closed
+ expect(page).to have_content(I18n.t("js.errors.reasons.forbidden"))
+ end
+
+ it "lets the user add a group with Manage permission from board settings on mobile",
+ mobile: true do
+ visit board.url
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_board_settings_menu_item
+
+ access_control.add_group(trust_level_4_group)
+ access_control.row(type: "group", id: trust_level_4_group.id).select_permission("manage")
+ boards_page.save_board_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+ end
+ end
+ end
+
+ context "when user is a regular user not in the manage group" do
+ fab!(:read_group, :group)
+ fab!(:board) do
+ board = Fabricate(:boards_board, name: "Visible Board", created_by: admin)
+ Fabricate(
+ :access_control_list_with_groups,
+ target: board,
+ permission: "view",
+ groups: [read_group],
+ )
+ board
+ end
+ fab!(:column) { Fabricate(:boards_column, board: board) }
+
+ before do
+ read_group.add(regular_user)
+ sign_in(regular_user)
+ end
+
+ it "can see the boards list but not management controls" do
+ boards_page.visit_page
+
+ expect(boards_page).to have_board_listed("Visible Board")
+ expect(boards_page).to have_no_new_board_button
+ end
+ end
+
+ context "when user is an admin" do
+ before { sign_in(admin) }
+
+ it "can manage boards regardless of group membership" do
+ boards_page.visit_page
+ expect(boards_page).to have_new_board_button
+ boards_page.click_new_board
+ boards_page.fill_modal_board_name("Admin Board")
+ boards_page.save_board_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+ expect(Boards::Board.find_by(name: "Admin Board")).to be_present
+ end
+
+ it "creates a column and a new tag when typing a non-existent tag" do
+ board = Fabricate(:boards_board, name: "New Tag Board", created_by: admin)
+
+ boards_page.visit_page
+ boards_page.click_board("New Tag Board")
+ board_component = PageObjects::Components::BoardsBoard.new
+ board_component.open_board_menu
+ board_component.click_add_column_menu_item
+
+ boards_page.fill_modal_column_title("Backlog")
+ boards_page.select_modal_column_tag("brand-new")
+ boards_page.save_column_modal
+
+ expect(toasts).to have_success(I18n.t("js.saved"))
+
+ new_tag = Tag.find_by(name: "brand-new")
+ expect(new_tag).to be_present
+
+ column = board.reload.columns.find_by(title: "Backlog")
+ expect(column.tag_id).to eq(new_tag.id)
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/page_objects/components/boards_add_from_topic.rb b/plugins/boards/spec/system/page_objects/components/boards_add_from_topic.rb
new file mode 100644
index 00000000000..51d99bb2d88
--- /dev/null
+++ b/plugins/boards/spec/system/page_objects/components/boards_add_from_topic.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class BoardsAddFromTopic < PageObjects::Components::Base
+ ADD_TO_BOARD_BUTTON = "#topic-footer-button-boards-add-from-topic"
+ MEMBERSHIP_PILL = "#topic-title .discourse-boards-topic-pill"
+
+ def add_to_column(board, column)
+ select_column(board, column)
+ end
+
+ def remove_from_column(board, column)
+ select_column(board, column)
+ end
+
+ def select_column(board, column)
+ find(ADD_TO_BOARD_BUTTON).click
+ within(".discourse-boards-add-from-topic-menu") do
+ find("button", exact_text: board.unicode_name).click
+ end
+ within(".discourse-boards-add-from-topic-column-menu") do
+ find("button", exact_text: column.unicode_title).click
+ end
+ self
+ end
+
+ def has_no_add_to_board_button?
+ has_no_css?(ADD_TO_BOARD_BUTTON)
+ end
+
+ def has_membership?(board, column)
+ has_css?(MEMBERSHIP_PILL, exact_text: board.unicode_name) do |pill|
+ pill["title"] ==
+ I18n.t(
+ "js.boards.topic_pill.title",
+ board: board.unicode_name,
+ column: column.unicode_title,
+ )
+ end
+ end
+
+ def has_membership_count?(count)
+ has_css?(
+ "#{MEMBERSHIP_PILL}.discourse-boards-topic-pill--multiple",
+ exact_text: I18n.t("js.boards.topic_pill.multiple", count:),
+ )
+ end
+
+ def open_memberships
+ find("#{MEMBERSHIP_PILL}.discourse-boards-topic-pill--multiple").click
+ self
+ end
+
+ def has_membership_in_menu?(board, column)
+ within("[data-content][data-identifier='discourse-boards-topic-pill']") do
+ find(".discourse-boards-boards-menu__item", text: board.unicode_name).has_css?(
+ ".discourse-boards-boards-menu__column",
+ text: /#{Regexp.escape(column.unicode_title)}/i,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/page_objects/components/boards_board.rb b/plugins/boards/spec/system/page_objects/components/boards_board.rb
new file mode 100644
index 00000000000..79021d4ee1e
--- /dev/null
+++ b/plugins/boards/spec/system/page_objects/components/boards_board.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class BoardsBoard < PageObjects::Components::Base
+ def has_name?(name)
+ has_css?(".discourse-boards-board-viewer__title", text: name)
+ end
+
+ def board_menu
+ PageObjects::Components::DMenu.new(
+ find(
+ ".discourse-boards-board-viewer__controls [data-identifier='boards-board-controls']",
+ ),
+ )
+ end
+
+ def open_board_menu
+ board_menu.expand
+ self
+ end
+
+ def click_board_settings_menu_item
+ board_menu.option("[data-identifier='board-settings']").click
+ self
+ end
+
+ def click_add_column_menu_item
+ board_menu.option("[data-identifier='add-column']").click
+ self
+ end
+
+ def click_delete_board_menu_item
+ board_menu.option("[data-identifier='delete-board']").click
+ self
+ end
+
+ def has_no_menu_item?(identifier)
+ board_menu.has_no_option?("[data-identifier='#{identifier}']")
+ self
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/page_objects/components/boards_column.rb b/plugins/boards/spec/system/page_objects/components/boards_column.rb
new file mode 100644
index 00000000000..fb2bf290ac6
--- /dev/null
+++ b/plugins/boards/spec/system/page_objects/components/boards_column.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class BoardsColumn < PageObjects::Components::Base
+ def initialize(title: nil, id: nil)
+ @title = title
+ @id = id
+
+ if @title.blank? && @id.blank?
+ raise "Column must be initialized with either a title or an id"
+ end
+ end
+
+ def find_by_title(title)
+ find(".discourse-boards-column__title", text: /#{Regexp.escape(title)}/i).ancestor(
+ ".discourse-boards-column",
+ )
+ end
+
+ def find_by_id(id)
+ find(".discourse-boards-column[data-column-id='#{id}']")
+ end
+
+ def find_column
+ if @title
+ find_by_title(@title)
+ elsif @id
+ find_by_id(@id)
+ end
+ end
+
+ def exists?
+ find_column
+ true
+ end
+
+ def menu
+ PageObjects::Components::DMenu.new(
+ find_column.find(".discourse-boards-column__menu-trigger", visible: :all),
+ )
+ end
+
+ def open_menu
+ menu.expand
+ self
+ end
+
+ def click_delete
+ menu.option(".discourse-boards-column__menu-delete").click
+ end
+
+ def has_color?(color)
+ color = color.delete_prefix("#")
+ find_column["style"].include?("--discourse-boards-column-color: ##{color};")
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/page_objects/pages/boards_board_viewer.rb b/plugins/boards/spec/system/page_objects/pages/boards_board_viewer.rb
new file mode 100644
index 00000000000..5c8aab7404d
--- /dev/null
+++ b/plugins/boards/spec/system/page_objects/pages/boards_board_viewer.rb
@@ -0,0 +1,374 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class BoardsBoardViewer < PageObjects::Pages::Base
+ def visit_board(board)
+ page.visit "/boards/#{board.slug}/#{board.id}"
+ self
+ end
+
+ def visit_board_with_slug(slug, board)
+ page.visit "/boards/#{slug}/#{board.id}"
+ self
+ end
+
+ def has_column?(title)
+ has_css?(".discourse-boards-column__title", text: /#{Regexp.escape(title)}/i)
+ end
+
+ def has_no_column?(title)
+ has_no_css?(".discourse-boards-column__title", text: /#{Regexp.escape(title)}/i)
+ end
+
+ def has_card_in_column?(column_title, card_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ has_css?(".discourse-boards-card__title", text: card_title)
+ end
+ end
+
+ def has_no_card_in_column?(column_title, card_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ has_no_css?(".discourse-boards-card__title", text: card_title)
+ end
+ end
+
+ def card_count_in_column(column_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ all(".discourse-boards-card").count
+ end
+ end
+
+ def drag_card_to_column(card_title, target_column_title)
+ find(".discourse-boards-card", text: card_title).drag_to(
+ find(".discourse-boards-column", text: /#{Regexp.escape(target_column_title)}/i),
+ html5: true,
+ delay: 0.4,
+ )
+ self
+ end
+
+ def has_board_title?(title)
+ has_css?(".discourse-boards-board-viewer__title", text: title)
+ end
+
+ def card_draggable?(card_title)
+ find(".discourse-boards-card", text: card_title)["draggable"] == "true"
+ end
+
+ def has_tag_on_card?(card_title, tag_name)
+ within(find(".discourse-boards-card", text: card_title)) do
+ has_css?(".discourse-tag", text: tag_name)
+ end
+ end
+
+ def has_no_tag_on_card?(card_title, tag_name)
+ within(find(".discourse-boards-card", text: card_title)) do
+ has_no_css?(".discourse-tag", text: tag_name)
+ end
+ end
+
+ def has_category_on_card?(card_title)
+ within(find(".discourse-boards-card", text: card_title)) do
+ has_css?(".discourse-boards-card__category")
+ end
+ end
+
+ def has_activity_indicator?(card_title, type)
+ has_css?(".discourse-boards-card.#{type}", text: card_title)
+ end
+
+ def has_add_card_button_in_column?(column_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ has_css?(".discourse-boards-column__add-btn")
+ end
+ end
+
+ def has_no_add_card_button_in_column?(column_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ has_no_css?(".discourse-boards-column__add-btn")
+ end
+ end
+
+ def click_add_card(column_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ find(".discourse-boards-column__add-btn").click
+ end
+ find(
+ "[data-content][data-identifier='boards-column-add'] .btn-transparent",
+ text: I18n.t("js.boards.board.add_card"),
+ ).click
+ has_css?(".discourse-boards-card-detail-modal")
+ self
+ end
+
+ def click_add_topic_as_card(column_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ find(".discourse-boards-column__add-btn").click
+ end
+ find(
+ "[data-content][data-identifier='boards-column-add'] .btn-transparent",
+ text: I18n.t("js.boards.board.add_topic_as_card"),
+ ).click
+ has_css?(".discourse-boards-add-topic-as-card-modal")
+ self
+ end
+
+ def fill_topic_search(value)
+ within(".discourse-boards-add-topic-as-card-modal") do
+ find("input.topic-search-input").fill_in(with: value)
+ end
+ self
+ end
+
+ def select_topic_search_result(topic_id)
+ find(".internal-link-results a[data-topic-id='#{topic_id}']").click
+ self
+ end
+
+ def submit_topic_search
+ within(".discourse-boards-add-topic-as-card-modal") do
+ find(".d-modal__footer .btn-primary").click
+ end
+ self
+ end
+
+ def submit_topic_search_with_enter
+ within(".discourse-boards-add-topic-as-card-modal") do
+ find("input.topic-search-input").send_keys(:enter)
+ end
+ self
+ end
+
+ def has_no_add_topic_as_card_modal?
+ has_no_css?(".discourse-boards-add-topic-as-card-modal")
+ end
+
+ def fill_card_title(title)
+ fill_card_detail_title(title)
+ end
+
+ def submit_card
+ save_card_detail
+ end
+
+ def has_floater_card_in_column?(column_title, card_title)
+ within(find(".discourse-boards-column", text: /#{Regexp.escape(column_title)}/i)) do
+ has_css?(".discourse-boards-card--floater", text: card_title)
+ end
+ end
+
+ def open_card_actions(card_title)
+ within(find(".discourse-boards-card", text: card_title)) do
+ find(".discourse-boards-card__actions-trigger", visible: :all).click
+ end
+ self
+ end
+
+ def has_edit_card_action?
+ has_css?(
+ "[data-content][data-identifier='boards-card-actions'] .btn-transparent .d-button-label",
+ text: I18n.t("js.edit"),
+ )
+ end
+
+ def click_edit_card
+ find(
+ "[data-content][data-identifier='boards-card-actions'] .btn-transparent",
+ text: I18n.t("js.edit"),
+ ).click
+ self
+ end
+
+ def has_card_detail_modal?
+ has_css?(".discourse-boards-card-detail-modal")
+ end
+
+ def fill_card_detail_title(new_title)
+ within(".discourse-boards-card-detail-modal") do
+ if has_css?(".discourse-boards-editable-title__input", wait: 0)
+ find(".discourse-boards-editable-title__input").set(new_title)
+ else
+ find(".discourse-boards-editable-title__text").click
+ find(".discourse-boards-editable-title__input").set(new_title)
+ end
+ end
+ self
+ end
+
+ def select_card_detail_tag(tag_name)
+ tag_chooser =
+ PageObjects::Components::SelectKit.new(".discourse-boards-card-detail-modal .tag-chooser")
+ tag_chooser.expand
+ tag_chooser.search(tag_name)
+ tag_chooser.select_row_by_name(tag_name)
+ tag_chooser.collapse
+ self
+ end
+
+ def create_card_detail_tag(tag_name)
+ tag_chooser =
+ PageObjects::Components::SelectKit.new(".discourse-boards-card-detail-modal .tag-chooser")
+ tag_chooser.expand
+ tag_chooser.search(tag_name)
+ tag_chooser.select_row_by_value(tag_name)
+ tag_chooser.collapse
+ self
+ end
+
+ def has_card_detail_tag?(tag_name)
+ tag_chooser =
+ PageObjects::Components::SelectKit.new(".discourse-boards-card-detail-modal .tag-chooser")
+ tag_chooser.has_selected_name?(tag_name)
+ end
+
+ def save_card_detail
+ within(".discourse-boards-card-detail-modal") do
+ find(".form-kit__actions button[type='submit']").click
+ end
+ self
+ end
+
+ def cancel_card_detail
+ within(".discourse-boards-card-detail-modal") do
+ find(".d-modal-cancel", text: I18n.t("js.cancel")).click
+ end
+ self
+ end
+
+ def has_fullscreen?
+ has_css?(".discourse-boards-board-viewer.discourse-boards-board-viewer--fullscreen")
+ end
+
+ def has_no_fullscreen?
+ has_no_css?(".discourse-boards-board-viewer.discourse-boards-board-viewer--fullscreen")
+ end
+
+ def open_controls_menu
+ find(
+ ".discourse-boards-board-viewer__controls [data-identifier='boards-board-controls']",
+ ).click
+ self
+ end
+
+ def has_no_controls_menu?
+ has_no_css?(
+ ".discourse-boards-board-viewer__controls [data-identifier='boards-board-controls']",
+ )
+ end
+
+ def click_fullscreen
+ find(
+ ".discourse-boards-board-viewer__controls .btn-flat[title='#{I18n.t("js.boards.board.fullscreen")}']",
+ ).click
+ self
+ end
+
+ def click_exit_fullscreen
+ find(".discourse-boards-board-viewer__exit-fullscreen").click
+ self
+ end
+
+ def has_board_settings_option?
+ has_css?(
+ "[data-content][data-identifier='boards-board-controls'] .btn-transparent .d-button-label",
+ text: I18n.t("js.boards.board.board_settings"),
+ )
+ end
+
+ def has_no_board_settings_option?
+ has_no_css?(
+ "[data-content][data-identifier='boards-board-controls'] .btn-transparent .d-button-label",
+ text: I18n.t("js.boards.board.board_settings"),
+ )
+ end
+
+ def visit_card(board, card)
+ page.visit "/boards/#{board.slug}/#{board.id}/cards/#{card.id}"
+ self
+ end
+
+ def has_no_card_detail_modal?
+ has_no_css?(".discourse-boards-card-detail-modal")
+ end
+
+ def click_floater_card(card_title)
+ find(".discourse-boards-card--floater", text: card_title).click
+ self
+ end
+
+ def has_card_tag?(card_title, tag_name)
+ within(find(".discourse-boards-card--floater", text: card_title)) do
+ has_css?(".discourse-tag", text: tag_name)
+ end
+ end
+
+ def has_card_notes_indicator?(card_title)
+ within(find(".discourse-boards-card--floater", text: card_title)) do
+ has_css?(".discourse-boards-card__notes-indicator")
+ end
+ end
+
+ def click_topic_card(card_title)
+ find(".discourse-boards-card:not(.discourse-boards-card--floater)", text: card_title).click
+ self
+ end
+
+ def has_topic_card_detail_modal?
+ has_css?(".discourse-boards-topic-card-detail-modal")
+ end
+
+ def has_no_topic_card_detail_modal?
+ has_no_css?(".discourse-boards-topic-card-detail-modal")
+ end
+
+ def has_topic_card_detail_cooked?
+ within(".discourse-boards-topic-card-detail-modal") do
+ has_css?(".discourse-boards-topic-card-detail__cooked")
+ end
+ end
+
+ def has_topic_card_detail_category?
+ within(".discourse-boards-topic-card-detail-modal") { has_css?(".badge-category__wrapper") }
+ end
+
+ def has_topic_card_detail_tags?
+ within(".discourse-boards-topic-card-detail-modal") do
+ has_css?(".discourse-boards-topic-card-detail__tags")
+ end
+ end
+
+ def has_topic_card_detail_reply_count?
+ within(".discourse-boards-topic-card-detail-modal") do
+ has_css?(".discourse-boards-topic-card-detail__stats")
+ end
+ end
+
+ def click_topic_card_view_topic
+ within(".discourse-boards-topic-card-detail-modal") { find(".btn-primary").click }
+ self
+ end
+
+ def has_constraint_fix_modal?
+ has_css?(".discourse-boards-constraint-fix-modal")
+ end
+
+ def click_constraint_fix_category(category_id)
+ find(".discourse-boards-constraint-fix-modal [data-category-id='#{category_id}']").click
+ self
+ end
+
+ def click_constraint_fix_tag(tag_name)
+ find(".discourse-boards-constraint-fix-modal [data-tag-name='#{tag_name}']").click
+ self
+ end
+
+ def click_constraint_fix_confirm
+ PageObjects::Modals::Base.new(
+ body_selector: ".discourse-boards-constraint-fix-modal",
+ ).click_primary_button
+ self
+ end
+ end
+ end
+end
diff --git a/plugins/boards/spec/system/page_objects/pages/boards_manage_boards.rb b/plugins/boards/spec/system/page_objects/pages/boards_manage_boards.rb
new file mode 100644
index 00000000000..f75e7299f60
--- /dev/null
+++ b/plugins/boards/spec/system/page_objects/pages/boards_manage_boards.rb
@@ -0,0 +1,150 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class BoardsManageBoards < PageObjects::Pages::Base
+ def visit_page
+ page.visit "/boards"
+ self
+ end
+
+ def board_settings_form
+ PageObjects::Components::FormKit.new("#{board_settings_modal.full_body_selector} .form-kit")
+ end
+
+ def column_settings_form
+ PageObjects::Components::FormKit.new(
+ "#{column_settings_modal.full_body_selector} .form-kit",
+ )
+ end
+
+ def click_new_board
+ find(".discourse-boards-manage__new-board").click
+ self
+ end
+
+ def has_board_listed?(name)
+ has_css?(".discourse-boards-board-card", text: name)
+ end
+
+ def has_no_board_listed?(name)
+ has_no_css?(".discourse-boards-board-card", text: name)
+ end
+
+ def has_empty_state?
+ has_css?(".discourse-boards-boards-empty")
+ end
+
+ def has_new_board_button?
+ has_css?(".discourse-boards-manage__new-board")
+ end
+
+ def has_no_new_board_button?
+ has_no_css?(".discourse-boards-manage__new-board")
+ end
+
+ def click_board(board_name)
+ find(".discourse-boards-board-card__name", text: board_name).click
+ self
+ end
+
+ # Board settings modal interactions
+
+ def board_settings_modal
+ PageObjects::Modals::Base.new(modal_selector: ".discourse-boards-board-settings-modal")
+ end
+
+ def fill_modal_board_name(name)
+ modal = board_settings_modal
+ modal
+ .body
+ .find(".discourse-boards-editable-title__input, .discourse-boards-editable-title__text")
+ .click
+ modal.body.find(".discourse-boards-editable-title__input").fill_in(with: name)
+ self
+ end
+
+ def toggle_modal_advanced_settings
+ modal = board_settings_modal
+ modal.body.find(".show-advanced").click
+ self
+ end
+
+ def select_modal_board_tag(tag_name)
+ modal = board_settings_modal
+ chooser =
+ PageObjects::Components::SelectKit.new(
+ "#{modal.full_body_selector} [data-name='tag_names'] .form-kit__control-tag-chooser",
+ )
+ chooser.expand
+ chooser.search(tag_name)
+ chooser.select_row_by_name(tag_name)
+ self
+ end
+
+ def save_board_modal
+ modal = board_settings_modal
+ modal.body.find(".discourse-boards-board-settings-modal__save-board").click
+ self
+ end
+
+ def delete_from_board_modal
+ modal = board_settings_modal
+ modal.body.find(".discourse-boards-board-settings-modal__delete-board").click
+ self
+ end
+
+ # Column settings modal interactions
+
+ def column_settings_modal
+ PageObjects::Modals::Base.new(modal_selector: ".discourse-boards-column-settings-modal")
+ end
+
+ def fill_modal_column_title(title)
+ modal = column_settings_modal
+ if modal.body.has_css?(".discourse-boards-editable-title__input", wait: 0)
+ modal.body.find(".discourse-boards-editable-title__input").fill_in(with: title)
+ else
+ modal.body.find(".discourse-boards-editable-title__text").click
+ modal.body.find(".discourse-boards-editable-title__input").fill_in(with: title)
+ end
+ self
+ end
+
+ def select_modal_column_tag(tag_name)
+ modal = column_settings_modal
+ chooser =
+ PageObjects::Components::SelectKit.new("#{modal.full_body_selector} .mini-tag-chooser")
+ chooser.expand
+ chooser.search(tag_name)
+ chooser.select_row_by_name(tag_name)
+ self
+ end
+
+ def fill_modal_column_color(color)
+ column_settings_form.field("color").fill_in(color)
+ end
+
+ def column_by_title(title)
+ PageObjects::Components::BoardsColumn.new(title: title)
+ end
+
+ def open_column_menu(column_title)
+ column = column_by_title(column_title)
+ column.open_menu
+ column
+ end
+
+ def save_column_modal
+ modal = column_settings_modal
+ modal.body.find(".discourse-boards-column-settings-modal__save").click
+ self
+ end
+
+ def has_column?(title)
+ column = column_by_title(title)
+ column.exists?
+ end
+ end
+ end
+end
diff --git a/plugins/boards/svg-icons/plugin-icons.svg b/plugins/boards/svg-icons/plugin-icons.svg
new file mode 100644
index 00000000000..496d0aa565f
--- /dev/null
+++ b/plugins/boards/svg-icons/plugin-icons.svg
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
+ <symbol id="boards" viewBox="0 0 512 512">
+ <path fill="currentColor" fill-rule="evenodd" d="M149 64C94 64 64 94 64 149v214c0 55 30 85 85 85h214c55 0 85-30 85-85V149c0-55-30-85-85-85H149Zm0 43c-28 0-42 14-42 42v214c0 28 14 42 42 42h214c28 0 42-14 42-42V149c0-28-14-42-42-42H149Z" clip-rule="evenodd"/>
+ <rect width="43" height="171" x="149" y="128" fill="currentColor" rx="21.5"/>
+ <rect width="43" height="107" x="234.5" y="128" fill="currentColor" rx="21.5"/>
+ <rect width="43" height="256" x="320" y="128" fill="currentColor" rx="21.5"/>
+ </symbol>
+</svg>
diff --git a/plugins/boards/test/javascripts/acceptance/boards-add-from-topic-button-test.js b/plugins/boards/test/javascripts/acceptance/boards-add-from-topic-button-test.js
new file mode 100644
index 00000000000..5a180332f14
--- /dev/null
+++ b/plugins/boards/test/javascripts/acceptance/boards-add-from-topic-button-test.js
@@ -0,0 +1,49 @@
+import { click, triggerEvent, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Boards add topic footer button", function (needs) {
+ needs.user({ can_edit_any_boards: true });
+
+ test("renders with the core topic footer buttons and opens its menu", async function (assert) {
+ pretender.get("/boards/api/boards/available", () =>
+ response({
+ boards: [
+ {
+ id: 1,
+ name: "Roadmap",
+ columns: [
+ { id: 11, title: "Next", cards: [] },
+ { id: 12, title: "Done", cards: [] },
+ ],
+ },
+ ],
+ })
+ );
+
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom(
+ ".topic-footer-main-buttons__actions #topic-footer-button-boards-add-from-topic"
+ )
+ .exists();
+ assert
+ .dom("#topic-footer-button-boards-add-from-topic .d-icon-boards")
+ .exists();
+
+ await click("#topic-footer-button-boards-add-from-topic");
+
+ assert.dom(".discourse-boards-add-from-topic-menu").exists();
+
+ await triggerEvent(
+ ".discourse-boards-add-from-topic-menu__board-item",
+ "mouseenter"
+ );
+
+ assert
+ .dom(".discourse-boards-add-from-topic-column-menu__column")
+ .exists({ count: 2 });
+ });
+});
diff --git a/plugins/boards/test/javascripts/acceptance/boards-keyboard-shortcuts-help-test.js b/plugins/boards/test/javascripts/acceptance/boards-keyboard-shortcuts-help-test.js
new file mode 100644
index 00000000000..9fe270c8b25
--- /dev/null
+++ b/plugins/boards/test/javascripts/acceptance/boards-keyboard-shortcuts-help-test.js
@@ -0,0 +1,29 @@
+import { triggerKeyEvent, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Boards keyboard shortcuts help", function (needs) {
+ needs.user();
+ needs.settings({ boards_enabled: true });
+
+ test("lists the current boards shortcuts", async function (assert) {
+ await visit("/");
+ await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
+
+ assert.dom(".shortcut-category-boards h2").hasText("Boards");
+ assert.dom(".shortcut-category-boards tbody tr").exists({ count: 4 });
+
+ assert
+ .dom(".shortcut-category-boards tbody")
+ .includesText("Navigate boards / columns");
+ assert
+ .dom(".shortcut-category-boards tbody")
+ .includesText("Navigate between cards");
+ assert
+ .dom(".shortcut-category-boards tbody")
+ .includesText("Move selected card to an adjacent column");
+ assert
+ .dom(".shortcut-category-boards tbody")
+ .includesText("Reorder selected card within a manually sorted column");
+ });
+});
diff --git a/plugins/boards/test/javascripts/components/boards-add-from-topic-menu-test.gjs b/plugins/boards/test/javascripts/components/boards-add-from-topic-menu-test.gjs
new file mode 100644
index 00000000000..d4ba01cb94d
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-add-from-topic-menu-test.gjs
@@ -0,0 +1,241 @@
+import {
+ click,
+ findAll,
+ render,
+ settled,
+ waitUntil,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import BoardsAddFromTopicColumnSubmenu from "discourse/plugins/boards/discourse/components/boards-add-from-topic-column-submenu";
+import BoardsAddFromTopicMenu from "discourse/plugins/boards/discourse/components/boards-add-from-topic-menu";
+import Board from "discourse/plugins/boards/discourse/models/board";
+
+function board(id, name, columns, topicIsMember = false) {
+ return {
+ id,
+ name,
+ unicode_name: name,
+ topic_is_member: topicIsMember,
+ columns: columns.map(
+ ({ id: columnId, title, icon, color, topic_is_member }) => ({
+ id: columnId,
+ title,
+ unicode_title: title,
+ icon,
+ color,
+ topic_is_member,
+ cards: [],
+ })
+ ),
+ };
+}
+
+module("Integration | Component | BoardsAddFromTopicMenu", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("shows skeleton rows while boards load", async function (assert) {
+ let resolveBoards;
+ const boardsResponse = new Promise((resolve) => {
+ resolveBoards = resolve;
+ });
+
+ pretender.get("/boards/api/boards/available", async () => {
+ await boardsResponse;
+ return response({
+ boards: [board(1, "Roadmap", [{ id: 11, title: "Next" }])],
+ });
+ });
+
+ this.set("data", { topic: { id: 1 } });
+
+ const renderPromise = render(
+ <template><BoardsAddFromTopicMenu @data={{this.data}} /></template>
+ );
+ await waitUntil(() =>
+ document.querySelector(".discourse-boards-add-from-topic-menu__skeleton")
+ );
+
+ assert
+ .dom(".discourse-boards-add-from-topic-menu__skeleton")
+ .exists({ count: 3 });
+ assert.dom(".discourse-boards-add-from-topic-menu__board").doesNotExist();
+
+ resolveBoards();
+ await renderPromise;
+ await settled();
+
+ assert
+ .dom(".discourse-boards-add-from-topic-menu__skeleton")
+ .doesNotExist();
+ assert
+ .dom(".discourse-boards-add-from-topic-menu__board")
+ .hasText("Roadmap");
+ });
+
+ test("only lists boards that have columns", async function (assert) {
+ pretender.get("/boards/api/boards/available", () =>
+ response({
+ boards: [
+ board(1, "Roadmap", [{ id: 11, title: "Next" }]),
+ board(2, "Empty board", []),
+ ],
+ })
+ );
+
+ this.set("data", { topic: { id: 1 } });
+
+ await render(
+ <template><BoardsAddFromTopicMenu @data={{this.data}} /></template>
+ );
+
+ assert
+ .dom(".discourse-boards-add-from-topic-menu__board")
+ .hasText("Roadmap");
+ assert
+ .dom(".discourse-boards-add-from-topic-menu__board")
+ .exists({ count: 1 });
+ assert
+ .dom(".discourse-boards-add-from-topic-menu__board")
+ .doesNotContainText("Empty board");
+ assert.deepEqual(
+ findAll(".dropdown-menu__subheader").map((element) =>
+ element.textContent.trim()
+ ),
+ ["Add to board"],
+ "does not render an empty Already added section"
+ );
+ });
+
+ test("groups boards by topic membership", async function (assert) {
+ pretender.get("/boards/api/boards/available", () =>
+ response({
+ boards: [
+ board(1, "Already on", [{ id: 11, title: "Doing" }], true),
+ board(2, "Available", [{ id: 21, title: "Next" }]),
+ ],
+ })
+ );
+
+ this.set("data", { topic: { id: 1 } });
+
+ await render(
+ <template><BoardsAddFromTopicMenu @data={{this.data}} /></template>
+ );
+
+ assert.deepEqual(
+ findAll(".dropdown-menu__subheader").map((element) =>
+ element.textContent.trim()
+ ),
+ ["Add to board", "Already added"]
+ );
+ assert.deepEqual(
+ findAll(".discourse-boards-add-from-topic-menu__board").map((element) =>
+ element.textContent.trim()
+ ),
+ ["Available", "Already on"]
+ );
+ assert
+ .dom(".discourse-boards-add-from-topic-menu .d-icon-circle")
+ .doesNotExist();
+ });
+
+ test("groups columns by topic membership", async function (assert) {
+ this.set("data", {
+ board: Board.create(
+ board(1, "Roadmap", [
+ {
+ id: 11,
+ title: "Done",
+ icon: "check",
+ color: "669DF1",
+ topic_is_member: true,
+ },
+ { id: 12, title: "Next", icon: "clock", color: "FCA700" },
+ ])
+ ),
+ topic: { id: 1 },
+ });
+
+ await render(
+ <template>
+ <BoardsAddFromTopicColumnSubmenu @data={{this.data}} />
+ </template>
+ );
+
+ assert.deepEqual(
+ findAll(".dropdown-menu__subheader").map((element) =>
+ element.textContent.trim()
+ ),
+ ["Roadmap", "Already added"]
+ );
+ const [availableColumn, alreadyAddedColumn] = findAll(
+ ".discourse-boards-add-from-topic-column-menu__column"
+ );
+ assert.deepEqual(
+ [availableColumn, alreadyAddedColumn].map((element) =>
+ element.textContent.trim()
+ ),
+ ["Next", "Done"]
+ );
+ assert
+ .dom(".discourse-boards-add-from-topic-column-menu__column .d-icon-clock")
+ .exists();
+ assert
+ .dom(".discourse-boards-add-from-topic-column-menu__column .d-icon-check")
+ .exists();
+ assert
+ .dom(".discourse-boards-add-from-topic-column-menu__column .d-icon-clock")
+ .hasStyle({ color: "rgb(252, 167, 0)" });
+ assert
+ .dom(".discourse-boards-add-from-topic-column-menu__column .d-icon-check")
+ .hasStyle({ color: "rgb(102, 157, 241)" });
+ assert.dom(".d-button__suffix-icon", availableColumn).doesNotExist();
+ assert.dom(".d-button__suffix-icon", alreadyAddedColumn).exists();
+
+ this.set("data", {
+ board: Board.create(
+ board(1, "Roadmap", [{ id: 12, title: "Next", icon: "clock" }])
+ ),
+ topic: { id: 1 },
+ });
+ await settled();
+
+ assert.deepEqual(
+ findAll(".dropdown-menu__subheader").map((element) =>
+ element.textContent.trim()
+ ),
+ ["Roadmap"],
+ "does not render an empty Already added section"
+ );
+ });
+
+ test("does not add the topic when the constraint check fails", async function (assert) {
+ let addRequests = 0;
+
+ pretender.put("/boards/api/boards/1/check-constraint-mismatches", () =>
+ response(500, { errors: ["Constraint check failed"] })
+ );
+ pretender.post("/boards/api/boards/1/cards", () => {
+ addRequests++;
+ return response({});
+ });
+
+ this.set("data", {
+ board: Board.create(
+ board(1, "Roadmap", [{ id: 11, title: "Next", icon: "clock" }])
+ ),
+ topic: { id: 1 },
+ });
+
+ await render(
+ <template>
+ <BoardsAddFromTopicColumnSubmenu @data={{this.data}} />
+ </template>
+ );
+ await click(".discourse-boards-add-from-topic-column-menu__column");
+
+ assert.strictEqual(addRequests, 0);
+ });
+});
diff --git a/plugins/boards/test/javascripts/components/boards-board-settings-test.gjs b/plugins/boards/test/javascripts/components/boards-board-settings-test.gjs
new file mode 100644
index 00000000000..061e2bccf7b
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-board-settings-test.gjs
@@ -0,0 +1,120 @@
+import { getOwner } from "@ember/owner";
+import { fillIn, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import BoardsBoardSettings from "discourse/plugins/boards/discourse/components/modal/boards-board-settings";
+import BoardsFabricators from "discourse/plugins/boards/discourse/lib/fabricators";
+
+module(
+ "Integration | Component | BoardsBoardSettings | New and existing boards",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.fabricators = new BoardsFabricators(getOwner(this));
+ this.model = {
+ board: null,
+ isNew: true,
+ onSave: sinon.spy(),
+ onDelete: () => {},
+ };
+ this.closeModal = sinon.spy();
+ });
+
+ test("slug placeholder is set to the slugified board name", async function (assert) {
+ await render(
+ <template>
+ <BoardsBoardSettings @model={{this.model}} @inline={{true}} />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-board-settings-modal").exists();
+ await fillIn(".discourse-boards-editable-title__input", "Apollo Program");
+
+ assert.strictEqual(
+ formKit().field("slug").inputElement.placeholder,
+ "apollo-program"
+ );
+ });
+
+ test("reports confirmed access loss when the saved modal closes", async function (assert) {
+ const group = this.site.groups[0];
+ const board = this.fabricators.board();
+ board.acl = [
+ {
+ type: "group",
+ id: group.id,
+ permission: "manage",
+ display_name: group.name,
+ },
+ ];
+ this.model = { ...this.model, board, isNew: false };
+
+ const dialog = getOwner(this).lookup("service:dialog");
+ sinon.stub(dialog, "confirm").resolves(true);
+
+ pretender.post("/access-control/evaluate.json", () =>
+ response(422, {
+ errors: ["You will lose permission to manage this board."],
+ extras: {
+ current_user_will_lose_permission: true,
+ loss_warning_permissions: ["manage"],
+ },
+ })
+ );
+
+ await render(
+ <template>
+ <BoardsBoardSettings
+ @model={{this.model}}
+ @closeModal={{this.closeModal}}
+ @inline={{true}}
+ />
+ </template>
+ );
+
+ await formKit().submit();
+
+ assert.true(this.model.onSave.calledOnce, "the board is saved");
+ assert.deepEqual(
+ this.closeModal.firstCall.args,
+ [{ reloadAfterSave: true }],
+ "the modal requests a reload after it closes"
+ );
+ });
+
+ test("default ACL is created using manage board allowed groups and logged in users", async function (assert) {
+ await render(
+ <template>
+ <BoardsBoardSettings @model={{this.model}} @inline={{true}} />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-board-settings-modal").exists();
+
+ assert.dom(".d-access-control__row.--group[data-row-id='1']").exists();
+ assert.dom(".d-access-control__row.--group[data-row-id='2']").exists();
+ assert.dom(".d-access-control__row.--group[data-row-id='5']").exists();
+ });
+
+ test("default ACL does not include logged_in_users twice if they are in boards_manage_board_allowed_groups", async function (assert) {
+ this.siteSettings.boards_manage_board_allowed_groups = "1|2|5";
+ await render(
+ <template>
+ <BoardsBoardSettings @model={{this.model}} @inline={{true}} />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-board-settings-modal").exists();
+
+ assert.dom(".d-access-control__row.--group[data-row-id='1']").exists();
+ assert.dom(".d-access-control__row.--group[data-row-id='2']").exists();
+ assert
+ .dom(".d-access-control__row.--group[data-row-id='5']")
+ .exists({ count: 1 });
+ });
+ }
+);
diff --git a/plugins/boards/test/javascripts/components/boards-board-viewer-test.gjs b/plugins/boards/test/javascripts/components/boards-board-viewer-test.gjs
new file mode 100644
index 00000000000..2d816537178
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-board-viewer-test.gjs
@@ -0,0 +1,711 @@
+import { getOwner } from "@ember/owner";
+import { click, render, settled, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import PermanentlyDeleteConfirmModal from "discourse/components/modal/permanently-delete-confirm";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, {
+ parsePostData,
+ response,
+} from "discourse/tests/helpers/create-pretender";
+import BoardsBoardViewer from "discourse/plugins/boards/discourse/components/boards-board-viewer";
+import BoardsFabricators from "discourse/plugins/boards/discourse/lib/fabricators";
+
+function columnSelector(columnId) {
+ return `.discourse-boards-column[data-column-id="${columnId}"]`;
+}
+
+function cardSelector(cardId) {
+ return `.discourse-boards-card[data-card-id="${cardId}"]`;
+}
+
+function columnCardIds(columnId) {
+ return [
+ ...document.querySelectorAll(
+ `${columnSelector(columnId)} .discourse-boards-card`
+ ),
+ ].map((card) => parseInt(card.dataset.cardId, 10));
+}
+
+function recentISO(daysAgo) {
+ return new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000).toISOString();
+}
+
+function stubCardRect(cardId, { top = 0, height = 48 } = {}) {
+ const card = document.querySelector(cardSelector(cardId));
+ sinon.stub(card, "getBoundingClientRect").returns({
+ top,
+ bottom: top + height,
+ left: 0,
+ right: 200,
+ width: 200,
+ height,
+ });
+}
+
+module("Integration | Component | BoardsBoardViewer", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.fabricators = new BoardsFabricators(getOwner(this));
+
+ this.messageBus = getOwner(this).lookup("service:message-bus");
+ this.originalClientId = this.messageBus.clientId;
+ this.messageBus.clientId = "test-client";
+ sinon.stub(this.messageBus, "subscribe");
+ sinon.stub(this.messageBus, "unsubscribe");
+
+ this.renderBoard = async (columns, boardOverrides = {}) => {
+ const board = this.fabricators.board({
+ id: 1,
+ can_write: true,
+ can_manage: false,
+ });
+ board.require_confirmation = false;
+ Object.assign(board, boardOverrides);
+
+ this.model = { board, columns };
+ await render(
+ <template>
+ <BoardsBoardViewer
+ @model={{this.model}}
+ @highlightCardId={{this.highlightCardId}}
+ @openBoardSettings={{this.openBoardSettings}}
+ />
+ </template>
+ );
+ };
+
+ this.makeColumn = ({ id, title, cards = [], defaultSort } = {}) => {
+ const column = this.fabricators.column({ id, title });
+ column.default_sort = defaultSort;
+ column.cards = cards;
+ return column;
+ };
+
+ this.makeCard = ({ id, columnId, title, position, recencyAt } = {}) => {
+ const card = this.fabricators.card({
+ id,
+ title,
+ column_id: columnId,
+ });
+ card.position = position;
+ card.recency_at = recencyAt;
+ return card;
+ };
+
+ this.dragDataTransfer = null;
+ this.dragCard = async (cardId) => {
+ this.dragDataTransfer = new DataTransfer();
+ stubCardRect(cardId);
+
+ await triggerEvent(cardSelector(cardId), "dragstart", {
+ clientX: 10,
+ clientY: 10,
+ dataTransfer: this.dragDataTransfer,
+ });
+ };
+
+ this.dropOnColumn = async (columnId, { clientY = 0 } = {}) => {
+ await triggerEvent(columnSelector(columnId), "drop", {
+ clientY,
+ dataTransfer: this.dragDataTransfer,
+ });
+ };
+ });
+
+ test("does not open board settings without manage permission", async function (assert) {
+ const modal = getOwner(this).lookup("service:modal");
+ const show = sinon.stub(modal, "show");
+ this.openBoardSettings = true;
+
+ await this.renderBoard([], { can_manage: false });
+ await settled();
+
+ assert.false(show.called, "the settings modal remains closed");
+ });
+
+ test("links board constraints while keeping the info tooltip", async function (assert) {
+ await this.renderBoard([], {
+ category_ids: [5],
+ tag_names: ["priority"],
+ });
+
+ assert
+ .dom(
+ ".discourse-boards-board-viewer__constraint a.badge-category__wrapper"
+ )
+ .hasAttribute("href", "/c/extensibility/5");
+ assert
+ .dom(
+ '.discourse-boards-board-viewer__constraint a.discourse-tag[data-tag-name="priority"]'
+ )
+ .hasAttribute("href", "/tag/priority");
+ assert
+ .dom(".discourse-boards-board-viewer__constraint .fk-d-tooltip__trigger")
+ .exists();
+ });
+
+ hooks.afterEach(function () {
+ this.messageBus.clientId = this.originalClientId;
+ sinon.restore();
+ });
+
+ test("completes a priority drop with the source column from drag start", async function (assert) {
+ const sourceCard = this.makeCard({
+ id: 101,
+ columnId: 10,
+ title: "Fix checkout",
+ position: 0,
+ });
+ const targetCard = this.makeCard({
+ id: 102,
+ columnId: 20,
+ title: "Ship receipts",
+ position: 0,
+ });
+
+ await this.renderBoard([
+ this.makeColumn({ id: 10, title: "Todo", cards: [sourceCard] }),
+ this.makeColumn({ id: 20, title: "Done", cards: [targetCard] }),
+ ]);
+
+ let requestData;
+ pretender.put("/boards/api/boards/1/cards/101", (request) => {
+ requestData = parsePostData(request.requestBody);
+
+ return response({
+ card: {
+ id: 101,
+ column_id: 20,
+ position: 1,
+ },
+ });
+ });
+
+ stubCardRect(102, { top: 0, height: 48 });
+ await this.dragCard(101);
+ await this.dropOnColumn(20, { clientY: 30 });
+
+ assert.strictEqual(requestData.card.column_id, "20");
+ assert.strictEqual(requestData.card.after_card_id, "102");
+ assert.deepEqual(
+ columnCardIds(10),
+ [],
+ "it removes the card from the source column"
+ );
+ assert.deepEqual(
+ columnCardIds(20),
+ [102, 101],
+ "it inserts the card after the target card"
+ );
+ assert
+ .dom(`${columnSelector(20)} ${cardSelector(101)}`)
+ .hasClass(
+ "discourse-boards-card--drop-highlighted",
+ "it highlights the dropped card"
+ );
+ });
+
+ test("dropping into a recency column sends no after_card_id and places the card first", async function (assert) {
+ const sourceCard = this.makeCard({
+ id: 101,
+ columnId: 10,
+ title: "Fix checkout",
+ position: 0,
+ });
+ const targetCard = this.makeCard({
+ id: 102,
+ columnId: 20,
+ title: "Ship receipts",
+ recencyAt: recentISO(2),
+ });
+
+ await this.renderBoard([
+ this.makeColumn({ id: 10, title: "Todo", cards: [sourceCard] }),
+ this.makeColumn({
+ id: 20,
+ title: "Recent",
+ cards: [targetCard],
+ defaultSort: "recency",
+ }),
+ ]);
+
+ let requestData;
+ pretender.put("/boards/api/boards/1/cards/101", (request) => {
+ requestData = parsePostData(request.requestBody);
+
+ return response({
+ card: {
+ id: 101,
+ column_id: 20,
+ position: -1,
+ recency_at: recentISO(1),
+ },
+ });
+ });
+
+ await this.dragCard(101);
+ await this.dropOnColumn(20);
+
+ assert.strictEqual(requestData.card.column_id, "20");
+ assert.strictEqual(requestData.card.after_card_id, "");
+ assert.deepEqual(
+ columnCardIds(10),
+ [],
+ "it removes the card from the source column"
+ );
+ assert.deepEqual(
+ columnCardIds(20),
+ [101, 102],
+ "it sorts the moved card to the top of the recency column"
+ );
+ });
+
+ test("checks topic card constraints on the server before moving it", async function (assert) {
+ const sourceCard = this.makeCard({
+ id: 101,
+ columnId: 10,
+ title: "Fix checkout",
+ position: 0,
+ });
+ sourceCard.topic_id = 777;
+ sourceCard.topic = { id: 777, title: "Fix checkout" };
+
+ const modal = getOwner(this).lookup("service:modal");
+ sinon.stub(modal, "show").callsFake((component, opts) => {
+ assert.deepEqual(opts.model.mismatches, {
+ needsTags: false,
+ needsCategory: true,
+ boardTagNames: [],
+ boardCategoryIds: [3],
+ });
+ opts.model.onConfirm({ category_id: 3 });
+ });
+
+ await this.renderBoard([
+ this.makeColumn({ id: 10, title: "Todo", cards: [sourceCard] }),
+ this.makeColumn({ id: 20, title: "Done", cards: [] }),
+ ]);
+
+ pretender.put(
+ "/boards/api/boards/1/check-constraint-mismatches",
+ (request) => {
+ const requestData = parsePostData(request.requestBody);
+ assert.strictEqual(requestData.topic_id, "777");
+ assert.strictEqual(requestData.target_column_id, "20");
+
+ return response({
+ categories_needed: [3],
+ tags_needed: [],
+ constraints_need_fixing: true,
+ });
+ }
+ );
+
+ let moveRequestData;
+ pretender.put("/boards/api/boards/1/cards/101", (request) => {
+ moveRequestData = parsePostData(request.requestBody);
+ return response({ card: { id: 101, column_id: 20, position: 0 } });
+ });
+
+ await this.dragCard(101);
+ await this.dropOnColumn(20);
+
+ assert.strictEqual(moveRequestData.constraint_fix.category_id, "3");
+ });
+
+ test("renders and highlights an old linked card in a recency column", async function (assert) {
+ const linkedCard = this.makeCard({
+ id: 101,
+ columnId: 10,
+ title: "Old linked card",
+ recencyAt: recentISO(8),
+ });
+ const recentCard = this.makeCard({
+ id: 102,
+ columnId: 10,
+ title: "Recent card",
+ recencyAt: recentISO(1),
+ });
+ this.highlightCardId = linkedCard.id;
+
+ await this.renderBoard([
+ this.makeColumn({
+ id: 10,
+ title: "Recent",
+ cards: [recentCard, linkedCard],
+ defaultSort: "recency",
+ }),
+ ]);
+ await settled();
+
+ assert
+ .dom(cardSelector(linkedCard.id))
+ .exists(
+ "the linked card is rendered despite falling outside the recency window"
+ )
+ .hasClass(
+ "discourse-boards-card--link-highlighted",
+ "the linked card receives the deep-link highlight"
+ );
+ });
+
+ test("canceling the constraint fix while adding a topic card stops creation", async function (assert) {
+ let addTopicAsCardModel;
+ let postRequests = 0;
+
+ const modal = getOwner(this).lookup("service:modal");
+ sinon.stub(modal, "show").callsFake((component, opts) => {
+ if (opts?.model?.onAddTopicAsCard) {
+ addTopicAsCardModel = opts.model;
+ } else if (opts?.model?.mismatches) {
+ opts.model.onCancel();
+ }
+
+ return Promise.resolve();
+ });
+
+ await this.renderBoard(
+ [this.makeColumn({ id: 10, title: "Todo", cards: [] })],
+ { category_ids: [1], tag_names: [] }
+ );
+
+ pretender.put(
+ "/boards/api/boards/1/check-constraint-mismatches",
+ (request) => {
+ const requestData = parsePostData(request.requestBody);
+ assert.strictEqual(requestData.topic_id, "777");
+ assert.strictEqual(requestData.target_column_id, "10");
+
+ return response({
+ categories_needed: [1],
+ tags_needed: [],
+ constraints_need_fixing: true,
+ });
+ }
+ );
+
+ pretender.post("/boards/api/boards/1/cards", () => {
+ postRequests++;
+ return response({ card: { id: 101, column_id: 10 } });
+ });
+
+ await click(".discourse-boards-column__add-btn");
+ await click(".fk-d-menu li:last-child button");
+ await addTopicAsCardModel.onAddTopicAsCard({
+ topicId: 777,
+ title: "Wrong category",
+ });
+
+ assert.strictEqual(postRequests, 0, "it does not create the card");
+ });
+
+ test("clicking and dragging on the board scrolls columns horizontally", async function (assert) {
+ await this.renderBoard([
+ this.makeColumn({
+ id: 10,
+ title: "Todo",
+ cards: [
+ this.makeCard({
+ id: 101,
+ columnId: 10,
+ title: "Fix checkout",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 20,
+ title: "Done",
+ cards: [
+ this.makeCard({
+ id: 102,
+ columnId: 20,
+ title: "Ship receipts",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 30,
+ title: "In Progress",
+ cards: [
+ this.makeCard({
+ id: 103,
+ columnId: 30,
+ title: "Implement login page",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 40,
+ title: "Review",
+ cards: [
+ this.makeCard({
+ id: 104,
+ columnId: 40,
+ title: "Write integration test coverage",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 50,
+ title: "Deploy",
+ cards: [
+ this.makeCard({
+ id: 105,
+ columnId: 50,
+ title: "Deploy to staging",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 60,
+ title: "Done",
+ cards: [
+ this.makeCard({
+ id: 106,
+ columnId: 60,
+ title: "Deploy to production",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 70,
+ title: "Cancelled",
+ cards: [
+ this.makeCard({
+ id: 107,
+ columnId: 70,
+ title: "Cancel order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 80,
+ title: "Archived",
+ cards: [
+ this.makeCard({
+ id: 108,
+ columnId: 80,
+ title: "Archive order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 90,
+ title: "On Hold",
+ cards: [
+ this.makeCard({
+ id: 109,
+ columnId: 90,
+ title: "On hold order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 100,
+ title: "Backlog",
+ cards: [
+ this.makeCard({
+ id: 110,
+ columnId: 100,
+ title: "Backlog order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 110,
+ title: "In Progress",
+ cards: [
+ this.makeCard({
+ id: 111,
+ columnId: 110,
+ title: "In progress order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 120,
+ title: "Review",
+ cards: [
+ this.makeCard({
+ id: 112,
+ columnId: 120,
+ title: "Review order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 130,
+ title: "Deploy",
+ cards: [
+ this.makeCard({
+ id: 113,
+ columnId: 130,
+ title: "Deploy order",
+ position: 0,
+ }),
+ ],
+ }),
+ this.makeColumn({
+ id: 140,
+ title: "Done",
+ cards: [
+ this.makeCard({
+ id: 114,
+ columnId: 140,
+ title: "Done order",
+ position: 0,
+ }),
+ ],
+ }),
+ ]);
+
+ const container = document.querySelector(
+ ".discourse-boards-board-container"
+ );
+
+ await triggerEvent(container, "pointerdown", {
+ pointerId: 1,
+ pointerType: "mouse",
+ button: 0,
+ clientX: 400,
+ clientY: 100,
+ });
+ await triggerEvent(container, "pointermove", {
+ pointerId: 1,
+ pointerType: "mouse",
+ clientX: -600,
+ clientY: 100,
+ });
+
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+
+ assert.strictEqual(
+ container.scrollLeft,
+ 1000,
+ "it scrolls the container by the drag distance"
+ );
+
+ await triggerEvent(container, "pointerup", {
+ pointerId: 1,
+ pointerType: "mouse",
+ clientX: 200,
+ clientY: 100,
+ });
+ });
+
+ test("deleting a column with many cards shows the permanently-delete confirm modal", async function (assert) {
+ const cards = Array.from({ length: 6 }, (_, index) =>
+ this.makeCard({
+ id: 200 + index,
+ columnId: 10,
+ title: `Card ${index + 1}`,
+ position: index,
+ })
+ );
+
+ const modal = getOwner(this).lookup("service:modal");
+ let modalComponent;
+ let modalOptions;
+ sinon.stub(modal, "show").callsFake((component, options) => {
+ modalComponent = component;
+ modalOptions = options;
+ return Promise.resolve();
+ });
+
+ let saveRequests = 0;
+ pretender.delete("/boards/api/boards/1/columns/10", () => {
+ saveRequests++;
+ return response(204);
+ });
+ pretender.get("/boards/api/boards/1.json", () =>
+ response({ board: {}, columns: [] })
+ );
+
+ await this.renderBoard(
+ [this.makeColumn({ id: 10, title: "Done", cards })],
+ { can_manage: true }
+ );
+
+ await click(`${columnSelector(10)} .discourse-boards-column__menu-trigger`);
+ await click(".discourse-boards-column__menu-delete");
+
+ assert.strictEqual(
+ modalComponent,
+ PermanentlyDeleteConfirmModal,
+ "it opens the permanently-delete confirm modal"
+ );
+ assert.strictEqual(
+ modalOptions.model.confirmPhrase,
+ "Done",
+ "it passes the column title as the confirm phrase"
+ );
+ assert.strictEqual(
+ typeof modalOptions.model.didConfirm,
+ "function",
+ "it wires up a didConfirm callback"
+ );
+
+ modalOptions.model.didConfirm();
+ await settled();
+
+ assert.strictEqual(
+ saveRequests,
+ 1,
+ "confirming the modal triggers the columns save"
+ );
+ });
+
+ test("same-column recency drops are ignored", async function (assert) {
+ const firstCard = this.makeCard({
+ id: 101,
+ columnId: 20,
+ title: "Fix checkout",
+ recencyAt: recentISO(1),
+ });
+ const secondCard = this.makeCard({
+ id: 102,
+ columnId: 20,
+ title: "Ship receipts",
+ recencyAt: recentISO(2),
+ });
+ let putRequests = 0;
+
+ await this.renderBoard([
+ this.makeColumn({
+ id: 20,
+ title: "Recent",
+ cards: [firstCard, secondCard],
+ defaultSort: "recency",
+ }),
+ ]);
+
+ pretender.put("/boards/api/boards/1/cards/101", () => {
+ putRequests++;
+ return response({ card: { id: 101, column_id: 20 } });
+ });
+
+ await this.dragCard(101);
+ await this.dropOnColumn(20);
+
+ assert.strictEqual(putRequests, 0, "it does not save ignored drops");
+ assert.deepEqual(
+ columnCardIds(20),
+ [101, 102],
+ "it leaves the recency column order unchanged"
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/components/boards-card-test.gjs b/plugins/boards/test/javascripts/components/boards-card-test.gjs
new file mode 100644
index 00000000000..a79395f0ce2
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-card-test.gjs
@@ -0,0 +1,231 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import BoardsCard from "discourse/plugins/boards/discourse/components/boards-card";
+import BoardsFabricators from "discourse/plugins/boards/discourse/lib/fabricators";
+
+module("Integration | Component | BoardsCard", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.fabricators = new BoardsFabricators(getOwner(this));
+ this.card = this.fabricators.card();
+ this.board = this.fabricators.board();
+ this.card.board_id = this.board.id;
+ });
+
+ test("renders basic card", async function (assert) {
+ await render(
+ <template>
+ <BoardsCard @card={{this.card}} @board={{this.board}} />
+ </template>
+ );
+ assert.dom(".discourse-boards-card").exists();
+ assert.dom(".discourse-boards-card__title").hasText(this.card.title);
+ });
+
+ test("renders a floater card's Unicode title", async function (assert) {
+ this.card.title = "Launch :rocket:";
+ this.card.unicode_title = "Launch πŸš€";
+
+ await render(
+ <template>
+ <BoardsCard @card={{this.card}} @board={{this.board}} />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-card__title").hasText("Launch πŸš€");
+ });
+
+ test("renders stored inline onebox data for a floater card", async function (assert) {
+ this.card.title = "https://github.com/discourse/discourse/pull/42462";
+ this.card.inline_onebox_data = {
+ url: this.card.title,
+ title: "FEATURE: Add ProseMirror tab support",
+ css_class: "--gh-status-approved",
+ };
+
+ await render(
+ <template>
+ <BoardsCard @card={{this.card}} @board={{this.board}} />
+ </template>
+ );
+
+ assert
+ .dom(".discourse-boards-card__title a.inline-onebox")
+ .hasAttribute("href", this.card.title)
+ .hasAttribute("target", "_blank")
+ .hasClass("--gh-status-approved")
+ .hasText("FEATURE: Add ProseMirror tab support");
+ });
+
+ test("renders a topic card's Unicode title", async function (assert) {
+ this.card = this.fabricators.card({
+ topic: {
+ id: 42,
+ title: "Topic :rocket:",
+ unicode_title: "Topic πŸš€",
+ },
+ });
+
+ await render(
+ <template>
+ <BoardsCard @card={{this.card}} @board={{this.board}} />
+ </template>
+ );
+
+ assert
+ .dom(".discourse-boards-card__title.discourse-boards-card__title--topic")
+ .hasText("Topic");
+ assert
+ .dom('.discourse-boards-card__title--topic img.emoji[title="rocket"]')
+ .exists();
+ });
+
+ test("unescapes emoji shortcodes remaining in a topic card's Unicode title", async function (assert) {
+ this.card = this.fabricators.card({
+ topic: {
+ id: 42,
+ title: "Funny topic :joy:",
+ unicode_title: "Funny topic :joy:",
+ },
+ });
+
+ await render(
+ <template>
+ <BoardsCard @card={{this.card}} @board={{this.board}} />
+ </template>
+ );
+
+ assert
+ .dom('.discourse-boards-card__title--topic img.emoji[title="joy"]')
+ .exists();
+ });
+
+ test("escapes topic card titles before unescaping emoji", async function (assert) {
+ this.card = this.fabricators.card({
+ topic: {
+ id: 42,
+ title: '<img src=x data-dangerous="true"> :joy:',
+ },
+ });
+
+ await render(
+ <template>
+ <BoardsCard @card={{this.card}} @board={{this.board}} />
+ </template>
+ );
+
+ assert.dom('[data-dangerous="true"]').doesNotExist();
+ assert
+ .dom('.discourse-boards-card__title--topic img.emoji[title="joy"]')
+ .exists();
+ assert
+ .dom(".discourse-boards-card__title--topic")
+ .includesText('<img src=x data-dangerous="true">');
+ });
+
+ test("suppresses column tags on floater cards", async function (assert) {
+ this.card.tags = [
+ { id: 1, name: "todo", slug: "todo" },
+ { id: 2, name: "unrelated", slug: "unrelated" },
+ ];
+ this.columnTags = ["todo"];
+
+ await render(
+ <template>
+ <BoardsCard
+ @card={{this.card}}
+ @board={{this.board}}
+ @columnTags={{this.columnTags}}
+ />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-card__tags").hasText("unrelated");
+ assert.dom(".discourse-boards-card__tags").doesNotContainText("todo");
+ });
+});
+
+module(
+ "Integration | Component | BoardsCard | Discourse Assign",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.fabricators = new BoardsFabricators(getOwner(this));
+ this.card = this.fabricators.card();
+ this.board = this.fabricators.board();
+ this.board.card_style = "detailed";
+ this.card.board_id = this.board.id;
+ this.currentUser.can_assign = true;
+ this.siteSettings.assign_enabled = true;
+ });
+
+ test("does not render assign button when assign_enabled is false", async function (assert) {
+ this.siteSettings.assign_enabled = false;
+ await render(
+ <template>
+ <BoardsCard
+ @card={{this.card}}
+ @board={{this.board}}
+ @canWrite={{this.board.can_write}}
+ />
+ </template>
+ );
+ assert.dom(".discourse-boards-card__assign-btn").doesNotExist();
+ });
+
+ test("renders assign button for a floating card", async function (assert) {
+ this.card.card_type = "floater";
+ await render(
+ <template>
+ <BoardsCard
+ @card={{this.card}}
+ @board={{this.board}}
+ @canWrite={{this.board.can_write}}
+ />
+ </template>
+ );
+ assert.dom(".discourse-boards-card__assign-btn").exists();
+ });
+
+ test("renders assign button for a topic card", async function (assert) {
+ const topic = this.fabricators.coreFabricators.topic();
+ this.card.card_type = "topic";
+ this.card.topic_id = topic.id;
+ this.card.topic = topic;
+
+ await render(
+ <template>
+ <BoardsCard
+ @card={{this.card}}
+ @board={{this.board}}
+ @canWrite={{this.board.can_write}}
+ />
+ </template>
+ );
+ assert.dom(".discourse-boards-card__assign-btn").exists();
+ });
+
+ test("does not render assignment for a closed topic card", async function (assert) {
+ const topic = this.fabricators.coreFabricators.topic();
+ topic.closed = true;
+ this.card.card_type = "topic";
+ this.card.topic_id = topic.id;
+ this.card.topic = topic;
+ topic.closed = true;
+ await render(
+ <template>
+ <BoardsCard
+ @card={{this.card}}
+ @board={{this.board}}
+ @canWrite={{this.board.can_write}}
+ />
+ </template>
+ );
+ assert.dom(".discourse-boards-card__assign-btn").doesNotExist();
+ });
+ }
+);
diff --git a/plugins/boards/test/javascripts/components/boards-column-test.gjs b/plugins/boards/test/javascripts/components/boards-column-test.gjs
new file mode 100644
index 00000000000..7b39ddc7962
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-column-test.gjs
@@ -0,0 +1,103 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import BoardsColumn from "discourse/plugins/boards/discourse/components/boards-column";
+import BoardsFabricators from "discourse/plugins/boards/discourse/lib/fabricators";
+
+function cardSelector(cardId) {
+ return `.discourse-boards-card[data-card-id="${cardId}"]`;
+}
+
+function daysAgoISO(days) {
+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
+}
+
+module("Integration | Component | BoardsColumn", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.fabricators = new BoardsFabricators(getOwner(this));
+ this.board = this.fabricators.board({ id: 1, can_write: false });
+
+ this.oldCard = this.fabricators.card({
+ id: 101,
+ title: "Old card",
+ column_id: 10,
+ });
+ this.oldCard.recency_at = daysAgoISO(8);
+
+ this.recentCard = this.fabricators.card({
+ id: 102,
+ title: "Recent card",
+ column_id: 10,
+ });
+ this.recentCard.recency_at = daysAgoISO(1);
+
+ this.column = this.fabricators.column({ id: 10, title: "Recent" });
+ this.column.default_sort = "recency";
+ this.column.cards = [this.oldCard, this.recentCard];
+
+ this.renderColumn = async () => {
+ await render(
+ <template>
+ <BoardsColumn
+ @column={{this.column}}
+ @board={{this.board}}
+ @canWrite={{false}}
+ @canManage={{false}}
+ @linkedCardId={{this.linkedCardId}}
+ @linkHighlightCardId={{this.linkHighlightCardId}}
+ />
+ </template>
+ );
+ };
+ });
+
+ test("hides cards outside the recency window", async function (assert) {
+ await this.renderColumn();
+
+ assert.dom(cardSelector(102)).exists("the recent card renders");
+ assert.dom(cardSelector(101)).doesNotExist("the old card is filtered out");
+ assert
+ .dom(".discourse-boards-column__show-all")
+ .exists("the hidden card is reachable behind the show-all button");
+ });
+
+ test("keeps the deep-linked card rendered once its highlight has faded", async function (assert) {
+ // The pulse highlight clears itself when its animation ends; the card it
+ // pointed at has to stay on the board after that.
+ this.linkedCardId = 101;
+ this.linkHighlightCardId = null;
+
+ await this.renderColumn();
+
+ assert
+ .dom(cardSelector(101))
+ .exists("the deep-linked card still bypasses the recency window")
+ .doesNotHaveClass(
+ "discourse-boards-card--link-highlighted",
+ "the faded pulse highlight is not reapplied"
+ );
+ });
+
+ test("pulses the deep-linked card while its highlight is active", async function (assert) {
+ this.linkedCardId = 101;
+ this.linkHighlightCardId = 101;
+
+ await this.renderColumn();
+
+ assert
+ .dom(cardSelector(101))
+ .hasClass(
+ "discourse-boards-card--link-highlighted",
+ "the linked card is highlighted"
+ );
+ assert
+ .dom(cardSelector(102))
+ .doesNotHaveClass(
+ "discourse-boards-card--link-highlighted",
+ "other cards are left alone"
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/components/boards-menu-test.gjs b/plugins/boards/test/javascripts/components/boards-menu-test.gjs
new file mode 100644
index 00000000000..6b6457bac84
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-menu-test.gjs
@@ -0,0 +1,155 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import BoardsMenu from "discourse/plugins/boards/discourse/components/boards-menu";
+
+function membership({
+ boardId,
+ boardName,
+ cardId,
+ columnId,
+ columnTitle,
+ unicodeColumnTitle,
+ unicodeBoardName,
+}) {
+ return {
+ board_id: boardId,
+ board_name: boardName,
+ unicode_board_name: unicodeBoardName,
+ board_slug: boardName.toLowerCase(),
+ cards: [
+ {
+ card_id: cardId,
+ column_id: columnId,
+ column_title: columnTitle,
+ unicode_column_title: unicodeColumnTitle,
+ column_color: "0088cc",
+ column_icon: "list",
+ },
+ ],
+ };
+}
+
+module("Integration | Component | BoardsMenu", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("lists each board with its column chips", async function (assert) {
+ this.data = {
+ memberships: [
+ membership({
+ boardId: 1,
+ boardName: "Sales",
+ cardId: 101,
+ columnId: 11,
+ columnTitle: "In progress",
+ }),
+ membership({
+ boardId: 2,
+ boardName: "Support",
+ cardId: 201,
+ columnId: 21,
+ columnTitle: "Queued",
+ }),
+ ],
+ };
+ this.close = () => {};
+
+ await render(
+ <template>
+ <BoardsMenu @data={{this.data}} @close={{this.close}} />
+ </template>
+ );
+
+ const labels = [
+ ...document.querySelectorAll(".discourse-boards-boards-menu__item-label"),
+ ].map((el) => el.textContent.trim());
+ assert.deepEqual(labels, ["Sales", "Support"]);
+
+ assert
+ .dom(
+ ".discourse-boards-boards-menu__item .discourse-boards-boards-menu__column"
+ )
+ .exists({ count: 2 });
+ assert
+ .dom(".discourse-boards-boards-menu__column")
+ .hasText("In progress", "shows the column the card sits in");
+ });
+
+ test("lists every column when a topic has several cards on one board", async function (assert) {
+ const sales = membership({
+ boardId: 1,
+ boardName: "Sales",
+ cardId: 101,
+ columnId: 11,
+ columnTitle: "In progress",
+ });
+ sales.cards.push({
+ card_id: 102,
+ column_id: 12,
+ column_title: "Done",
+ column_color: "00aa66",
+ column_icon: "check",
+ });
+ this.data = { memberships: [sales] };
+ this.close = () => {};
+
+ await render(
+ <template>
+ <BoardsMenu @data={{this.data}} @close={{this.close}} />
+ </template>
+ );
+
+ assert
+ .dom(".discourse-boards-boards-menu__item-label")
+ .exists({ count: 1 });
+ assert.dom(".discourse-boards-boards-menu__column").exists({ count: 2 });
+ });
+
+ test("renders Unicode column titles", async function (assert) {
+ this.data = {
+ memberships: [
+ membership({
+ boardId: 1,
+ boardName: "Sales",
+ cardId: 101,
+ columnId: 11,
+ columnTitle: "Doing :rocket:",
+ unicodeColumnTitle: "Doing πŸš€",
+ }),
+ ],
+ };
+ this.close = () => {};
+
+ await render(
+ <template>
+ <BoardsMenu @data={{this.data}} @close={{this.close}} />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-boards-menu__column").hasText("Doing πŸš€");
+ });
+
+ test("renders Unicode board names", async function (assert) {
+ this.data = {
+ memberships: [
+ membership({
+ boardId: 1,
+ boardName: "Sales :fire:",
+ unicodeBoardName: "Sales πŸ”₯",
+ cardId: 101,
+ columnId: 11,
+ columnTitle: "Doing",
+ }),
+ ],
+ };
+ this.close = () => {};
+
+ await render(
+ <template>
+ <BoardsMenu @data={{this.data}} @close={{this.close}} />
+ </template>
+ );
+
+ assert.dom(".discourse-boards-boards-menu__item-label").hasText("Sales πŸ”₯");
+ });
+});
diff --git a/plugins/boards/test/javascripts/components/boards-topic-pill-menu-test.gjs b/plugins/boards/test/javascripts/components/boards-topic-pill-menu-test.gjs
new file mode 100644
index 00000000000..e55b1108004
--- /dev/null
+++ b/plugins/boards/test/javascripts/components/boards-topic-pill-menu-test.gjs
@@ -0,0 +1,73 @@
+import EmberObject from "@ember/object";
+import { trustHTML } from "@ember/template";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import DMenus from "discourse/float-kit/components/d-menus";
+import renderTags from "discourse/lib/render-tags";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+function membership({ boardId, boardName, cardId, columnTitle }) {
+ return {
+ board_id: boardId,
+ board_name: boardName,
+ board_slug: boardName.toLowerCase(),
+ cards: [
+ {
+ card_id: cardId,
+ column_id: 11,
+ column_title: columnTitle,
+ column_color: "0088cc",
+ column_icon: "list",
+ },
+ ],
+ };
+}
+
+module("Integration | boards topic pill menu", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("clicking the pill of a topic on several boards opens a menu of them", async function (assert) {
+ const topic = EmberObject.create({
+ board_memberships: [
+ membership({
+ boardId: 1,
+ boardName: "Sales",
+ cardId: 101,
+ columnTitle: "In progress",
+ }),
+ membership({
+ boardId: 2,
+ boardName: "Support",
+ cardId: 201,
+ columnTitle: "Queued",
+ }),
+ ],
+ });
+ this.tags = trustHTML(renderTags(topic));
+
+ await render(
+ <template>
+ {{this.tags}}
+ <DMenus />
+ </template>
+ );
+
+ assert
+ .dom(".discourse-boards-topic-pill--multiple")
+ .hasAria("expanded", "false");
+
+ await click(".discourse-boards-topic-pill--multiple");
+
+ assert
+ .dom(".discourse-boards-topic-pill--multiple")
+ .hasAria("expanded", "true");
+ assert.deepEqual(
+ [
+ ...document.querySelectorAll(
+ ".discourse-boards-boards-menu__item-label"
+ ),
+ ].map((el) => el.textContent.trim()),
+ ["Sales", "Support"]
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/unit/components/boards-drop-test.js b/plugins/boards/test/javascripts/unit/components/boards-drop-test.js
new file mode 100644
index 00000000000..8093b5f0e33
--- /dev/null
+++ b/plugins/boards/test/javascripts/unit/components/boards-drop-test.js
@@ -0,0 +1,157 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { shouldRefetchMovedCardPayload } from "discourse/plugins/boards/discourse/components/boards-board-viewer";
+import { shouldInsertSourceDropIndicator } from "discourse/plugins/boards/discourse/components/boards-card";
+import {
+ recencyDropIndicatorInsertBefore,
+ shouldAnimateDropIndicatorPlacement,
+} from "discourse/plugins/boards/discourse/components/boards-column";
+import { autoScrollSpeedForPointer } from "discourse/plugins/boards/discourse/lib/boards-auto-scroll";
+
+function createDropTarget() {
+ const column = document.createElement("div");
+ column.className = "discourse-boards-column";
+
+ const cardsContainer = document.createElement("div");
+ cardsContainer.className = "discourse-boards-column__cards";
+
+ column.append(cardsContainer);
+ return column;
+}
+
+module("Boards | Unit | Components | boards drop", function (hooks) {
+ setupTest(hooks);
+
+ test("the initial placeholder in the source column does not animate", function (assert) {
+ assert.false(
+ shouldAnimateDropIndicatorPlacement({
+ hadIndicator: false,
+ columnId: 10,
+ fromColumnId: 10,
+ hasPlacedIndicator: false,
+ }),
+ "it skips the first placeholder animation in the source column"
+ );
+ assert.true(
+ shouldAnimateDropIndicatorPlacement({
+ hadIndicator: true,
+ columnId: 10,
+ fromColumnId: 10,
+ hasPlacedIndicator: true,
+ }),
+ "it still animates after the placeholder already exists"
+ );
+ assert.true(
+ shouldAnimateDropIndicatorPlacement({
+ hadIndicator: false,
+ columnId: 20,
+ fromColumnId: 10,
+ hasPlacedIndicator: false,
+ }),
+ "it still animates the initial placement in a different column"
+ );
+ assert.true(
+ shouldAnimateDropIndicatorPlacement({
+ hadIndicator: false,
+ columnId: 10,
+ fromColumnId: 10,
+ hasPlacedIndicator: true,
+ }),
+ "it animates when re-entering the source column later in the drag"
+ );
+ });
+
+ test("source placeholder insertion is skipped once a live placeholder exists", function (assert) {
+ const root = document.createElement("div");
+
+ assert.true(
+ shouldInsertSourceDropIndicator(root),
+ "it allows the source placeholder before any live placeholder exists"
+ );
+
+ const sourceIndicator = document.createElement("div");
+ sourceIndicator.className =
+ "discourse-boards-column__drop-indicator discourse-boards-column__drop-indicator--source";
+ root.append(sourceIndicator);
+
+ assert.true(
+ shouldInsertSourceDropIndicator(root),
+ "it ignores the hidden source placeholder"
+ );
+
+ const liveIndicator = document.createElement("div");
+ liveIndicator.className = "discourse-boards-column__drop-indicator";
+ root.append(liveIndicator);
+
+ assert.false(
+ shouldInsertSourceDropIndicator(root),
+ "it skips inserting the source placeholder after dragover has created a live placeholder"
+ );
+ });
+
+ test("recency drop indicator target falls before the show older button when all cards are hidden", function (assert) {
+ const target = createDropTarget();
+ const cardsContainer = target.querySelector(
+ ".discourse-boards-column__cards"
+ );
+ const showAllButton = document.createElement("button");
+ showAllButton.className = "discourse-boards-column__show-all";
+ cardsContainer.append(showAllButton);
+
+ assert.strictEqual(
+ recencyDropIndicatorInsertBefore(cardsContainer, [], 101),
+ showAllButton,
+ "the show older button is used as the insertion point"
+ );
+ });
+
+ test("column drag auto-scroll speed follows pointer edge proximity", function (assert) {
+ const verticalRect = { top: 100, bottom: 500 };
+ const horizontalRect = { left: 100, right: 500 };
+
+ assert.strictEqual(
+ autoScrollSpeedForPointer(300, verticalRect),
+ 0,
+ "it does not scroll away from the column edges"
+ );
+ assert.true(
+ autoScrollSpeedForPointer(110, verticalRect) < 0,
+ "it scrolls up near the top edge"
+ );
+ assert.true(
+ autoScrollSpeedForPointer(490, verticalRect) > 0,
+ "it scrolls down near the bottom edge"
+ );
+ assert.true(
+ Math.abs(autoScrollSpeedForPointer(100, verticalRect)) >
+ Math.abs(autoScrollSpeedForPointer(150, verticalRect)),
+ "it scrolls faster closer to the edge"
+ );
+ assert.true(
+ autoScrollSpeedForPointer(490, horizontalRect, "x") > 0,
+ "it supports horizontal scrolling near the right edge"
+ );
+ });
+
+ test("moved topic cards without existing topic data require a board refetch", function (assert) {
+ assert.true(
+ shouldRefetchMovedCardPayload(null, {
+ id: 101,
+ column_id: 20,
+ topic_id: 9001,
+ }),
+ "it refetches when a new topic card payload omits the topic"
+ );
+ assert.false(
+ shouldRefetchMovedCardPayload(
+ { id: 101, topic_id: 9001, topic: { id: 9001 } },
+ { id: 101, column_id: 20, topic_id: 9001 }
+ ),
+ "it merges stripped payloads for cards already visible to the client"
+ );
+ assert.false(
+ shouldRefetchMovedCardPayload(null, { id: 102, column_id: 20 }),
+ "it does not refetch floating cards"
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/unit/lib/boards-column-helpers-test.js b/plugins/boards/test/javascripts/unit/lib/boards-column-helpers-test.js
new file mode 100644
index 00000000000..219ab242f0c
--- /dev/null
+++ b/plugins/boards/test/javascripts/unit/lib/boards-column-helpers-test.js
@@ -0,0 +1,41 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ columnColorVariable,
+ hasColumnColor,
+} from "discourse/plugins/boards/discourse/lib/boards-column-helpers";
+
+module("Boards | Unit | Lib | boards-column-helpers", function (hooks) {
+ setupTest(hooks);
+
+ test("hasColumnColor recognizes valid hex values only", function (assert) {
+ assert.true(hasColumnColor("1a2b3c"), "a 6-digit hex has a color");
+ assert.true(hasColumnColor("f0a"), "a 3-digit hex has a color");
+ assert.false(hasColumnColor(null), "no value has no color");
+ assert.false(hasColumnColor(""), "empty has no color");
+ assert.false(hasColumnColor("nope!"), "a malformed value has no color");
+ });
+
+ test("columnColorVariable emits the fill plus contrasting text colors", function (assert) {
+ assert.strictEqual(
+ columnColorVariable("1a2b3c").toString(),
+ "--discourse-boards-column-color: #1a2b3c; --discourse-boards-column-title-text-color: #ffffff;",
+ "a dark color gets white title text"
+ );
+ assert.strictEqual(
+ columnColorVariable("ddb30e").toString(),
+ "--discourse-boards-column-color: #ddb30e; --discourse-boards-column-title-text-color: #ffffff;",
+ "a light color still gets light text on the darker title chip"
+ );
+ assert.strictEqual(
+ columnColorVariable("f0a").toString(),
+ "--discourse-boards-column-color: #ff00aa; --discourse-boards-column-title-text-color: #ffffff;",
+ "short hexes are expanded"
+ );
+ assert.strictEqual(
+ columnColorVariable(null).toString(),
+ "--discourse-boards-column-color: var(--primary-500); --discourse-boards-column-title-text-color: var(--secondary);",
+ "unset/invalid colors fall back to scheme variables for the fill and text"
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/unit/lib/boards-motion-test.js b/plugins/boards/test/javascripts/unit/lib/boards-motion-test.js
new file mode 100644
index 00000000000..74130c48b3d
--- /dev/null
+++ b/plugins/boards/test/javascripts/unit/lib/boards-motion-test.js
@@ -0,0 +1,104 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ animateCardReorder,
+ boardsMotionEnabled,
+ captureCardRects,
+ KANBAN_MOTION_EASING,
+ KANBAN_REORDER_DURATION,
+} from "discourse/plugins/boards/discourse/lib/boards-motion";
+
+function createCard(cardId) {
+ const card = document.createElement("div");
+ card.className = "discourse-boards-card";
+ card.dataset.cardId = String(cardId);
+ return card;
+}
+
+module("Boards | Unit | Lib | boards-motion", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.originalMatchMedia = window.matchMedia;
+ this.container = document.createElement("div");
+ document.body.append(this.container);
+ });
+
+ hooks.afterEach(function () {
+ window.matchMedia = this.originalMatchMedia;
+ this.container.remove();
+ });
+
+ test("boardsMotionEnabled respects reduced motion", function (assert) {
+ window.matchMedia = () => ({ matches: true });
+ assert.false(boardsMotionEnabled());
+
+ window.matchMedia = () => ({ matches: false });
+ assert.true(boardsMotionEnabled());
+ });
+
+ test("captureCardRects skips excluded cards", function (assert) {
+ const firstCard = createCard(1);
+ firstCard.getBoundingClientRect = () => ({ left: 16, top: 24 });
+
+ const secondCard = createCard(2);
+ secondCard.getBoundingClientRect = () => ({ left: 32, top: 48 });
+
+ this.container.append(firstCard, secondCard);
+
+ const rects = captureCardRects(this.container, { skipCardIds: [2] });
+
+ assert.deepEqual(rects.get("1"), { left: 16, top: 24 });
+ assert.false(rects.has("2"));
+ });
+
+ test("animateCardReorder animates cards from the previous visual position", function (assert) {
+ window.matchMedia = () => ({ matches: false });
+
+ const card = createCard(1);
+ let frames;
+ let options;
+
+ card.getBoundingClientRect = () => ({ left: 12, top: 72 });
+ card.animate = (newFrames, newOptions) => {
+ frames = newFrames;
+ options = newOptions;
+
+ return {
+ cancel() {},
+ oncancel: null,
+ onfinish: null,
+ };
+ };
+
+ this.container.append(card);
+
+ animateCardReorder(this.container, new Map([["1", { left: 12, top: 24 }]]));
+
+ assert.deepEqual(frames, [
+ { transform: "translate3d(0px, -48px, 0)" },
+ { transform: "translate3d(0, 0, 0)" },
+ ]);
+ assert.deepEqual(options, {
+ duration: KANBAN_REORDER_DURATION,
+ easing: KANBAN_MOTION_EASING,
+ });
+ });
+
+ test("animateCardReorder skips cards when Element.animate is unavailable", function (assert) {
+ window.matchMedia = () => ({ matches: false });
+
+ const card = createCard(1);
+ card.getBoundingClientRect = () => ({ left: 12, top: 72 });
+
+ this.container.append(card);
+
+ animateCardReorder(this.container, new Map([["1", { left: 12, top: 24 }]]));
+
+ assert.strictEqual(
+ card.style.transform,
+ "",
+ "it skips the animation when animations are unsupported"
+ );
+ });
+});
diff --git a/plugins/boards/test/javascripts/unit/lib/boards-topic-pill-test.js b/plugins/boards/test/javascripts/unit/lib/boards-topic-pill-test.js
new file mode 100644
index 00000000000..af0d3e74898
--- /dev/null
+++ b/plugins/boards/test/javascripts/unit/lib/boards-topic-pill-test.js
@@ -0,0 +1,237 @@
+import EmberObject from "@ember/object";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import renderTags from "discourse/lib/render-tags";
+import { membershipsFor } from "discourse/plugins/boards/discourse/lib/boards-topic-pill";
+
+function membership({
+ boardId,
+ boardName,
+ unicodeBoardName,
+ cardId,
+ columnTitle,
+}) {
+ return {
+ board_id: boardId,
+ board_name: boardName,
+ unicode_board_name: unicodeBoardName,
+ board_slug: boardName.toLowerCase(),
+ cards: [
+ {
+ card_id: cardId,
+ column_id: 11,
+ column_title: columnTitle,
+ column_color: "0088cc",
+ column_icon: "list",
+ },
+ ],
+ };
+}
+
+function sales() {
+ return membership({
+ boardId: 1,
+ boardName: "Sales",
+ cardId: 101,
+ columnTitle: "In progress",
+ });
+}
+
+function support() {
+ return membership({
+ boardId: 2,
+ boardName: "Support",
+ cardId: 201,
+ columnTitle: "Queued",
+ });
+}
+
+function topic(boardsMemberships) {
+ return EmberObject.create({ board_memberships: boardsMemberships });
+}
+
+function parse(html) {
+ const el = document.createElement("div");
+ el.innerHTML = html;
+ return el;
+}
+
+module("Boards | Unit | Lib | discourse-boards-topic-pill", function (hooks) {
+ setupTest(hooks);
+
+ test("renders the pill as a tag inside core's tag list", function (assert) {
+ const el = parse(renderTags(topic([sales()]), { mode: "list" }));
+ const pill = el.querySelector("a.discourse-boards-topic-pill");
+
+ assert.dom(pill).exists("renders a pill");
+ assert.dom(pill.parentElement).hasTagName("li");
+ assert.dom(pill.closest("ul")).hasClass("discourse-tags");
+ assert
+ .dom(pill)
+ .hasClass("discourse-tag", "reuses core's tag styling")
+ .hasAttribute("href", "/boards/sales/1?card=101")
+ .hasAttribute(
+ "title",
+ "This topic is in the In progress column of the Sales board"
+ )
+ .hasText("Sales");
+ });
+
+ test("titles the pill with a column count when a topic has several cards on one board", function (assert) {
+ const board = sales();
+ board.cards.push({
+ card_id: 102,
+ column_id: 12,
+ column_title: "Done",
+ column_color: "00aa66",
+ column_icon: "check",
+ });
+
+ const el = parse(renderTags(topic([board]), { mode: "list" }));
+
+ assert
+ .dom("a.discourse-boards-topic-pill", el)
+ .hasAttribute("title", "This topic is in 2 columns of the Sales board");
+ });
+
+ test("uses the Unicode column title", function (assert) {
+ const board = sales();
+ board.cards[0].column_title = "In progress :rocket:";
+ board.cards[0].unicode_column_title = "In progress πŸš€";
+
+ const el = parse(renderTags(topic([board]), { mode: "list" }));
+
+ assert
+ .dom("a.discourse-boards-topic-pill", el)
+ .hasAttribute(
+ "title",
+ "This topic is in the In progress πŸš€ column of the Sales board"
+ );
+ });
+
+ test("uses the Unicode board name for the pill label and title", function (assert) {
+ const board = membership({
+ boardId: 1,
+ boardName: "Sales :fire:",
+ unicodeBoardName: "Sales πŸ”₯",
+ cardId: 101,
+ columnTitle: "In progress",
+ });
+
+ const el = parse(renderTags(topic([board]), { mode: "list" }));
+
+ assert
+ .dom("a.discourse-boards-topic-pill", el)
+ .hasText("Sales πŸ”₯")
+ .hasAttribute(
+ "title",
+ "This topic is in the In progress column of the Sales πŸ”₯ board"
+ );
+ });
+
+ test("renders a single menu trigger carrying its boards when a topic is on several", function (assert) {
+ const memberships = [sales(), support()];
+ const el = parse(renderTags(topic(memberships)));
+ const trigger = el.querySelector("a.discourse-boards-topic-pill--multiple");
+
+ assert.dom(trigger.parentElement).hasTagName("li");
+ assert
+ .dom(trigger)
+ .hasClass("discourse-tag")
+ .hasAttribute("role", "button")
+ .hasAttribute("tabindex", "0")
+ .hasAttribute("aria-expanded", "false")
+ .doesNotHaveAttribute("href", "it opens a menu instead of navigating")
+ .hasText("2 boards");
+ assert.dom("a.discourse-boards-topic-pill", el).exists({ count: 1 });
+
+ // the boards ride along in data attributes, for the menu to read back
+ assert
+ .dom(trigger)
+ .hasAttribute("data-card-count", "2")
+ .hasAttribute("data-card-0-board-slug", "sales")
+ .hasAttribute("data-card-0-column-title", "In progress")
+ .hasAttribute("data-card-1-board-slug", "support");
+ assert.deepEqual(
+ membershipsFor(trigger),
+ memberships.map((board) => ({
+ board_id: board.board_id,
+ board_name: board.board_name,
+ board_slug: board.board_slug,
+ cards: board.cards.map((card) => ({
+ card_id: card.card_id,
+ column_title: card.column_title,
+ column_color: card.column_color,
+ column_icon: card.column_icon,
+ })),
+ }))
+ );
+ });
+
+ test("carries every column of a board a topic has several cards on", function (assert) {
+ const board = sales();
+ board.cards.push({
+ card_id: 102,
+ column_id: 12,
+ column_title: "Done",
+ column_color: "00aa66",
+ column_icon: "check",
+ });
+ const el = parse(renderTags(topic([board, support()])));
+ const trigger = el.querySelector("a.discourse-boards-topic-pill--multiple");
+
+ const [first] = membershipsFor(trigger);
+ assert.deepEqual(
+ first.cards.map((card) => card.column_title),
+ ["In progress", "Done"]
+ );
+ });
+
+ test("carries Unicode column titles for the multiple-board menu", function (assert) {
+ const board = sales();
+ board.cards[0].column_title = "In progress :rocket:";
+ board.cards[0].unicode_column_title = "In progress πŸš€";
+ const el = parse(renderTags(topic([board, support()])));
+ const trigger = el.querySelector("a.discourse-boards-topic-pill--multiple");
+
+ assert
+ .dom(trigger)
+ .hasAttribute("data-card-0-column-title", "In progress πŸš€");
+ assert.strictEqual(
+ membershipsFor(trigger)[0].cards[0].column_title,
+ "In progress πŸš€"
+ );
+ });
+
+ test("leaves out data for a column with no colour or icon", function (assert) {
+ const board = sales();
+ board.cards[0].column_color = null;
+ board.cards[0].column_icon = null;
+ const el = parse(renderTags(topic([board, support()])));
+ const trigger = el.querySelector("a.discourse-boards-topic-pill--multiple");
+
+ const [{ cards }] = membershipsFor(trigger);
+ assert.strictEqual(cards[0].column_color, undefined);
+ assert.strictEqual(cards[0].column_icon, undefined);
+ assert.strictEqual(cards[0].column_title, "In progress");
+ });
+
+ test("lists the boards instead of a menu when the caller wants inert markup", function (assert) {
+ const el = parse(
+ renderTags(topic([sales(), support()]), { tagName: "span" })
+ );
+
+ assert.dom(".discourse-boards-topic-pill--multiple", el).doesNotExist();
+ assert.dom(".discourse-tags__tag-separator", el).exists({ count: 1 });
+ assert.deepEqual(
+ [...el.querySelectorAll("span.discourse-boards-topic-pill")].map((pill) =>
+ pill.textContent.trim()
+ ),
+ ["Sales", "Support"]
+ );
+ });
+
+ test("renders nothing when the topic is not on a board", function (assert) {
+ assert.strictEqual(renderTags(topic([]), {}), "");
+ });
+});
diff --git a/plugins/boards/test/javascripts/unit/models/boards-title-test.js b/plugins/boards/test/javascripts/unit/models/boards-title-test.js
new file mode 100644
index 00000000000..e0f00dff23e
--- /dev/null
+++ b/plugins/boards/test/javascripts/unit/models/boards-title-test.js
@@ -0,0 +1,60 @@
+import { module, test } from "qunit";
+import Board from "discourse/plugins/boards/discourse/models/board";
+import Card from "discourse/plugins/boards/discourse/models/card";
+import Column from "discourse/plugins/boards/discourse/models/column";
+
+module("Unit | Models | Boards titles", function () {
+ test("board fancyTitle prefers the Unicode name", function (assert) {
+ const board = Board.create({
+ name: "Launch :rocket:",
+ unicode_name: "Launch πŸš€",
+ });
+
+ assert.strictEqual(board.fancyTitle, "Launch πŸš€");
+ assert.strictEqual(Board.create({ name: "Launch" }).fancyTitle, "Launch");
+ });
+
+ test("floater card fancyTitle prefers the Unicode title", function (assert) {
+ const card = Card.create({
+ card_type: "floater",
+ title: "Launch :rocket:",
+ unicode_title: "Launch πŸš€",
+ });
+
+ assert.strictEqual(card.fancyTitle, "Launch πŸš€");
+ });
+
+ test("topic card fancyTitle comes from its topic", function (assert) {
+ const card = Card.create({
+ card_type: "topic",
+ topic: {
+ title: "Topic :rocket:",
+ unicode_title: "Topic πŸš€",
+ },
+ });
+
+ assert.strictEqual(card.fancyTitle, "Topic πŸš€");
+ });
+
+ test("column fancyTitle prefers the Unicode title", function (assert) {
+ const column = Column.create({
+ title: "Doing :rocket:",
+ unicode_title: "Doing πŸš€",
+ });
+
+ assert.strictEqual(column.fancyTitle, "Doing πŸš€");
+ assert.strictEqual(Column.create({ title: "Doing" }).fancyTitle, "Doing");
+ });
+
+ test("copying models preserves their titles", function (assert) {
+ const column = Column.create({
+ title: "To Do :rocket:",
+ unicode_title: "To Do πŸš€",
+ cards: [],
+ }).copy({ cards: [{ id: 1, title: "Ship it" }] });
+ const card = column.cards[0].copy({ notes: "Ready" });
+
+ assert.strictEqual(column.fancyTitle, "To Do πŸš€");
+ assert.strictEqual(card.fancyTitle, "Ship it");
+ });
+});
diff --git a/plugins/boards/test/javascripts/unit/routes/boards-board-configure-test.js b/plugins/boards/test/javascripts/unit/routes/boards-board-configure-test.js
new file mode 100644
index 00000000000..b909d514c49
--- /dev/null
+++ b/plugins/boards/test/javascripts/unit/routes/boards-board-configure-test.js
@@ -0,0 +1,47 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+
+module("Unit | Route | boards-board-configure", function (hooks) {
+ setupTest(hooks);
+
+ test("redirects users who cannot manage the board", function (assert) {
+ const route = this.owner.lookup("route:boards-board-configure");
+ const replaceWith = sinon.stub(route.router, "replaceWith");
+
+ route.afterModel(
+ {
+ board: {
+ id: 42,
+ slug: "team-board",
+ can_manage: false,
+ },
+ },
+ { to: { params: { slug: "team-board" } } }
+ );
+
+ assert.deepEqual(
+ replaceWith.firstCall.args,
+ ["boardsBoard", "team-board", 42],
+ "the regular board route is used"
+ );
+ });
+
+ test("keeps managers on the configure route", function (assert) {
+ const route = this.owner.lookup("route:boards-board-configure");
+ const replaceWith = sinon.stub(route.router, "replaceWith");
+
+ route.afterModel(
+ {
+ board: {
+ id: 42,
+ slug: "team-board",
+ can_manage: true,
+ },
+ },
+ { to: { params: { slug: "team-board" } } }
+ );
+
+ assert.false(replaceWith.called, "no redirect occurs");
+ });
+});
diff --git a/plugins/boards/tsconfig.json b/plugins/boards/tsconfig.json
new file mode 100644
index 00000000000..f03b8f020ec
--- /dev/null
+++ b/plugins/boards/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "extends": "discourse/tsconfig-plugin",
+ "include": [
+ "admin/assets/javascripts/**/*",
+ "assets/javascripts/**/*",
+ "test/javascripts/**/*"
+ ],
+ "compilerOptions": {
+ "paths": {
+ "discourse/plugins/boards/*": ["./assets/javascripts/*"],
+ "discourse/plugins/boards/admin/*": ["./admin/assets/javascripts/admin/*"]
+ }
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 26e0600ec5c..61c64eafabf 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -131,7 +131,7 @@ importers:
version: 3.0.1([email protected])
'@rollup/browser':
specifier: ^4.63.0
- version: 4.63.0
+ version: 4.63.1
'@rollup/plugin-babel':
specifier: ^7.0.0
version: 7.1.0(@babel/[email protected])
@@ -194,11 +194,11 @@ importers:
version: 0.1.0
terser:
specifier: ^5.47.1
- version: 5.50.0
+ version: 5.48.0
devDependencies:
vitest:
specifier: ^4.1.9
frontend/deprecation-silencer: {}
@@ -504,7 +504,7 @@ importers:
version: 3.0.6(@babel/[email protected])(@embroider/[email protected](@glint/[email protected]))(@glint/[email protected])
'@embroider/vite':
specifier: ^1.7.10
'@floating-ui/dom':
specifier: ^1.7.5
version: 1.7.6
@@ -735,6 +735,12 @@ importers:
specifier: npm:@discourse/[email protected]
version: '@discourse/[email protected]'
+ plugins/boards:
+ dependencies:
+ discourse:
+ specifier: npm:@discourse/types@*
+ version: '@discourse/[email protected]'
+
plugins/chat:
dependencies:
discourse:
@@ -1035,8 +1041,8 @@ packages:
'@babel/core': ^8.0.0
eslint: ^9.0.0 || ^10.0.0
- '@babel/[email protected]':
- resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==}
engines: {node: '>=6.9.0'}
@@ -1164,8 +1170,8 @@ packages:
resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}
engines: {node: '>=6.9.0'}
- '@babel/[email protected]':
- resolution: {integrity: sha512-4wFaiLd0bVo4cIoTXI3zKI038NIWE/cr3jvBjejOVYVxV/m8Ltav1USiGzG1fmS5J2RhgEOgXNNK46cRPnRsrg==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-9Fr9QeyCAyi1BR1jKZ6uYQ24EIhQUx5ReHfQU7drOE+TPOb+w11/dsqLkMOT2U29OdCT71XajrOT8xDc1C7orA==}
engines: {node: ^22.18.0 || >=24.11.0}
@@ -1188,13 +1194,13 @@ packages:
resolution: {integrity: sha512-wfbi91pM3py96oIiJEz7qIpyXDytgr9zQC1HEWwlGNVRAEmItuU/0a41ZUKu1sJGyhhOIpc4t5vk4PYzt8wpsg==}
engines: {node: ^22.18.0 || >=24.11.0}
- '@babel/[email protected]':
- resolution: {integrity: sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==}
engines: {node: '>=6.0.0'}
hasBin: true
- '@babel/[email protected]':
- resolution: {integrity: sha512-srpptsAkEbbNIC/q8nT7o+m6CQe8CJUTV/t7MYc9NnWlgYVtHOb7JH6SorxMhN0kuRJjVqXbKClG6xSbPtzz+g==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-aLxAE+imI9bCcyaPrUDjBv3uSkWieifjLe0kuFOZF0zli0L6GCsTmsePnTr55adbIAgYz2zhN1vnFimCBUYcRQ==}
engines: {node: ^22.18.0 || >=24.11.0}
hasBin: true
@@ -1672,20 +1678,20 @@ packages:
resolution: {integrity: sha512-eAD0QW/AlbamBbw0FeGiwasbCVPq5ncW0HNVyLP3B9czqLyh4gvw+5JTSNt6le9+ziAU7mqDZsKTHf3jTb4chQ==}
engines: {node: ^22.18.0 || >=24.11.0}
- '@babel/[email protected]':
- resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==}
engines: {node: '>=6.9.0'}
- '@babel/[email protected]':
- resolution: {integrity: sha512-bZnmqzGG8UZneG1lLxBoWIH0G6Gr1D846Yu4/3XnY6FhCndMR49u26nTY08u/dAxWmLWF9vGQOuC+84FfIUoeg==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-bxTj/W2VclGE6CctlfQOpxg8MPDzXArRqkOBePw8EHfebcjF7fETWSS3BriEECo+UiU/Yblq+xUtSImFu7cTbw==}
engines: {node: ^22.18.0 || >=24.11.0}
- '@babel/[email protected]':
- resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==}
engines: {node: '>=6.9.0'}
- '@babel/[email protected]':
- resolution: {integrity: sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g==}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-K8ponJDxBwDHigkeFqaqT5wLGl4bTlwMafR8k7b5CPxr6Ww+UG9ls8Yx6Tcpboxu97eeGVEEyKcHmEyOwN1vSw==}
engines: {node: ^22.18.0 || >=24.11.0}
'@blueoak/[email protected]':
@@ -2422,6 +2428,12 @@ packages:
'@microsoft/[email protected]':
resolution: {integrity: sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==}
+ '@napi-rs/[email protected]':
+ resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
+ peerDependencies:
+ '@emnapi/core': ^1.7.1
+ '@emnapi/runtime': ^1.7.1
+
'@napi-rs/[email protected]':
resolution: {integrity: sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==}
peerDependencies:
@@ -2853,8 +2865,8 @@ packages:
'@rolldown/[email protected]':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
- '@rollup/[email protected]':
- resolution: {integrity: sha512-pIfhDqHdIEJi4MwYr/0BrjiAjK3nRSo4NE/Ng9gmzMmjS1aJSSHg5T2OQFHnh6mfF8Z0DhqY86BPP+IhKr+PcQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-qsJijWUL79BPPzuVazW3E/tVQAkSMmjHVk/NQfRbr3BmviFqwxPb7twF0RfneJqebBikfAL2RxXGvzC6O1JEqg==}
'@rollup/[email protected]':
resolution: {integrity: sha512-h9Y+xYha6p4wKO+FwdiPIkE+eIYCm8MzZPpX1iARIoFBnmKP9CnpT1p9dDf/DTFm6fyN8PmuLyRI5qZgchnitw==}
@@ -2944,6 +2956,9 @@ packages:
resolution: {integrity: sha512-92F7/SFyufn4DXsha9+QfKnN03JGqtMFMXgSHbZOo8JG59WkTni7UzAouNQDf7AuP9OAMxVOPQcqG3sB7w+kkg==}
engines: {node: ^16.14.0 || >=18.0.0}
+ '@tybys/[email protected]':
+ resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
+
resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==}
@@ -3221,7 +3236,6 @@ packages:
'@xmldom/[email protected]':
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
- deprecated: this version has critical issues, please update to the latest version
resolution: {integrity: sha512-SlFk3QSqeuvmN/anaIteUkB6ipBHoG1jq5gfQZU2kqvbkDW3Iab7SNufj4io4e8StvuIshD+loJnsQgTEvq6dA==}
@@ -3249,8 +3263,8 @@ packages:
peerDependencies:
acorn: ^6.0.0 || ^7.0.0 || ^8.0.0
- resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==}
+ resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==}
engines: {node: '>=0.4.0'}
hasBin: true
@@ -3550,8 +3564,8 @@ packages:
resolution: {integrity: sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==}
engines: {node: ^4.5.0 || >= 5.9}
- resolution: {integrity: sha512-Grytf1xOxOEMTGRwx6rLGKkTabd4vMg3VrKdj/7joCmV0qgh4QwMMO6xh34YEXQqirAuUdgQGa5orJQQ+69RBw==}
+ resolution: {integrity: sha512-girxaJ7WZssDOFhzCGZTDKoTa1gk6A1TbflaYTpykLJ4UU9Fz9kx1aREM8JCuoVHbL8X8T/mJg7w2oYSq72Oig==}
engines: {node: '>=6.0.0'}
hasBin: true
@@ -3596,15 +3610,15 @@ packages:
resolution: {integrity: sha512-chUsBxGRtuElD6fmw1gHLpvnKdVLK302peeFa9ZqAEk8TyzZ3fygLyUEDDPTJvL9+Bor0dIwn6ePOsRM2y0zQQ==}
- resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==}
+ resolution: {integrity: sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==}
- resolution: {integrity: sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==}
+ resolution: {integrity: sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==}
- resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==}
- engines: {node: 20 || >=22}
+ resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==}
+ engines: {node: 18 || 20 || >=22}
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
@@ -3614,11 +3628,11 @@ packages:
resolution: {integrity: sha512-6IXBgfRt7HZ61g67ssBc6lBb3Smw3DPZ9dEYirgtvXWpRZ2A9M22nxy6opEwJDgDJzlu/bB7ToppW33OFkA1gA==}
engines: {node: '>= 6'}
- resolution: {integrity: sha512-ca3QcjNzX7umqQ06PeDDjAf2WJ9DcgzoECuXT638YDpNC+gCJeoDDKYk0KieeE7VeX7YHyrkfyynQzMvZZ/4ew==}
+ resolution: {integrity: sha512-XIGsUyJgehSRNVVrOnRuW+tijYBqkoGEONc/UHkiOBW+C0trPv9c/Icc/Cf+2l1McQlHW/Mc6SksHg6qFlEClg==}
engines: {node: 16.* || >= 18}
peerDependencies:
- '@babel/core': ^7.17.9 || ^8.0.0
+ '@babel/core': ^7.17.9
resolution: {integrity: sha512-3TWi92ogzUhLmCF5V4DjhN7v4t6OjXYO21p9GkuOZQ1SiVmM1sYio364y64dREHUzjFEcH8mdVCiRDdrwUGVTw==}
@@ -3674,9 +3688,6 @@ packages:
resolution: {integrity: sha512-bQAtwjSrF4Nu0CK0JOy5OZqw9t5U0zzv2555EA/cF8/a8SLDTIetk9UgrtMVw7qKLKdSpOZ2liZNeZZDaKgayw==}
engines: {node: 10.* || >= 12.*}
- resolution: {integrity: sha512-0RejLwoC95kv4kta8KAa+FmECJCK78Qgm8SRDEK7YyU0N9Cx6KpY3UCDy9WELl3mCXLN8TokNxc7/hp3lL4lfw==}
-
resolution: {integrity: sha512-hVsmIgCDrl2NFM+3Gs4Cr2TA6UPaIZip99hN8mtkaUPgM8UeVnCbxelCvBjUBHo0oaaqP5jzqqnRVvb568Yu5g==}
engines: {node: 6.* || >= 8.*}
@@ -3711,9 +3722,6 @@ packages:
resolution: {integrity: sha512-NXfi+Vas24n3Ivo21GvENTI55qxKu7OwKRnCLWXld8MiLiQKQlWIq28eoARaFj0lTUFwUa4jKZeA7fW9PiWQeg==}
engines: {node: 8.* || >= 10.*}
- resolution: {integrity: sha512-QHESTrrrPlKuXQNWsvXawSQbV2g34wCZ5oKgd6bntdOuN8VHxbg1BCBHqVY5HxXJhWelimgGxj3vI7ECkyij8g==}
-
resolution: {integrity: sha512-p5el5/ig0QeRGFPkLMPdm7KblkTm44eicEWfwnRTz6hncghVuRZ0+XDAtCi7ynxobeE/mey5Q7lAulFkgNzxVA==}
engines: {node: '>= 20.19.*'}
@@ -3725,8 +3733,8 @@ packages:
peerDependencies:
browserslist: '*'
- resolution: {integrity: sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==}
+ resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
hasBin: true
@@ -3777,8 +3785,8 @@ packages:
resolution: {integrity: sha512-RbsNrFyhwkx+6psk/0fK/Q9orOUr9VMxohGd8vTa4djf4TGLfblBgUfqZChrZuW0Q+mz2eBPFLusw9Jfukzmhg==}
hasBin: true
- resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==}
+ resolution: {integrity: sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==}
resolution: {integrity: sha512-PiT/hQmTonHhl/HFGN+Lx3JJUznrVYJ3+AQsnthneZbvW7x+f08Tk7yLJTLEOUvBTbduLeeBkxEaYXUOUrRq6g==}
@@ -4385,8 +4393,8 @@ packages:
engines: {node: '>=0.10.0'}
hasBin: true
- resolution: {integrity: sha512-aYlviXiaXBbzvKgyALpcMmqa3Np3sDr0XnZbEG62n2UpZFbEcjQ4EEMOLGzVPhwVnwTz0lvKY+GcARbunuHekw==}
+ resolution: {integrity: sha512-G2Hym8JIf/QreuseqkDibgH8Ci8KfJzqGDKdakbhSx9UltwRBH2cBLAWU/lBX0sCdv0TlhyxQyDCnSfxgMWsjA==}
resolution: {integrity: sha512-yCQlVR3NLgjGA09LMc1NYX0XiAd0tHTM4/AmIHD0wq87QpHGmWcpMxyKGEe/TBczyCwBEJifaZNtAjMDsW1YdA==}
@@ -4407,8 +4415,8 @@ packages:
resolution: {integrity: sha512-JJYeYjiz/JTn34q7F5DSOjkkZqy8qwFOOxXfE6pe9yEJqWGu4qErKxlz8I22JoVEQ/aBUO+OcKTpmctvykM9YA==}
engines: {node: 6.* || 8.* || >= 10.*}
- resolution: {integrity: sha512-Thvqx+jwGYhimYbkkL0gwhwMlhghTIR3uQ9R0yNaTjBIttZIfSWJ/2W40kaJlwhnsElXq7zbFjZcff22p6nzCg==}
+ resolution: {integrity: sha512-Pxm5JP0jQ6fCBlXuh1BFmhrg2/5YXjhf16JI/n8ReOR6Nl+fEbudMpdO69LlqZRsMmTgdjCRmfSxMh26Wsw/rw==}
engines: {node: 16.* || 18.* || >= 20}
peerDependencies:
'@babel/core': ^7.12.0
@@ -5393,8 +5401,8 @@ packages:
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}
+ resolution: {integrity: sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==}
engines: {node: '>=0.10.0'}
@@ -6276,8 +6284,8 @@ packages:
resolution: {integrity: sha512-ygvf5JIR4NT1LbM6o8z1oz1icTkta72gXKwidvSqIVxuzVd/P21UI0Wbq1J+MStAu50Vvr8qWYNSz1W4uycqMQ==}
- resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}
+ resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@ -6352,9 +6360,9 @@ packages:
engines: {node: '>=10'}
hasBin: true
- resolution: {integrity: sha512-SGFVW+UHYZlNGkFfMHev141IUTDh47r/t0yb1sZxrSect6+E88anirPFAiBA/aH/VSESYQ7AWpE2hzLIxf9ILA==}
- engines: {node: 20 || 22 || 24 || 26}
+ resolution: {integrity: sha512-Bq72L2oi/isYSy0guN9ihNhAMQOyZEwts+Bezm/1U+wh8bQ+fVQ2ZiUoJJjceOMiiKv/BUrA0NF98jFc81CB6w==}
+ engines: {node: 20 || 22 || 24}
resolution: {integrity: sha512-lDsQv8FoGdBUdf0+TjGsq2orxKuXdwFlQ6Zw6TX3xIcTwTfEpCLyKqvEauvCHJ8iu3KBV8+uPhlv70YsNGdUBQ==}
@@ -6428,8 +6436,8 @@ packages:
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
- resolution: {integrity: sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ==}
+ resolution: {integrity: sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==}
engines: {node: '>=18'}
@@ -7053,8 +7061,8 @@ packages:
resolution: {integrity: sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==}
- resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==}
+ resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
engines: {node: '>= 0.6'}
@@ -7383,8 +7391,8 @@ packages:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
- resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}
+ resolution: {integrity: sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==}
engines: {node: '>=10'}
hasBin: true
@@ -7833,8 +7841,8 @@ packages:
resolution: {integrity: sha512-HAixuesxFQIUaQk3ptX2jhfO/FsOkgVkDDMawvp6n/fkB1q6BKfs3lURw9I+pK/2e2e/q/vrLrxmeqauBoyGMQ==}
- resolution: {integrity: sha512-CN9BVxWhgS/hRxtUMjtC2uRWSTcSfQFHMDWma6sKKfIivCD91sM+FOPfvwoaRMqCSrUpe1nv3jDamd9eEQ4y+w==}
+ resolution: {integrity: sha512-J/9An6vs9Us6wKRriSFXBWdRZapREHqFzdNUKk0pmu804EMR6dr6winwo7e5JDxN4xahxQsuysyYFwlwj4XN/Q==}
engines: {node: '>=10'}
hasBin: true
@@ -8096,8 +8104,8 @@ packages:
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
engines: {node: '>= 0.8'}
- resolution: {integrity: sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==}
+ resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
hasBin: true
peerDependencies:
browserslist: '>= 4.21.0'
@@ -8426,8 +8434,8 @@ packages:
utf-8-validate:
optional: true
- resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==}
+ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
engines: {node: '>=10.0.0'}
peerDependencies:
bufferutil: ^4.0.1
@@ -8538,7 +8546,7 @@ snapshots:
dependencies:
- '@babel/helper-validator-identifier': 8.0.4
+ '@babel/helper-validator-identifier': 8.0.2
js-tokens: 10.0.0
'@babel/[email protected]': {}
@@ -8548,14 +8556,14 @@ snapshots:
dependencies:
'@babel/code-frame': 7.29.7
- '@babel/generator': 7.29.8
+ '@babel/generator': 7.29.7
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
'@babel/helpers': 7.29.7
- '@babel/parser': 7.29.8
+ '@babel/parser': 7.29.7
'@babel/template': 7.29.7
- '@babel/traverse': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/traverse': 7.29.7
+ '@babel/types': 7.29.7
'@jridgewell/remapping': 2.3.5
convert-source-map: 2.0.0
debug: 4.4.3
@@ -8571,10 +8579,10 @@ snapshots:
'@babel/generator': 8.0.0
'@babel/helper-compilation-targets': 8.0.0
'@babel/helpers': 8.0.0
- '@babel/parser': 8.0.4
+ '@babel/parser': 8.0.0
'@babel/template': 8.0.0
- '@babel/traverse': 8.0.4
- '@babel/types': 8.0.4
+ '@babel/traverse': 8.0.0
+ '@babel/types': 8.0.0
'@types/gensync': 1.0.5
convert-source-map: 2.0.0
empathic: 2.0.1
@@ -8582,7 +8590,7 @@ snapshots:
import-meta-resolve: 4.2.0
json5: 2.2.3
obug: 2.1.3
- semver: 7.8.5
+ semver: 7.8.4
dependencies:
@@ -8590,20 +8598,20 @@ snapshots:
eslint: 10.6.0([email protected])
eslint-scope: 9.1.2
eslint-visitor-keys: 5.0.1
- semver: 7.8.5
+ semver: 7.8.4
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
- '@babel/parser': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/parser': 7.29.7
+ '@babel/types': 7.29.7
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
jsesc: 3.1.0
dependencies:
- '@babel/parser': 8.0.4
- '@babel/types': 8.0.4
+ '@babel/parser': 8.0.0
+ '@babel/types': 8.0.0
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.31
'@types/jsesc': 2.5.1
@@ -8611,17 +8619,17 @@ snapshots:
dependencies:
- '@babel/types': 7.29.8
+ '@babel/types': 7.29.7
dependencies:
- '@babel/types': 8.0.4
+ '@babel/types': 8.0.0
dependencies:
'@babel/compat-data': 7.29.7
'@babel/helper-validator-option': 7.29.7
- browserslist: 4.28.8
+ browserslist: 4.28.2
lru-cache: 5.1.1
semver: 6.3.1
@@ -8629,9 +8637,9 @@ snapshots:
dependencies:
'@babel/compat-data': 8.0.0
'@babel/helper-validator-option': 8.0.0
- browserslist: 4.28.8
+ browserslist: 4.28.2
lru-cache: 11.5.1
- semver: 7.8.5
+ semver: 7.8.4
dependencies:
@@ -8641,7 +8649,7 @@ snapshots:
'@babel/helper-optimise-call-expression': 7.29.7
'@babel/helper-replace-supers': 7.29.7(@babel/[email protected])
'@babel/helper-skip-transparent-expression-wrappers': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
semver: 6.3.1
transitivePeerDependencies:
- supports-color
@@ -8654,8 +8662,8 @@ snapshots:
'@babel/helper-optimise-call-expression': 8.0.0
'@babel/helper-replace-supers': 8.0.1(@babel/[email protected])
'@babel/helper-skip-transparent-expression-wrappers': 8.0.0
- '@babel/traverse': 8.0.4
- semver: 7.8.5
+ '@babel/traverse': 8.0.0
+ semver: 7.8.4
dependencies:
@@ -8681,20 +8689,20 @@ snapshots:
dependencies:
- '@babel/traverse': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/traverse': 7.29.7
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/traverse': 8.0.4
- '@babel/types': 8.0.4
+ '@babel/traverse': 8.0.0
+ '@babel/types': 8.0.0
dependencies:
- '@babel/traverse': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/traverse': 7.29.7
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8703,17 +8711,17 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-module-imports': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/types': 7.29.8
+ '@babel/types': 7.29.7
dependencies:
- '@babel/types': 8.0.4
+ '@babel/types': 8.0.0
'@babel/[email protected]': {}
@@ -8726,7 +8734,7 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-annotate-as-pure': 7.29.7
'@babel/helper-wrap-function': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8735,7 +8743,7 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-member-expression-to-functions': 7.29.7
'@babel/helper-optimise-call-expression': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8744,19 +8752,19 @@ snapshots:
'@babel/core': 8.0.1
'@babel/helper-member-expression-to-functions': 8.0.0
'@babel/helper-optimise-call-expression': 8.0.0
- '@babel/traverse': 8.0.4
+ '@babel/traverse': 8.0.0
dependencies:
- '@babel/traverse': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/traverse': 7.29.7
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
- '@babel/traverse': 8.0.4
- '@babel/types': 8.0.4
+ '@babel/traverse': 8.0.0
+ '@babel/types': 8.0.0
'@babel/[email protected]': {}
@@ -8764,7 +8772,7 @@ snapshots:
'@babel/[email protected]': {}
- '@babel/[email protected]': {}
+ '@babel/[email protected]': {}
'@babel/[email protected]': {}
@@ -8773,34 +8781,34 @@ snapshots:
dependencies:
'@babel/template': 7.29.7
- '@babel/traverse': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/traverse': 7.29.7
+ '@babel/types': 7.29.7
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/template': 7.29.7
- '@babel/types': 7.29.8
+ '@babel/types': 7.29.7
dependencies:
'@babel/template': 8.0.0
- '@babel/types': 8.0.4
+ '@babel/types': 8.0.0
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
- '@babel/types': 7.29.8
+ '@babel/types': 7.29.7
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
- '@babel/types': 8.0.4
+ '@babel/types': 8.0.0
dependencies:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8835,7 +8843,7 @@ snapshots:
dependencies:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8936,7 +8944,7 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
'@babel/helper-remap-async-to-generator': 7.29.7(@babel/[email protected])
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8983,7 +8991,7 @@ snapshots:
'@babel/helper-globals': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
'@babel/helper-replace-supers': 7.29.7(@babel/[email protected])
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -8997,7 +9005,7 @@ snapshots:
dependencies:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -9054,7 +9062,7 @@ snapshots:
'@babel/core': 7.29.7
'@babel/helper-compilation-targets': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -9100,7 +9108,7 @@ snapshots:
'@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
'@babel/helper-plugin-utils': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -9140,7 +9148,7 @@ snapshots:
'@babel/helper-plugin-utils': 7.29.7
'@babel/plugin-transform-destructuring': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-parameters': 7.29.7(@babel/[email protected])
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
transitivePeerDependencies:
- supports-color
@@ -9368,7 +9376,7 @@ snapshots:
dependencies:
'@babel/core': 7.29.7
'@babel/helper-plugin-utils': 7.29.7
- '@babel/types': 7.29.8
+ '@babel/types': 7.29.7
esutils: 2.0.3
@@ -9382,46 +9390,46 @@ snapshots:
dependencies:
'@babel/code-frame': 7.29.7
- '@babel/parser': 7.29.8
- '@babel/types': 7.29.8
+ '@babel/parser': 7.29.7
+ '@babel/types': 7.29.7
dependencies:
'@babel/code-frame': 8.0.0
- '@babel/parser': 8.0.4
- '@babel/types': 8.0.4
+ '@babel/parser': 8.0.0
+ '@babel/types': 8.0.0
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
'@babel/code-frame': 7.29.7
- '@babel/generator': 7.29.8
+ '@babel/generator': 7.29.7
'@babel/helper-globals': 7.29.7
- '@babel/parser': 7.29.8
+ '@babel/parser': 7.29.7
'@babel/template': 7.29.7
- '@babel/types': 7.29.8
+ '@babel/types': 7.29.7
debug: 4.4.3
transitivePeerDependencies:
- supports-color
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
'@babel/code-frame': 8.0.0
'@babel/generator': 8.0.0
'@babel/helper-globals': 8.0.0
- '@babel/parser': 8.0.4
+ '@babel/parser': 8.0.0
'@babel/template': 8.0.0
- '@babel/types': 8.0.4
+ '@babel/types': 8.0.0
obug: 2.1.3
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
- '@babel/[email protected]':
+ '@babel/[email protected]':
dependencies:
'@babel/helper-string-parser': 8.0.0
- '@babel/helper-validator-identifier': 8.0.4
+ '@babel/helper-validator-identifier': 8.0.2
'@blueoak/[email protected]': {}
@@ -9714,7 +9722,7 @@ snapshots:
dependencies:
'@babel/core': 7.29.7
'@embroider/macros': 1.20.6(@babel/[email protected])(@glint/[email protected])
- ember-cli-babel: 8.3.2(@babel/[email protected])
+ ember-cli-babel: 8.3.1(@babel/[email protected])
ember-modifier-manager-polyfill: 1.2.0(@babel/[email protected])
ember-source: 6.10.1(patch_hash=85ff9a16d08431e3bdc9aea8d55280e14f437f1c2a7d8e461de56c614ad48926)(@glimmer/[email protected])([email protected])
optionalDependencies:
@@ -9750,7 +9758,7 @@ snapshots:
'@embroider/shared-internals': 3.1.1
broccoli-funnel: 3.0.8
common-ancestor-path: 1.0.1
- semver: 7.8.5
+ semver: 7.8.4
transitivePeerDependencies:
- supports-color
@@ -9764,7 +9772,7 @@ snapshots:
'@babel/plugin-transform-runtime': 7.29.7(@babel/[email protected])
'@babel/preset-env': 7.29.7(@babel/[email protected])
'@babel/runtime': 7.29.7
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
'@embroider/core': 4.6.3(@glint/[email protected])
'@embroider/macros': 1.20.4(@babel/[email protected])(@glint/[email protected])
'@types/babel__code-frame': 7.27.0
@@ -9795,7 +9803,7 @@ snapshots:
resolve: 1.22.12
resolve-package-path: 4.0.3
resolve.exports: 2.0.3
- semver: 7.8.5
+ semver: 7.8.4
symlink-or-copy: 1.3.1
tree-sync: 2.1.0
typescript-memoize: 1.1.1
@@ -9812,8 +9820,8 @@ snapshots:
'@embroider/[email protected](@glint/[email protected])':
dependencies:
'@babel/core': 7.29.7
- '@babel/parser': 7.29.8
- '@babel/traverse': 7.29.8
+ '@babel/parser': 7.29.7
+ '@babel/traverse': 7.29.7
'@embroider/macros': 1.20.6(@babel/[email protected])(@glint/[email protected])
'@embroider/reverse-exports': 0.2.0
'@embroider/shared-internals': 3.1.1
@@ -9835,7 +9843,7 @@ snapshots:
resolve: 1.22.12
resolve-package-path: 4.0.3
resolve.exports: 2.0.3
- semver: 7.8.5
+ semver: 7.8.4
typescript-memoize: 1.1.1
walk-sync: 3.0.0
transitivePeerDependencies:
@@ -9856,11 +9864,11 @@ snapshots:
'@embroider/shared-internals': 3.1.1
assert-never: 1.4.0
babel-import-util: 3.0.1
- ember-cli-babel: 8.3.2(@babel/[email protected])
+ ember-cli-babel: 8.3.1(@babel/[email protected])
find-up: 5.0.0
lodash: 4.18.1
resolve: 1.22.12
- semver: 7.8.5
+ semver: 7.8.4
optionalDependencies:
'@glint/template': 1.7.8
transitivePeerDependencies:
@@ -9872,11 +9880,11 @@ snapshots:
'@embroider/shared-internals': 3.1.1
assert-never: 1.4.0
babel-import-util: 3.0.1
- ember-cli-babel: 8.3.2(@babel/[email protected])
+ ember-cli-babel: 8.3.1(@babel/[email protected])
find-up: 5.0.0
lodash: 4.18.1
resolve: 1.22.12
- semver: 7.8.5
+ semver: 7.8.4
optionalDependencies:
'@glint/template': 1.7.8
transitivePeerDependencies:
@@ -9911,7 +9919,7 @@ snapshots:
minimatch: 3.1.5
pkg-entry-points: 1.1.2
resolve-package-path: 4.0.3
- semver: 7.8.5
+ semver: 7.8.4
typescript-memoize: 1.1.1
transitivePeerDependencies:
- supports-color
@@ -9929,20 +9937,20 @@ snapshots:
pkg-entry-points: 1.1.2
resolve-package-path: 4.0.3
resolve.exports: 2.0.3
- semver: 7.8.5
+ semver: 7.8.4
typescript-memoize: 1.1.1
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.7
'@embroider/core': 4.6.3(@glint/[email protected])
'@embroider/macros': 1.20.6(@babel/[email protected])(@glint/[email protected])
'@embroider/reverse-exports': 0.2.0
assert-never: 1.4.0
- browserslist: 4.28.8
- browserslist-to-esbuild: 2.1.1([email protected])
+ browserslist: 4.28.2
+ browserslist-to-esbuild: 2.1.1([email protected])
chalk: 5.6.2
content-tag: 4.2.0
debug: 4.4.3
@@ -9951,8 +9959,8 @@ snapshots:
jsdom: 25.0.1
send: 1.2.1
source-map-url: 0.4.1
- terser: 5.50.0
+ terser: 5.48.0
transitivePeerDependencies:
- '@glint/template'
- bufferutil
@@ -9987,7 +9995,7 @@ snapshots:
dependencies:
'@eslint/object-schema': 3.0.5
debug: 4.4.3
- minimatch: 10.2.6
+ minimatch: 10.2.5
transitivePeerDependencies:
- supports-color
@@ -10301,7 +10309,7 @@ snapshots:
dependencies:
chardet: 2.1.1
- iconv-lite: 0.7.3
+ iconv-lite: 0.7.2
optionalDependencies:
'@types/node': 25.9.1
@@ -10458,6 +10466,13 @@ snapshots:
'@microsoft/[email protected]': {}
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@tybys/wasm-util': 0.10.2
+ optional: true
+
dependencies:
'@emnapi/core': 1.10.0
@@ -10520,7 +10535,7 @@ snapshots:
promise-all-reject-late: 1.0.1
promise-call-limit: 3.0.2
read-package-json-fast: 3.0.2
- semver: 7.8.5
+ semver: 7.8.4
ssri: 10.0.6
treeverse: 3.0.0
walk-up-path: 3.0.1
@@ -10530,7 +10545,7 @@ snapshots:
'@npmcli/[email protected]':
dependencies:
- semver: 7.8.5
+ semver: 7.8.4
'@npmcli/[email protected]':
dependencies:
@@ -10541,7 +10556,7 @@ snapshots:
proc-log: 4.2.0
promise-inflight: 1.0.1
promise-retry: 2.0.1
- semver: 7.8.5
+ semver: 7.8.4
which: 4.0.0
transitivePeerDependencies:
- bluebird
@@ -10564,7 +10579,7 @@ snapshots:
json-parse-even-better-errors: 3.0.2
pacote: 18.0.6
proc-log: 4.2.0
- semver: 7.8.5
+ semver: 7.8.4
transitivePeerDependencies:
- bluebird
- supports-color
@@ -10581,7 +10596,7 @@ snapshots:
json-parse-even-better-errors: 3.0.2
normalize-package-data: 6.0.2
proc-log: 4.2.0
- semver: 7.8.5
+ semver: 7.8.4
transitivePeerDependencies:
- bluebird
@@ -10782,7 +10797,7 @@ snapshots:
dependencies:
'@emnapi/core': 1.10.0
'@emnapi/runtime': 1.10.0
- '@napi-rs/wasm-runtime': 1.1.6(@emnapi/[email protected])(@emnapi/[email protected])
+ '@napi-rs/wasm-runtime': 1.1.5(@emnapi/[email protected])(@emnapi/[email protected])
optional: true
'@rolldown/[email protected]':
@@ -10799,7 +10814,7 @@ snapshots:
'@rolldown/[email protected]': {}
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
dependencies:
'@types/estree': 1.0.9
@@ -10888,6 +10903,11 @@ snapshots:
'@tufjs/canonical-json': 2.0.0
minimatch: 9.0.9
+ '@tybys/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
dependencies:
tslib: 2.8.1
@@ -11063,8 +11083,8 @@ snapshots:
'@typescript-eslint/types': 8.56.1
'@typescript-eslint/visitor-keys': 8.56.1
debug: 4.4.3
- minimatch: 10.2.6
- semver: 7.8.5
+ minimatch: 10.2.5
+ semver: 7.8.4
tinyglobby: 0.2.17
ts-api-utils: 2.5.0([email protected])
typescript: 5.9.3
@@ -11078,8 +11098,8 @@ snapshots:
'@typescript-eslint/types': 8.62.1
'@typescript-eslint/visitor-keys': 8.62.1
debug: 4.4.3
- minimatch: 10.2.6
- semver: 7.8.5
+ minimatch: 10.2.5
+ semver: 7.8.4
tinyglobby: 0.2.17
ts-api-utils: 2.5.0([email protected])
typescript: 5.9.3
@@ -11169,13 +11189,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
dependencies:
'@vitest/spy': 4.1.9
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
'@vitest/[email protected]':
dependencies:
@@ -11272,11 +11292,11 @@ snapshots:
dependencies:
- acorn: 8.18.0
+ acorn: 8.17.0
@@ -11448,8 +11468,8 @@ snapshots:
dependencies:
- browserslist: 4.28.8
- caniuse-lite: 1.0.30001810
+ browserslist: 4.28.2
+ caniuse-lite: 1.0.30001799
fraction.js: 5.3.4
picocolors: 1.1.1
postcss: 8.5.26
@@ -11487,7 +11507,7 @@ snapshots:
dependencies:
'@babel/core': 7.29.7
babel-import-util: 2.1.1
- semver: 7.8.5
+ semver: 7.8.4
dependencies:
@@ -11597,7 +11617,7 @@ snapshots:
dependencies:
@@ -11638,7 +11658,7 @@ snapshots:
content-type: 1.0.5
debug: 4.4.3
http-errors: 2.0.1
- iconv-lite: 0.7.3
+ iconv-lite: 0.7.2
on-finished: 2.4.1
qs: 6.15.2
raw-body: 3.0.2
@@ -11653,16 +11673,16 @@ snapshots:
raw-body: 1.1.7
safe-json-parse: 1.0.1
dependencies:
balanced-match: 1.0.2
concat-map: 0.0.1
dependencies:
balanced-match: 1.0.2
dependencies:
balanced-match: 4.0.4
@@ -11687,7 +11707,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.7
broccoli-persistent-filter: 3.1.3
@@ -11819,24 +11839,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- async-disk-cache: 1.3.5
- async-promise-queue: 1.0.5
- broccoli-plugin: 1.3.1
- fs-tree-diff: 0.5.9
- hash-for-dep: 1.5.2
- heimdalljs: 0.2.6
- heimdalljs-logger: 0.1.10
- mkdirp: 0.5.6
- promise-map-series: 0.2.3
- rimraf: 2.7.1
- rsvp: 3.6.2
- symlink-or-copy: 1.3.1
- walk-sync: 0.3.4
- transitivePeerDependencies:
- - supports-color
-
dependencies:
async-disk-cache: 1.3.5
@@ -11927,13 +11929,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- broccoli-persistent-filter: 1.4.6
- minimatch: 3.1.5
- transitivePeerDependencies:
- - supports-color
-
dependencies:
ansi-html: 0.0.9
@@ -11957,18 +11952,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
- browserslist: 4.28.8
+ browserslist: 4.28.2
meow: 13.2.0
dependencies:
- baseline-browser-mapping: 2.11.19
- caniuse-lite: 1.0.30001810
- electron-to-chromium: 1.5.414
- node-releases: 2.0.53
- update-browserslist-db: 1.3.1([email protected])
+ baseline-browser-mapping: 2.10.37
+ caniuse-lite: 1.0.30001799
+ electron-to-chromium: 1.5.373
+ node-releases: 2.0.47
+ update-browserslist-db: 1.2.3([email protected])
dependencies:
@@ -12035,7 +12030,7 @@ snapshots:
dependencies:
tmp: 0.0.28
dependencies:
@@ -12279,7 +12274,7 @@ snapshots:
dependencies:
- browserslist: 4.28.8
+ browserslist: 4.28.2
@@ -12330,7 +12325,7 @@ snapshots:
postcss-modules-values: 4.0.0([email protected])
postcss-value-parser: 4.2.0
schema-utils: 3.3.0
- semver: 7.8.5
+ semver: 7.8.4
dependencies:
@@ -12469,8 +12464,8 @@ snapshots:
dependencies:
'@one-ini/wasm': 0.2.1
commander: 14.0.3
- minimatch: 10.2.6
- semver: 7.8.5
+ minimatch: 10.2.5
+ semver: 7.8.4
@@ -12478,7 +12473,7 @@ snapshots:
dependencies:
jake: 10.9.4
dependencies:
@@ -12525,7 +12520,7 @@ snapshots:
pkg-entry-points: 1.1.2
resolve: 1.22.12
resolve-package-path: 4.0.3
- semver: 7.8.5
+ semver: 7.8.4
style-loader: 2.0.0
typescript-memoize: 1.1.1
walk-sync: 3.0.0
@@ -12579,7 +12574,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@babel/core': 7.29.7
'@babel/helper-compilation-targets': 7.29.7
@@ -12592,24 +12587,23 @@ snapshots:
'@babel/plugin-transform-runtime': 7.29.7(@babel/[email protected])
'@babel/plugin-transform-typescript': 7.29.7(@babel/[email protected])
'@babel/preset-env': 7.29.7(@babel/[email protected])
- '@babel/runtime': 7.29.7
+ '@babel/runtime': 7.12.18
amd-name-resolver: 1.3.1
babel-plugin-debug-macros: 0.3.4(patch_hash=387f93bad78f3a98b20dc742f4f0b7a165c7e6ebc65cc60356748346c0725c7f)(@babel/[email protected])
babel-plugin-ember-data-packages-polyfill: 0.1.2
babel-plugin-ember-modules-api-polyfill: 3.5.0
babel-plugin-module-resolver: 5.0.3
- broccoli-babel-transpiler: 8.1.0(@babel/[email protected])
+ broccoli-babel-transpiler: 8.0.2(@babel/[email protected])
broccoli-debug: 0.6.5
broccoli-funnel: 3.0.8
broccoli-source: 3.0.1
- broccoli-string-replace: 0.1.2
calculate-cache-key-for-tree: 2.0.0
clone: 2.1.2
ember-cli-babel-plugin-helpers: 1.1.1
ember-cli-version-checker: 5.1.2
ensure-posix-path: 1.1.1
resolve-package-path: 4.0.3
- semver: 7.8.5
+ semver: 7.8.4
transitivePeerDependencies:
- supports-color
@@ -12675,7 +12669,7 @@ snapshots:
fs-extra: 9.1.0
resolve: 1.22.12
rsvp: 4.8.5
- semver: 7.8.5
+ semver: 7.8.4
stagehand: 1.0.1
walk-sync: 2.2.0
transitivePeerDependencies:
@@ -12697,7 +12691,7 @@ snapshots:
dependencies:
resolve-package-path: 3.1.0
- semver: 7.8.5
+ semver: 7.8.4
silent-error: 1.1.1
transitivePeerDependencies:
- supports-color
@@ -12763,7 +12757,7 @@ snapshots:
lodash: 4.18.1
markdown-it: 14.2.0
markdown-it-terminal: 0.4.0([email protected])
- minimatch: 10.2.6
+ minimatch: 10.2.5
morgan: 1.10.1
nopt: 3.0.6
npm-package-arg: 13.0.2
@@ -12777,7 +12771,7 @@ snapshots:
resolve-package-path: 4.0.3
safe-stable-stringify: 2.5.0
sane: 5.0.1
- semver: 7.8.5
+ semver: 7.8.4
silent-error: 1.1.1
sort-package-json: 3.6.1
symlink-or-copy: 1.3.1
@@ -12892,7 +12886,7 @@ snapshots:
cli-table3: 0.6.5
debug: 4.4.3
ember-auto-import: 2.13.1(@glint/[email protected])
- ember-cli-babel: 8.3.2(@babel/[email protected])
+ ember-cli-babel: 8.3.1(@babel/[email protected])
ember-source: 6.10.1(patch_hash=85ff9a16d08431e3bdc9aea8d55280e14f437f1c2a7d8e461de56c614ad48926)(@glimmer/[email protected])([email protected])
execa: 8.0.1
@@ -12901,7 +12895,7 @@ snapshots:
npmlog: 7.0.1
qunit: 2.25.0
rimraf: 5.0.10
- semver: 7.8.5
+ semver: 7.8.4
silent-error: 1.1.1
transitivePeerDependencies:
- '@glint/template'
@@ -12949,8 +12943,8 @@ snapshots:
dependencies:
- '@babel/parser': 7.29.8
- '@babel/traverse': 7.29.8
+ '@babel/parser': 7.29.7
+ '@babel/traverse': 7.29.7
recast: 0.18.10
transitivePeerDependencies:
- supports-color
@@ -12983,7 +12977,7 @@ snapshots:
broccoli-funnel: 3.0.8
broccoli-merge-trees: 4.2.0
chalk: 4.1.2
- ember-cli-babel: 8.3.2(@babel/[email protected])
+ ember-cli-babel: 8.3.1(@babel/[email protected])
ember-cli-get-component-path-option: 1.0.0
ember-cli-is-package-missing: 1.0.0
ember-cli-normalize-entity-name: 1.0.0
@@ -12995,7 +12989,7 @@ snapshots:
inflection: 2.0.1
route-recognizer: 0.3.4
- semver: 7.8.5
+ semver: 7.8.4
silent-error: 1.1.1
simple-html-tokenizer: 0.5.11
transitivePeerDependencies:
@@ -13346,7 +13340,7 @@ snapshots:
imurmurhash: 0.1.4
is-glob: 4.0.3
json-stable-stringify-without-jsonify: 1.0.1
- minimatch: 10.2.6
+ minimatch: 10.2.5
natural-compare: 1.4.0
optionator: 0.9.4
optionalDependencies:
@@ -13356,8 +13350,8 @@ snapshots:
dependencies:
- acorn: 8.18.0
- acorn-jsx: 5.3.2([email protected])
+ acorn: 8.17.0
+ acorn-jsx: 5.3.2([email protected])
eslint-visitor-keys: 5.0.1
@@ -13462,7 +13456,7 @@ snapshots:
parseurl: 1.3.3
proxy-addr: 2.0.7
qs: 6.15.2
- range-parser: 1.3.0
+ range-parser: 1.2.1
router: 2.2.0
send: 1.2.1
serve-static: 2.2.1
@@ -13915,7 +13909,7 @@ snapshots:
dependencies:
- minimatch: 10.2.6
+ minimatch: 10.2.5
minipass: 7.1.3
path-scurry: 2.0.2
@@ -14145,7 +14139,7 @@ snapshots:
dependencies:
safer-buffer: 2.1.2
dependencies:
safer-buffer: 2.1.2
@@ -14482,7 +14476,7 @@ snapshots:
dependencies:
- '@babel/parser': 7.29.8
+ '@babel/parser': 7.29.7
'@jsdoc/salty': 0.2.9
'@types/markdown-it': 14.1.2
bluebird: 3.7.2
@@ -14519,7 +14513,7 @@ snapshots:
whatwg-encoding: 3.1.1
whatwg-mimetype: 4.0.0
whatwg-url: 14.2.0
- ws: 8.21.3
+ ws: 8.21.0
xml-name-validator: 5.0.0
transitivePeerDependencies:
- bufferutil
@@ -14546,7 +14540,7 @@ snapshots:
whatwg-encoding: 3.1.1
whatwg-mimetype: 4.0.0
whatwg-url: 14.2.0
- ws: 8.21.3
+ ws: 8.21.0
xml-name-validator: 5.0.0
transitivePeerDependencies:
- bufferutil
@@ -14696,7 +14690,7 @@ snapshots:
docopt: 0.6.2
hasown: 2.0.4
npm-license-corrections: 1.6.2
- semver: 7.8.5
+ semver: 7.8.4
spdx-expression-parse: 4.0.0
spdx-expression-validate: 2.0.0
spdx-osi: 3.0.0
@@ -15000,25 +14994,25 @@ snapshots:
dependencies:
- brace-expansion: 5.0.9
+ brace-expansion: 5.0.6
dependencies:
- brace-expansion: 1.1.18
+ brace-expansion: 1.1.15
dependencies:
- brace-expansion: 2.1.4
+ brace-expansion: 2.1.1
dependencies:
- brace-expansion: 2.1.4
+ brace-expansion: 2.1.1
dependencies:
- brace-expansion: 2.1.4
+ brace-expansion: 2.1.1
@@ -15069,7 +15063,7 @@ snapshots:
dependencies:
@@ -15129,7 +15123,7 @@ snapshots:
make-fetch-happen: 13.0.1
nopt: 7.2.1
proc-log: 4.2.0
- semver: 7.8.5
+ semver: 7.8.4
tar: 6.2.1
which: 4.0.0
transitivePeerDependencies:
@@ -15137,7 +15131,7 @@ snapshots:
@@ -15152,7 +15146,7 @@ snapshots:
dependencies:
hosted-git-info: 7.0.2
- semver: 7.8.5
+ semver: 7.8.4
validate-npm-package-license: 3.0.4
@@ -15163,7 +15157,7 @@ snapshots:
dependencies:
- semver: 7.8.5
+ semver: 7.8.4
@@ -15173,14 +15167,14 @@ snapshots:
dependencies:
hosted-git-info: 7.0.2
proc-log: 4.2.0
- semver: 7.8.5
+ semver: 7.8.4
validate-npm-package-name: 5.0.1
dependencies:
hosted-git-info: 9.0.3
proc-log: 6.1.0
- semver: 7.8.5
+ semver: 7.8.4
validate-npm-package-name: 7.0.2
@@ -15192,7 +15186,7 @@ snapshots:
npm-install-checks: 6.3.0
npm-normalize-package-bin: 3.0.1
npm-package-arg: 11.0.3
- semver: 7.8.5
+ semver: 7.8.4
dependencies:
@@ -15620,7 +15614,7 @@ snapshots:
dependencies:
- '@babel/traverse': 7.29.8
+ '@babel/traverse': 7.29.7
content-tag: 4.2.0
prettier: 3.8.1
transitivePeerDependencies:
@@ -15779,7 +15773,7 @@ snapshots:
dependencies:
- mktemp: 2.0.4
+ mktemp: 2.0.3
rimraf: 5.0.10
underscore.string: 3.3.6
@@ -15797,7 +15791,7 @@ snapshots:
dependencies:
@@ -15808,7 +15802,7 @@ snapshots:
dependencies:
bytes: 3.1.2
http-errors: 2.0.1
- iconv-lite: 0.7.3
+ iconv-lite: 0.7.2
unpipe: 1.0.0
@@ -16188,7 +16182,7 @@ snapshots:
dependencies:
@@ -16201,7 +16195,7 @@ snapshots:
mime-types: 3.0.2
ms: 2.1.3
on-finished: 2.4.1
- range-parser: 1.3.0
+ range-parser: 1.2.1
statuses: 2.0.2
transitivePeerDependencies:
- supports-color
@@ -16397,7 +16391,7 @@ snapshots:
get-stdin: 9.0.0
git-hooks-list: 3.2.0
is-plain-obj: 4.1.0
- semver: 7.8.5
+ semver: 7.8.4
sort-object-keys: 1.1.3
tinyglobby: 0.2.17
@@ -16407,7 +16401,7 @@ snapshots:
detect-newline: 4.0.1
git-hooks-list: 4.2.1
is-plain-obj: 4.1.0
- semver: 7.8.5
+ semver: 7.8.4
sort-object-keys: 2.1.0
tinyglobby: 0.2.17
@@ -16782,10 +16776,10 @@ snapshots:
dependencies:
'@jridgewell/source-map': 0.3.11
- acorn: 8.18.0
+ acorn: 8.17.0
commander: 2.20.3
source-map-support: 0.5.21
@@ -16804,7 +16798,7 @@ snapshots:
http-proxy: 1.18.1(patch_hash=3032f3a47f33911d5c278ec6f2d4e0e4afc8f977baea1012613b13de23831c73)
js-yaml: 4.2.0
lodash: 4.18.1
- minimatch: 10.2.6
+ minimatch: 10.2.5
mkdirp: 3.0.1
mustache: 4.2.0
printf: 0.6.1
@@ -16950,7 +16944,7 @@ snapshots:
dependencies:
growly: 1.3.0
is-wsl: 2.2.0
- semver: 7.8.5
+ semver: 7.8.4
shellwords: 0.1.1
which: 2.0.2
@@ -17059,7 +17053,7 @@ snapshots:
dependencies:
- semver: 7.8.5
+ semver: 7.8.4
dependencies:
@@ -17133,9 +17127,9 @@ snapshots:
dependencies:
- browserslist: 4.28.8
+ browserslist: 4.28.2
escalade: 3.2.0
picocolors: 1.1.1
@@ -17168,7 +17162,7 @@ snapshots:
dependencies:
lightningcss: 1.32.0
picomatch: 4.0.4
@@ -17179,13 +17173,13 @@ snapshots:
'@types/node': 25.9.1
fsevents: 2.3.3
jiti: 2.6.1
- terser: 5.50.0
+ terser: 5.48.0
yaml: 2.9.0
dependencies:
'@vitest/expect': 4.1.9
'@vitest/pretty-format': 4.1.9
'@vitest/runner': 4.1.9
'@vitest/snapshot': 4.1.9
@@ -17202,7 +17196,7 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 25.9.1
@@ -17232,7 +17226,7 @@ snapshots:
dependencies:
path-browserify: 1.0.1
- semver: 7.8.5
+ semver: 7.8.4
typescript-auto-import-cache: 0.3.6
vscode-languageserver-textdocument: 1.0.12
vscode-nls: 5.2.0
@@ -17301,7 +17295,7 @@ snapshots:
dependencies:
ensure-posix-path: 1.1.1
matcher-collection: 2.0.1
- minimatch: 10.2.6
+ minimatch: 10.2.5
@@ -17473,7 +17467,7 @@ snapshots:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index c3ece7825a9..d32283706f4 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -17,6 +17,7 @@ packages:
- "frontend/asset-processor"
- "frontend/discourse-types"
- "plugins/automation"
+- "plugins/boards"
- "plugins/chat"
- "plugins/checklist"
- "plugins/discourse-adplugin"
diff --git a/spec/lib/plugin/metadata_spec.rb b/spec/lib/plugin/metadata_spec.rb
index 859467edd1b..6ac5ce9d63c 100644
--- a/spec/lib/plugin/metadata_spec.rb
+++ b/spec/lib/plugin/metadata_spec.rb
@@ -50,6 +50,8 @@ TEXT
official("discourse-akismet")
official("discourse-cakeday")
official("discourse-data-explorer")
+ official("boards")
+ unofficial("discourse-kanban")
unofficial("babble")
end
diff --git a/themes/horizon/scss/main.scss b/themes/horizon/scss/main.scss
index 0b0cb23f7c2..4155d5db885 100644
--- a/themes/horizon/scss/main.scss
+++ b/themes/horizon/scss/main.scss
@@ -98,7 +98,7 @@ body:not(.has-full-page-chat, .wizard) {
> *:not(
.experimental-screen,
.activate-account,
- .discourse-kanban-board-viewer
+ .discourse-boards-board-viewer
) {
box-sizing: border-box;
max-width: 1000px;
diff --git a/translator.yml b/translator.yml
index ffa1279f6c5..a6626b2ecf5 100644
--- a/translator.yml
+++ b/translator.yml
@@ -24,6 +24,13 @@ files:
destination_path: error_pages/503.html
label: core
+ - source_path: plugins/boards/config/locales/client.en.yml
+ destination_path: plugins/boards/client.yml
+ label: boards
+ - source_path: plugins/boards/config/locales/server.en.yml
+ destination_path: plugins/boards/server.yml
+ label: boards
+
- source_path: plugins/chat/config/locales/client.en.yml
destination_path: plugins/chat/client.yml
label: chat
diff --git a/tsconfig.json b/tsconfig.json
index 791c7c5c296..b6a14a1d99e 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -3,6 +3,7 @@
{ "path": "frontend/discourse" },
{ "path": "frontend/discourse-i18n" },
{ "path": "plugins/automation" },
+ { "path": "plugins/boards" },
{ "path": "plugins/chat" },
{ "path": "plugins/checklist" },
{ "path": "plugins/discourse-adplugin" },