Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(admin): reorder custom badges (#3711)

Hampusf05f22adab12
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.json
index ee54b20f2..3e4548239 100644
--- a/fluxer_admin/openapi-admin.json
+++ b/fluxer_admin/openapi-admin.json
@@ -1254,6 +1254,63 @@
}
}
},
+ "/admin/badges/order": {
+ "put": {
+ "operationId": "reorder_admin_badges",
+ "summary": "Reorder custom badges",
+ "tags": ["Admin"],
+ "responses": {
+ "200": {
+ "description": "Success",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AdminCustomBadgeListResponse"}}}
+ },
+ "400": {
+ "description": "Bad Request - The request was malformed or contained invalid data",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "401": {
+ "description": "Unauthorized - Authentication is required or the token is invalid",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "403": {
+ "description": "Forbidden - You do not have permission to perform this action",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ },
+ "429": {
+ "description": "Too Many Requests - You are being rate limited",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},
+ "headers": {
+ "Retry-After": {
+ "description": "Number of seconds to wait before retrying (only on 429)",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Limit": {
+ "description": "The number of requests that can be made in the current window",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Remaining": {
+ "description": "The number of remaining requests that can be made",
+ "schema": {"type": "integer"}
+ },
+ "X-RateLimit-Reset": {
+ "description": "Unix timestamp when the rate limit resets",
+ "schema": {"type": "integer"}
+ }
+ }
+ },
+ "500": {
+ "description": "Internal Server Error - An unexpected error occurred",
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
+ }
+ },
+ "description": "Sets the display order of the custom badges. The body lists every user and guild badge on this instance exactly once, in the new order. Creates audit log entry. Requires BADGE_UPDATE permission.",
+ "security": [{"adminApiKey": []}],
+ "requestBody": {
+ "required": true,
+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ReorderCustomBadgesRequest"}}}
+ }
+ }
+ },
"/admin/badges/{badge_id}": {
"patch": {
"operationId": "update_admin_badge",
@@ -18977,6 +19034,30 @@
"required": ["id", "type", "name", "description", "asset_url", "href"],
"additionalProperties": false
},
+ "ReorderCustomBadgesRequest": {
+ "type": "object",
+ "properties": {
+ "badge_ids": {
+ "maxItems": 200,
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/SnowflakeType"},
+ "description": "IDs of every custom badge on this instance, user and guild, in the new display order"
+ }
+ },
+ "required": ["badge_ids"]
+ },
+ "AdminCustomBadgeListResponse": {
+ "type": "object",
+ "properties": {
+ "badges": {
+ "type": "array",
+ "items": {"$ref": "#/components/schemas/AdminCustomBadgeResponse"},
+ "description": "Badges defined on this instance, in display order"
+ }
+ },
+ "required": ["badges"],
+ "additionalProperties": false
+ },
"CreateCustomBadgeRequest": {
"type": "object",
"properties": {
@@ -18996,18 +19077,6 @@
},
"required": ["type", "name", "image"]
},
- "AdminCustomBadgeListResponse": {
- "type": "object",
- "properties": {
- "badges": {
- "type": "array",
- "items": {"$ref": "#/components/schemas/AdminCustomBadgeResponse"},
- "description": "Badges defined on this instance, in display order"
- }
- },
- "required": ["badges"],
- "additionalProperties": false
- },
"AdminAuditLogResponseSchema": {
"type": "object",
"properties": {
diff --git a/fluxer_admin/src/api/badges.rs b/fluxer_admin/src/api/badges.rs
index 6c38e0097..5ac2d7290 100644
--- a/fluxer_admin/src/api/badges.rs
+++ b/fluxer_admin/src/api/badges.rs
@@ -84,6 +84,18 @@ impl AdminApiClient {
Ok(())
}
+ pub async fn reorder_badges(&self, ids: &[String]) -> ApiResult<AdminCustomBadgeList> {
+ let body = generated_types::ReorderCustomBadgesRequest {
+ badge_ids: ids.iter().map(|id| snowflake(id)).collect(),
+ };
+ let response = self
+ .generated()
+ .reorder_admin_badges(&body)
+ .await
+ .map_err(|e| self.generated_error(e))?;
+ self.generated_value(response.into_inner())
+ }
+
pub async fn update_user_badges(&self, user_id: &str, ids: &[String]) -> ApiResult<AdminUser> {
let body = generated_types::UpdateUserCustomBadgesRequest {
badge_ids: badge_ids(ids),
diff --git a/fluxer_admin/src/api/types/badges.rs b/fluxer_admin/src/api/types/badges.rs
index bccf2a959..752e8548e 100644
--- a/fluxer_admin/src/api/types/badges.rs
+++ b/fluxer_admin/src/api/types/badges.rs
@@ -58,12 +58,48 @@ pub struct AdminCustomBadgeList {
pub badges: Vec<AdminCustomBadge>,
}
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum BadgeMove {
+ Up,
+ Down,
+}
+
+impl BadgeMove {
+ pub fn parse(value: &str) -> Option<Self> {
+ match value {
+ "up" => Some(Self::Up),
+ "down" => Some(Self::Down),
+ _ => None,
+ }
+ }
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Up => "up",
+ Self::Down => "down",
+ }
+ }
+}
+
impl AdminCustomBadgeList {
pub fn of_type(&self, badge_type: CustomBadgeType) -> impl Iterator<Item = &AdminCustomBadge> {
self.badges
.iter()
.filter(move |badge| badge.badge_type == badge_type)
}
+
+ pub fn moved_order(&self, badge_id: &str, direction: BadgeMove) -> Option<Vec<String>> {
+ let index = self.badges.iter().position(|badge| badge.id == badge_id)?;
+ let badge_type = self.badges[index].badge_type;
+ let same_type = |candidate: &AdminCustomBadge| candidate.badge_type == badge_type;
+ let neighbour = match direction {
+ BadgeMove::Up => self.badges[..index].iter().rposition(same_type)?,
+ BadgeMove::Down => index + 1 + self.badges[index + 1..].iter().position(same_type)?,
+ };
+ let mut order: Vec<String> = self.badges.iter().map(|badge| badge.id.clone()).collect();
+ order.swap(index, neighbour);
+ Some(order)
+ }
}
pub struct CustomBadgeFields {
@@ -72,3 +108,62 @@ pub struct CustomBadgeFields {
pub href: Option<String>,
pub image: Option<String>,
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn badge(id: &str, badge_type: CustomBadgeType) -> AdminCustomBadge {
+ AdminCustomBadge {
+ id: id.to_owned(),
+ badge_type,
+ name: id.to_owned(),
+ description: None,
+ asset_url: String::new(),
+ href: None,
+ }
+ }
+
+ fn ids(values: &[&str]) -> Option<Vec<String>> {
+ Some(values.iter().map(|value| (*value).to_owned()).collect())
+ }
+
+ fn list() -> AdminCustomBadgeList {
+ AdminCustomBadgeList {
+ badges: vec![
+ badge("1", CustomBadgeType::User),
+ badge("2", CustomBadgeType::Guild),
+ badge("3", CustomBadgeType::User),
+ badge("4", CustomBadgeType::Guild),
+ badge("5", CustomBadgeType::User),
+ ],
+ }
+ }
+
+ #[test]
+ fn moved_order_swaps_with_the_nearest_badge_of_the_same_type() {
+ let badges = list();
+ assert_eq!(
+ ids(&["3", "2", "1", "4", "5"]),
+ badges.moved_order("3", BadgeMove::Up)
+ );
+ assert_eq!(
+ ids(&["1", "4", "3", "2", "5"]),
+ badges.moved_order("2", BadgeMove::Down)
+ );
+ assert_eq!(
+ ids(&["1", "2", "5", "4", "3"]),
+ badges.moved_order("3", BadgeMove::Down)
+ );
+ }
+
+ #[test]
+ fn moved_order_refuses_the_ends_and_unknown_badges() {
+ let badges = list();
+ assert_eq!(None, badges.moved_order("1", BadgeMove::Up));
+ assert_eq!(None, badges.moved_order("2", BadgeMove::Up));
+ assert_eq!(None, badges.moved_order("5", BadgeMove::Down));
+ assert_eq!(None, badges.moved_order("4", BadgeMove::Down));
+ assert_eq!(None, badges.moved_order("9", BadgeMove::Up));
+ }
+}
diff --git a/fluxer_admin/src/routes/badges.rs b/fluxer_admin/src/routes/badges.rs
index f5d010e88..02b34b9c9 100644
--- a/fluxer_admin/src/routes/badges.rs
+++ b/fluxer_admin/src/routes/badges.rs
@@ -3,7 +3,9 @@
use crate::{
api::{
client::{AdminApiClient, ApiError},
- types::{BADGE_IMAGE_MAX_BYTES, BADGE_IMAGE_TYPES, CustomBadgeFields, CustomBadgeType},
+ types::{
+ BADGE_IMAGE_MAX_BYTES, BADGE_IMAGE_TYPES, BadgeMove, CustomBadgeFields, CustomBadgeType,
+ },
},
middleware::{
auth::AuthContext,
@@ -26,6 +28,7 @@ pub fn router() -> Router<AppState> {
.route("/badges", get(badges_page).post(create_badge))
.route("/badges/{badge_id}", post(update_badge))
.route("/badges/{badge_id}/delete", post(delete_badge))
+ .route("/badges/{badge_id}/move/{direction}", post(move_badge))
.layer(DefaultBodyLimit::max(BADGE_IMAGE_MAX_BYTES + 64 * 1024))
}
@@ -179,3 +182,34 @@ async fn delete_badge(
};
flash::redirect_with_flash(&back, flash, config.secure_cookies())
}
+
+async fn move_badge(
+ State(state): State<AppState>,
+ auth: axum::Extension<AuthContext>,
+ Path((badge_id, direction)): Path<(String, String)>,
+) -> Response {
+ let config = state.config();
+ let back = format!("{}/badges", config.base_path);
+ let Some(direction) = BadgeMove::parse(&direction) else {
+ return flash::redirect_error(config, &back, "Choose up or down");
+ };
+ let client = AdminApiClient::new(state.http_client(), config, &auth.0.session);
+ let badges = match client.list_badges().await {
+ Ok(badges) => badges,
+ Err(error) => {
+ return flash::redirect_with_flash(
+ &back,
+ failure("move", &error),
+ config.secure_cookies(),
+ );
+ }
+ };
+ let Some(order) = badges.moved_order(&badge_id, direction) else {
+ return flash::redirect_error(config, &back, "This badge cannot move any further");
+ };
+ let flash = match client.reorder_badges(&order).await {
+ Ok(_) => FlashData::success("Badge moved"),
+ Err(error) => failure("move", &error),
+ };
+ flash::redirect_with_flash(&back, flash, config.secure_cookies())
+}
diff --git a/fluxer_admin/src/templates/pages/badges.rs b/fluxer_admin/src/templates/pages/badges.rs
index 87991d7b5..2d01e2d57 100644
--- a/fluxer_admin/src/templates/pages/badges.rs
+++ b/fluxer_admin/src/templates/pages/badges.rs
@@ -4,7 +4,7 @@ use crate::{
acl,
api::types::{
AdminCustomBadge, AdminCustomBadgeList, BADGE_IMAGE_MAX_BYTES, BADGE_IMAGE_TYPES,
- CustomBadgeType,
+ BadgeMove, CustomBadgeType,
},
config::AdminConfig,
middleware::auth::AuthContext,
@@ -14,7 +14,7 @@ use crate::{
error_display::error_alert,
form::{
FORM_INPUT_CLASS, FORM_LABEL_CLASS, FORM_SELECT_CLASS, csrf_input, danger_button,
- submit_button,
+ secondary_button, submit_button,
},
page_container::{card_with_header, page_header},
},
@@ -84,8 +84,11 @@ fn badge_section(
(empty_state_full(None, "No badges of this type yet.", None))
} @else {
div class="divide-y divide-neutral-100" {
- @for badge in badges {
- (badge_row(config, badge, permissions, csrf_token))
+ @for (index, badge) in badges.iter().enumerate() {
+ (badge_row(config, badge, permissions, csrf_token, BadgePosition {
+ first: index == 0,
+ last: index + 1 == badges.len(),
+ }))
}
}
}
@@ -93,11 +96,36 @@ fn badge_section(
)
}
+struct BadgePosition {
+ first: bool,
+ last: bool,
+}
+
+fn move_form(
+ config: &AdminConfig,
+ badge: &AdminCustomBadge,
+ direction: BadgeMove,
+ csrf_token: &str,
+) -> Markup {
+ let label = match direction {
+ BadgeMove::Up => "Move up",
+ BadgeMove::Down => "Move down",
+ };
+ html! {
+ form method="post"
+ action={(config.base_path) "/badges/" (badge.id) "/move/" (direction.as_str())} {
+ (csrf_input(csrf_token))
+ (secondary_button(label))
+ }
+ }
+}
+
fn badge_row(
config: &AdminConfig,
badge: &AdminCustomBadge,
permissions: &BadgePermissions,
csrf_token: &str,
+ position: BadgePosition,
) -> Markup {
let base = &config.base_path;
html! {
@@ -131,6 +159,12 @@ fn badge_row(
}
}
}
+ @if permissions.update && !position.first {
+ (move_form(config, badge, BadgeMove::Up, csrf_token))
+ }
+ @if permissions.update && !position.last {
+ (move_form(config, badge, BadgeMove::Down, csrf_token))
+ }
@if permissions.delete {
form method="post" action={(base) "/badges/" (badge.id) "/delete"}
onsubmit="return confirm('Delete this badge? Everyone it was given to stops showing it.')" {
diff --git a/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts b/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts
index 4e7105c0d..0cb91c6ee 100644
--- a/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/BadgeAdminController.ts
@@ -16,6 +16,7 @@ import {
AdminCustomBadgeResponse,
CreateCustomBadgeRequest,
CustomBadgeIdParam,
+ ReorderCustomBadgesRequest,
UpdateCustomBadgeRequest,
UpdateUserCustomBadgesRequest,
} from '@fluxer/schema/src/domains/admin/AdminBadgeSchemas';
@@ -74,6 +75,33 @@ export function BadgeAdminController(app: HonoApp) {
return ctx.json(badge);
},
);
+ app.put(
+ '/admin/badges/order',
+ RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
+ requireAdminACL(AdminACLs.BADGE_UPDATE),
+ Validator('json', ReorderCustomBadgesRequest),
+ OpenAPI({
+ operationId: 'reorder_admin_badges',
+ summary: 'Reorder custom badges',
+ description:
+ 'Sets the display order of the custom badges. The body lists every user and guild badge on this instance exactly once, in the new order. Creates audit log entry. Requires BADGE_UPDATE permission.',
+ responseSchema: AdminCustomBadgeListResponse,
+ statusCode: 200,
+ security: 'adminApiKey',
+ tags: 'Admin',
+ }),
+ async (ctx) => {
+ const {badge_ids: badgeIds} = ctx.req.valid('json');
+ const response = await ctx.get('adminService').badgeService.reorderBadges(badgeIds);
+ await recordAdminWrite(ctx, {
+ targetType: 'badge',
+ targetId: 0n,
+ action: 'reorder_badges',
+ metadata: {badge_ids: badgeIds.join(',')},
+ });
+ return ctx.json(response);
+ },
+ );
app.patch(
'/admin/badges/:badge_id',
RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),
diff --git a/fluxer_api/src/api/admin/services/AdminBadgeService.ts b/fluxer_api/src/api/admin/services/AdminBadgeService.ts
index 9b0a9aa1f..dfa41a1e6 100644
--- a/fluxer_api/src/api/admin/services/AdminBadgeService.ts
+++ b/fluxer_api/src/api/admin/services/AdminBadgeService.ts
@@ -18,6 +18,7 @@ import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {type CustomBadgeType, MAX_CUSTOM_BADGES_PER_TYPE} from '@fluxer/constants/src/BadgeConstants';
import {MaxBadgesError} from '@fluxer/errors/src/domains/badge/MaxBadgesError';
import {UnknownBadgeError} from '@fluxer/errors/src/domains/badge/UnknownBadgeError';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import type {
AdminCustomBadgeListResponse,
AdminCustomBadgeResponse,
@@ -138,6 +139,21 @@ export class AdminBadgeService {
}
}
+ async reorderBadges(badgeIds: ReadonlyArray<bigint>): Promise<AdminCustomBadgeListResponse> {
+ const order = badgeIds.map(String);
+ const badges = await this.deps.instanceConfigRepository.updateCustomBadges((current) => {
+ const reordered = order.map((id) => findBadge(current, id));
+ if (new Set(order).size !== order.length) {
+ throw InputValidationError.create('badge_ids', 'Each badge can only be listed once');
+ }
+ if (reordered.length !== current.length) {
+ throw InputValidationError.create('badge_ids', 'List every badge on this instance');
+ }
+ return reordered;
+ });
+ return {badges: badges.map(mapCustomBadgeToAdminResponse)};
+ }
+
async updateUserBadges(params: {
userId: UserID;
badgeIds: ReadonlyArray<bigint>;
diff --git a/fluxer_api/src/api/admin/tests/AdminCustomBadgeOrder.test.ts b/fluxer_api/src/api/admin/tests/AdminCustomBadgeOrder.test.ts
new file mode 100644
index 000000000..e64e92348
--- /dev/null
+++ b/fluxer_api/src/api/admin/tests/AdminCustomBadgeOrder.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestCustomBadge} from '@app/api/admin/tests/AdminTestUtils';
+import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import type {AdminCustomBadgeListResponse} from '@fluxer/schema/src/domains/admin/AdminBadgeSchemas';
+import type {ProfileBadgeResponse} from '@fluxer/schema/src/domains/user/ProfileBadgeSchemas';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
+
+describe('custom badge order', () => {
+ let harness: ApiTestHarness;
+ let admin: TestAccount;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+ beforeEach(async () => {
+ await harness.resetData();
+ admin = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.WILDCARD]);
+ });
+
+ async function listedIds(): Promise<Array<string>> {
+ const response = await createBuilder<AdminCustomBadgeListResponse>(harness, admin.token)
+ .get('/admin/badges')
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ return response.badges.map((badge) => badge.id);
+ }
+
+ async function createBadges(): Promise<Array<string>> {
+ const first = await createTestCustomBadge(harness, admin.token, 'user', 'First');
+ const second = await createTestCustomBadge(harness, admin.token, 'guild', 'Second');
+ const third = await createTestCustomBadge(harness, admin.token, 'user', 'Third');
+ return [first.id, second.id, third.id];
+ }
+
+ async function expectRejectedOrder(badgeIds: Array<string>, status: number, code: string) {
+ const {json} = await createBuilder<{errors?: Array<{path: string}>}>(harness, admin.token)
+ .put('/admin/badges/order')
+ .body({badge_ids: badgeIds})
+ .expect(status, code)
+ .executeWithResponse();
+ return json;
+ }
+
+ test('saves the new order and shows it in the list and on profiles', async () => {
+ const [first, second, third] = await createBadges();
+ const response = await createBuilder<AdminCustomBadgeListResponse>(harness, admin.token)
+ .put('/admin/badges/order')
+ .body({badge_ids: [third, second, first]})
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect(response.badges.map((badge) => badge.id)).toEqual([third, second, first]);
+ expect(await listedIds()).toEqual([third, second, first]);
+
+ const target = await createTestAccount(harness);
+ await createBuilder(harness, admin.token)
+ .patch(`/admin/users/${target.userId}/badges`)
+ .body({badge_ids: [first, third]})
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ const profile = await createBuilder<{profile_badges: Array<ProfileBadgeResponse>}>(harness, target.token)
+ .get(`/users/${target.userId}/profile`)
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect(profile.profile_badges.filter((badge) => badge.kind === 'custom').map((badge) => badge.key)).toEqual([
+ `custom:${third}`,
+ `custom:${first}`,
+ ]);
+ });
+
+ test('rejects an unknown ID and keeps the order', async () => {
+ const [first, second, third] = await createBadges();
+ await expectRejectedOrder([third, second, first, '1'], HTTP_STATUS.NOT_FOUND, 'UNKNOWN_BADGE');
+ expect(await listedIds()).toEqual([first, second, third]);
+ });
+
+ test('rejects a missing ID and keeps the order', async () => {
+ const [first, second, third] = await createBadges();
+ const json = await expectRejectedOrder([third, first], HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY');
+ expect(json.errors).toEqual([expect.objectContaining({path: 'badge_ids'})]);
+ expect(await listedIds()).toEqual([first, second, third]);
+ });
+
+ test('rejects a duplicate ID and keeps the order', async () => {
+ const [first, second, third] = await createBadges();
+ const json = await expectRejectedOrder([third, second, first, third], HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY');
+ expect(json.errors).toEqual([expect.objectContaining({path: 'badge_ids'})]);
+ expect(await listedIds()).toEqual([first, second, third]);
+ });
+
+ test('needs the badge update ACL', async () => {
+ const [first, second, third] = await createBadges();
+ const reader = await setUserACLs(harness, await createTestAccount(harness), [
+ AdminACLs.AUTHENTICATE,
+ AdminACLs.BADGE_LIST,
+ ]);
+ await createBuilder(harness, reader.token)
+ .put('/admin/badges/order')
+ .body({badge_ids: [third, second, first]})
+ .expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
+ .execute();
+ expect(await listedIds()).toEqual([first, second, third]);
+ });
+});
diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts
index d486f36f8..72cd178bb 100644
--- a/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts
+++ b/fluxer_api/src/api/admin/tests/audit_coverage/BadgeAdminAuditCases.ts
@@ -38,6 +38,23 @@ export const BadgeAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [
};
},
},
+ {
+ method: 'PUT',
+ route: '/admin/badges/order',
+ async prepare({harness, admin}) {
+ const first = await createTestCustomBadge(harness, admin.token, 'user');
+ const second = await createTestCustomBadge(harness, admin.token, 'guild');
+ return {
+ request: {path: '/admin/badges/order', body: {badge_ids: [second.id, first.id]}},
+ expected: {
+ action: 'reorder_badges',
+ targetType: 'badge',
+ targetId: '0',
+ metadata: {badge_ids: `${second.id},${first.id}`},
+ },
+ };
+ },
+ },
{
method: 'PATCH',
route: '/admin/badges/:badge_id',
diff --git a/fluxer_docs/src/content/docs/admin-api/badges.mdx b/fluxer_docs/src/content/docs/admin-api/badges.mdx
index 830a04414..65084240f 100644
--- a/fluxer_docs/src/content/docs/admin-api/badges.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/badges.mdx
@@ -8,7 +8,7 @@ import RouteHeader from '@/components/RouteHeader.astro';
A custom badge is an image that instance admins make and give out. A user badge shows on the [profile](/http-api/users/#profile-badge-object) of each account it's given to, after the built-in badges. A guild badge shows next to the guild name, after its verified, partnered or discoverable badge, and [instance discovery](/http-api/instance/#guild-badge-object) lists every guild badge for clients.
-You can make up to 100 badges of each type, and an account or guild can have up to 10. Give badges with [Update user badges](/admin-api/users/#update-user-badges) and the `badge_ids` field of [Update guild](/admin-api/guilds/#update-guild). Deleting a badge takes it off everyone who had it.
+You can make up to 100 badges of each type, and an account or guild can have up to 10. Give badges with [Update user badges](/admin-api/users/#update-user-badges) and the `badge_ids` field of [Update guild](/admin-api/guilds/#update-guild). Deleting a badge takes it off everyone who had it. You can change the display order with [Reorder badges](#reorder-badges) or the Move up and Move down buttons on the Badges page of the admin panel.
## Admin custom badge object
@@ -40,7 +40,7 @@ You can make up to 100 badges of each type, and an account or guild can have up
<RouteHeader method="GET" path="/v1/admin/badges" auditReason />
-Returns every custom badge in display order, which is the order they were made in. You need `badge:list`.
+Returns every custom badge in display order. A new badge goes to the end. You need `badge:list`.
### Response body
@@ -126,3 +126,31 @@ Deletes a badge and its image and returns 204. Accounts and guilds that had it s
| 404 | [error response](/admin-api/#error-response) | `UNKNOWN_BADGE` when the badge doesn't exist |
The rate limit is 100 requests per minute, on the `admin:user:modify` bucket.
+
+## Reorder badges
+
+<RouteHeader method="PUT" path="/v1/admin/badges/order" auditReason />
+
+Sets the display order of the custom badges and returns them in the new order. Send every user and guild badge on the instance exactly once. Profiles and guilds show their badges in this order. You need `badge:update`.
+
+### JSON body
+
+| Field | Type | Description |
+| --- | --- | --- |
+| badge_ids | array[snowflake] | Every badge ID on the instance in the new order (up to 200) |
+
+### Response body
+
+| Field | Type | Description |
+| --- | --- | --- |
+| badges | array[[Admin custom badge](#admin-custom-badge-object) object] | The badges of both types in the new order |
+
+### Response
+
+| Status | Body | Condition |
+| --- | --- | --- |
+| 200 | response body | The order was saved |
+| 400 | [error response](/admin-api/#error-response) | `INVALID_FORM_BODY` when `badge_ids` leaves out a badge or lists one twice |
+| 404 | [error response](/admin-api/#error-response) | `UNKNOWN_BADGE` when an ID isn't a badge on the instance |
+
+The rate limit is 100 requests per minute, on the `admin:user:modify` bucket.
diff --git a/fluxer_docs/src/content/docs/admin-api/index.mdx b/fluxer_docs/src/content/docs/admin-api/index.mdx
index 391e8977f..8997e5248 100644
--- a/fluxer_docs/src/content/docs/admin-api/index.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/index.mdx
@@ -443,6 +443,7 @@ These entries have `access` set to `write`.
| remove_registration_url | A revoked registration URL was removed from the list |
| remove_relationships_by_category | Every relationship in one category was removed from an account |
| rename_registration_url | A registration URL was given a new label |
+| reorder_badges | The display order of the custom badges was changed |
| resend_verification_email | An email verification message was requested again for an account |
| resolve_report | A report was updated or resolved |
| revoke_admin_api_key | An Admin API key was revoked |
diff --git a/packages/schema/src/domains/admin/AdminBadgeSchemas.ts b/packages/schema/src/domains/admin/AdminBadgeSchemas.ts
index f68092215..a00955488 100644
--- a/packages/schema/src/domains/admin/AdminBadgeSchemas.ts
+++ b/packages/schema/src/domains/admin/AdminBadgeSchemas.ts
@@ -5,6 +5,7 @@ import {
CUSTOM_BADGE_NAME_MAX_LENGTH,
CustomBadgeTypes,
MAX_CUSTOM_BADGES_PER_ENTITY,
+ MAX_CUSTOM_BADGES_PER_TYPE,
} from '@fluxer/constants/src/BadgeConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {
@@ -95,6 +96,15 @@ export const UpdateUserCustomBadgesRequest = z.object({
export type UpdateUserCustomBadgesRequest = z.infer<typeof UpdateUserCustomBadgesRequest>;
+export const ReorderCustomBadgesRequest = z.object({
+ badge_ids: z
+ .array(SnowflakeType)
+ .max(MAX_CUSTOM_BADGES_PER_TYPE * 2)
+ .describe('IDs of every custom badge on this instance, user and guild, in the new display order'),
+});
+
+export type ReorderCustomBadgesRequest = z.infer<typeof ReorderCustomBadgesRequest>;
+
export const CustomBadgeIdListResponse = z
.array(SnowflakeStringType)
.max(MAX_CUSTOM_BADGES_PER_ENTITY)