diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ec8e7c5f..e9798386d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ Pull requests merged to `main` are listed in the nightly pre-releases until the - Site: AH Ledger crafting margins can be sorted and filtered, with shareable market URLs. - Site: /search can find a character nobody has stored yet: a full "First Surname" with no match is looked up in Blizzard's character API (US, then EU) and the character is stored and listed. Off until `EVERLOOT_ARMORY_LOOKUP=1`; limited per address and site-wide, never for crawlers or the header's type-ahead. - Site: armory character pages show completed achievements, faction standings and the number of completed quests from Blizzard's character API, each with the time of its read; the crawler keeps only those fields and deletes each part 30 days after its last read. +- Site: the armory has a guild directory at /armory/guilds: search by name, filter by region and ruleset, sort by members read, average item level or level 60 count. Guild pages show the class mix, levels and average item level, a guild hidden through /guilds/hide leaves the armory too, and ranking rows show the region as a coloured chip. Counts start once the new database migration is applied. - Site: zone and dungeon pages show their terrain types (Desert, Snowy, Swamp, Haunted, Strongholds and Cities and the rest) and the gear whose effect works there, and `/database/terrain` lists every terrain type's zones and instances and every item, enchant and set bonus that changes run, mount or swim speed, all read from the game files. - Site: Add daily auction reports with archived asking-price movers, house spreads, RSS and downloadable share cards. - Site: browse Blizzard auction house data by region and house, search item names, sort and page through current prices, and read 30 days of daily unit prices per house on the ad-free item pages. diff --git a/kb/test/armory-guild-directory-sql.test.ts b/kb/test/armory-guild-directory-sql.test.ts new file mode 100644 index 000000000..fed82d191 --- /dev/null +++ b/kb/test/armory-guild-directory-sql.test.ts @@ -0,0 +1,26 @@ +import { PGlite } from "@electric-sql/pglite"; +import { readFileSync } from "node:fs"; +import { expect, test } from "vitest"; + +const read = (path: string) => readFileSync(new URL(`../../supabase/${path}`, import.meta.url), "utf8"); + +test("the guild directory migration counts read members, honours both hides, and is safe twice", async () => { + const db = new PGlite(); + try { + // Unrelated prerequisites are minimal stand-ins; the players, guilds and armory SQL is real. + await db.exec(`create role anon; create role authenticated; create role service_role; + create table public.users(id uuid primary key); + create table public.character_suppressions(realm text,character text); + create table public.intake_quota_buckets(bucket text primary key,count int,reset_at timestamptz); + create function public.create_api_key(uuid,text,text,text,text[]) returns text language sql as 'select null::text';`); + const links = read("migrations/20261021190000_character_links.sql"); + await db.exec(links.slice(0, links.indexOf("alter table public.api_keys"))); + for (const migration of [ + "20261021130000_players", "20261022160000_players_realm_key", "20261025120000_guilds", + "20261109120000_armory", "20261109130000_armory_touch_members", "20261112190000_armory_profiles", + ]) await db.exec(read(`migrations/${migration}.sql`)); + for (let i = 0; i < 2; i++) await db.exec(read("migrations/20261117170000_armory_guild_directory.sql")); + await db.exec(read("tests/armory_guild_directory.sql")); + expect((await db.query("select count(*)::int as n from public.armory_guilds")).rows).toEqual([{ n: 0 }]); + } finally { await db.close(); } +}, 60_000); diff --git a/supabase/migrations/20261117170000_armory_guild_directory.sql b/supabase/migrations/20261117170000_armory_guild_directory.sql new file mode 100644 index 000000000..551ab76d1 --- /dev/null +++ b/supabase/migrations/20261117170000_armory_guild_directory.sql @@ -0,0 +1,67 @@ +-- The guild directory on /guilds: every armory guild with what the armory has read of its members. +-- Apply after 20261109120000_armory.sql and 20261025120000_guilds.sql. The maintainer applies it; safe to apply twice. +-- Until it is applied the site lists armory guilds by name only (armory_search_guilds) and says the directory is not +-- ready; nothing else depends on it. +-- +-- One row per armory guild: the roster size Blizzard reports, how many of its characters the armory has read, their +-- average item level and how many are level 60, and the newest read of the guild or any of them. Hidden characters +-- are left out of every count (armory hide rule, repeated at read time). A guild hidden through /guilds/hide is left +-- out in the region its realm names: the hide form asks for a realm, the armory keys guilds by region, so a hide on +-- any realm of a region hides the armory guild of that name in that region. That may hide more, never less. +set lock_timeout = '3s'; + +do $$ +begin + if to_regclass('public.armory_guilds') is null or to_regclass('public.guild_suppressions') is null then + raise exception 'Apply 20261109120000_armory.sql and 20261025120000_guilds.sql first'; + end if; +end $$; + +-- The per-guild counts read the characters of one region by guild without touching the table rows. +create index if not exists armory_characters_guild_directory on public.armory_characters(region,guild_slug) + include (slug,level,item_level,fetched_at) where guild_slug is not null; + +-- Filters: a literal guild-name prefix (2 characters or more, as armory_search_guilds), a region, a ruleset. +-- Sort: 'members' (characters read, the default), 'item_level' (their average) or 'level_60' (how many are 60). +-- At most 100 rows a page; `total` is the number of guilds the filters match, repeated on every row. +create or replace function public.armory_guild_directory(p_prefix text, p_region text, p_ruleset_id smallint, p_sort text, p_limit integer, p_offset integer) +returns table (region text, slug text, name text, faction text, ruleset_id smallint, ruleset text, member_count integer, + members_read integer, average_item_level numeric, level_60 integer, fetched_at timestamptz, total integer) +language sql stable security definer set search_path = '' set lock_timeout = '3s' +as $$ +with read as ( + select c.region,c.guild_slug,count(*)::integer as members_read,round(avg(c.item_level),1) as average_item_level, + (count(*) filter (where c.level=60))::integer as level_60,max(c.fetched_at) as newest + from public.armory_characters c + where c.guild_slug is not null and (p_region is null or c.region=p_region) + and not exists(select 1 from public.armory_hides h where h.region=c.region and h.slug=c.slug) + group by c.region,c.guild_slug +), listed as ( + select g.region,g.slug,g.name,g.faction,g.ruleset_id,g.ruleset,g.member_count,coalesce(r.members_read,0) as members_read, + r.average_item_level,coalesce(r.level_60,0) as level_60,greatest(g.fetched_at,r.newest) as fetched_at + from public.armory_guilds g left join read r on r.region=g.region and r.guild_slug=g.slug + where (p_region is null or g.region=p_region) and (p_ruleset_id is null or g.ruleset_id=p_ruleset_id) + and (p_prefix is null or (char_length(p_prefix)>=2 and p_prefix ~ '^[^%_\\]+$' and lower(g.name) like lower(p_prefix)||'%')) + and not exists(select 1 from public.guild_suppressions s + where s.guild_key=lower(g.name) and s.realm_key ~ ('(^| )' || g.region || '[0-9]*( |$)')) +) +select l.region,l.slug,l.name,l.faction,l.ruleset_id,l.ruleset,l.member_count,l.members_read,l.average_item_level,l.level_60, + l.fetched_at,(count(*) over())::integer +from listed l +order by case p_sort when 'item_level' then l.average_item_level when 'level_60' then l.level_60 else l.members_read end desc nulls last, + l.members_read desc,l.name,l.region,l.slug +limit least(greatest(coalesce(p_limit,50),0),100) offset greatest(coalesce(p_offset,0),0); +$$; +revoke all on function public.armory_guild_directory(text, text, smallint, text, integer, integer) from public, anon, authenticated; +grant execute on function public.armory_guild_directory(text, text, smallint, text, integer, integer) to service_role; +notify pgrst, 'reload schema'; +reset lock_timeout; + +-- Readback (every row t): +-- select has_function_privilege('service_role','public.armory_guild_directory(text,text,smallint,text,integer,integer)','EXECUTE') +-- and not has_function_privilege('anon','public.armory_guild_directory(text,text,smallint,text,integer,integer)','EXECUTE') as ok; +-- select count(*) >= 0 as ok from public.armory_guild_directory(null,null,null,'members',1,0); +-- Rollback: +-- drop function if exists public.armory_guild_directory(text, text, smallint, text, integer, integer); +-- drop index if exists public.armory_characters_guild_directory; +-- notify pgrst, 'reload schema'; diff --git a/supabase/tests/armory_guild_directory.sql b/supabase/tests/armory_guild_directory.sql new file mode 100644 index 000000000..d5cd27b9b --- /dev/null +++ b/supabase/tests/armory_guild_directory.sql @@ -0,0 +1,82 @@ +-- Disposable database with the armory and guilds migrations and the guild directory applied. Invented identities only. +begin; + +select public.armory_upsert_characters('us', jsonb_build_array( + jsonb_build_object('slug','arla-quill','character_id',11,'name','Arla','surname','Quill','level',60,'ruleset_id',1,'ruleset','PvP', + 'race_id',1,'race','Human','class_id',8,'class','Mage','faction','Alliance','guild_slug','quill-watch','guild_name','Quill Watch','item_level',70,'equipment','[]'::jsonb), + jsonb_build_object('slug','brin-quill','character_id',12,'name','Brin','surname','Quill','level',42,'ruleset_id',1,'ruleset','PvP', + 'race_id',1,'race','Human','class_id',1,'class','Warrior','faction','Alliance','guild_slug','quill-watch','guild_name','Quill Watch','item_level',50,'equipment','[]'::jsonb), + jsonb_build_object('slug','cass-quill','character_id',13,'name','Cass','surname','Quill','level',60,'ruleset_id',1,'ruleset','PvP', + 'race_id',1,'race','Human','class_id',5,'class','Priest','faction','Alliance','guild_slug','quill-watch','guild_name','Quill Watch','item_level',90,'equipment','[]'::jsonb), + jsonb_build_object('slug','dorn-mire','character_id',14,'name','Dorn','surname','Mire','level',60,'ruleset_id',1,'ruleset','PvP', + 'race_id',2,'race','Orc','class_id',3,'class','Hunter','faction','Horde','guild_slug','mire-band','guild_name','Mire Band','item_level',85,'equipment','[]'::jsonb), + jsonb_build_object('slug','erra-mire','character_id',15,'name','Erra','surname','Mire','level',60,'ruleset_id',1,'ruleset','PvP', + 'race_id',2,'race','Orc','class_id',3,'class','Hunter','faction','Horde','guild_slug','mire-band','guild_name','Mire Band','item_level',85,'equipment','[]'::jsonb) +)); +select public.armory_upsert_characters('eu', jsonb_build_array( + jsonb_build_object('slug','fenn-quay','character_id',21,'name','Fenn','surname','Quay','level',30,'ruleset_id',2,'ruleset','Normal', + 'race_id',1,'race','Human','class_id',2,'class','Paladin','faction','Alliance','guild_slug','quay-hall','guild_name','Quay Hall','equipment','[]'::jsonb) +)); +select public.armory_upsert_guild('us','{"slug":"quill-watch","guild_id":1,"name":"Quill Watch","faction":"Alliance","ruleset_id":1,"ruleset":"PvP","member_count":40}','[]'); +select public.armory_upsert_guild('us','{"slug":"mire-band","guild_id":2,"name":"Mire Band","faction":"Horde","ruleset_id":1,"ruleset":"PvP","member_count":9}','[]'); +select public.armory_upsert_guild('eu','{"slug":"quay-hall","guild_id":3,"name":"Quay Hall","faction":"Alliance","ruleset_id":2,"ruleset":"Normal","member_count":5}','[]'); +select public.armory_upsert_guild('eu','{"slug":"quiet-few","guild_id":4,"name":"Quiet Few","faction":"Horde","ruleset_id":2,"ruleset":"Normal","member_count":2}','[]'); + +do $$ +declare r record; +begin + -- Default sort: characters read, then name. A guild with none read is still listed, with zeros and no average. + if (select array_agg(slug order by ordinality) from (select slug, row_number() over() as ordinality + from public.armory_guild_directory(null,null,null,'members',10,0)) x) <> array['quill-watch','mire-band','quay-hall','quiet-few'] then + raise exception 'members order'; + end if; + select * into r from public.armory_guild_directory(null,'us',null,'members',10,0) where slug='quill-watch'; + if r.members_read<>3 or r.level_60<>2 or r.average_item_level<>70.0 or r.member_count<>40 or r.total<>2 or r.fetched_at is null then + raise exception 'quill counts %', r; + end if; + select * into r from public.armory_guild_directory(null,'eu',null,'members',10,0) where slug='quiet-few'; + if r.members_read<>0 or r.level_60<>0 or r.average_item_level is not null then raise exception 'empty guild %', r; end if; + -- Item level: highest average first; a guild with no item level read sorts last. + if (select slug from public.armory_guild_directory(null,null,null,'item_level',1,0))<>'mire-band' then raise exception 'item level sort'; end if; + if (select slug from public.armory_guild_directory(null,null,null,'item_level',1,3)) not in ('quay-hall','quiet-few') then raise exception 'item level nulls last'; end if; + -- Level 60 count, with characters read breaking the tie (2 and 2: Quill Watch has 3 read). + if (select slug from public.armory_guild_directory(null,null,null,'level_60',1,0))<>'quill-watch' then raise exception 'level 60 sort'; end if; + -- Filters and paging. + if (select count(*) from public.armory_guild_directory(null,null,2::smallint,'members',10,0))<>2 then raise exception 'ruleset filter'; end if; + if (select count(*) from public.armory_guild_directory('Qu',null,null,'members',10,0))<>3 then raise exception 'prefix'; end if; + if (select count(*) from public.armory_guild_directory('qUi',null,null,'members',10,0))<>2 then raise exception 'prefix case'; end if; + if exists(select 1 from public.armory_guild_directory('Q',null,null,'members',10,0)) then raise exception 'one-letter prefix'; end if; + if exists(select 1 from public.armory_guild_directory('Q%',null,null,'members',10,0)) then raise exception 'wildcard prefix'; end if; + if (select array_agg(slug) from public.armory_guild_directory(null,null,null,'members',2,2)) <> array['quay-hall','quiet-few'] then raise exception 'page 2'; end if; + if (select min(total) from public.armory_guild_directory(null,null,null,'members',2,2))<>4 then raise exception 'total on a later page'; end if; + if (select count(*) from public.armory_guild_directory(null,null,null,'members',500,0))<>4 then raise exception 'limit cap'; end if; +end $$; + +-- A hidden character leaves every count at once. +select public.armory_hide('us','cass-quill'); +do $$ +declare r record; +begin + select * into r from public.armory_guild_directory(null,'us',null,'members',10,0) where slug='quill-watch'; + if r.members_read<>2 or r.level_60<>1 or r.average_item_level<>60.0 then raise exception 'hidden member counted %', r; end if; +end $$; + +-- A guild hide on a US realm hides the US guild of that name, not an EU one. +insert into public.guild_suppressions(realm_key,guild_key) values('camwow us1 realm 4 pvp','mire band'); +insert into public.guild_suppressions(realm_key,guild_key) values('camwow us1 realm 2 normal','quay hall'); +do $$ +begin + if exists(select 1 from public.armory_guild_directory(null,null,null,'members',10,0) where slug='mire-band') then raise exception 'hidden guild listed'; end if; + if not exists(select 1 from public.armory_guild_directory(null,null,null,'members',10,0) where slug='quay-hall') then raise exception 'hide crossed regions'; end if; + if (select min(total) from public.armory_guild_directory(null,null,null,'members',10,0))<>3 then raise exception 'total with a hidden guild'; end if; +end $$; + +do $$ +declare f text := 'public.armory_guild_directory(text,text,smallint,text,integer,integer)'; +begin + if has_function_privilege('anon',f,'EXECUTE') or has_function_privilege('authenticated',f,'EXECUTE') then raise exception 'public directory access'; end if; + if not has_function_privilege('service_role',f,'EXECUTE') then raise exception 'missing server directory access'; end if; + if not (select prosecdef and proconfig @> array['search_path=""','lock_timeout=3s'] from pg_proc where oid=f::regprocedure) then raise exception 'unsafe function'; end if; + if to_regclass('public.armory_characters_guild_directory') is null then raise exception 'missing index'; end if; +end $$; +rollback; diff --git a/web/src/app/armory/[region]/guilds/[slug]/page.tsx b/web/src/app/armory/[region]/guilds/[slug]/page.tsx index 773f8071c..c853e3526 100644 --- a/web/src/app/armory/[region]/guilds/[slug]/page.tsx +++ b/web/src/app/armory/[region]/guilds/[slug]/page.tsx @@ -3,16 +3,18 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { trailFor } from "@/lib/breadcrumbs"; import { cache } from "react"; -import { Container, DataTable, PageHeader, SectionHeading, type Column } from "@/components/ui"; +import { Container, DataTable, Facts, PageHeader, SectionHeading, type Column } from "@/components/ui"; import { armoryCharacterPath, armoryGuildPath, armoryOn, classTokenOfId, isArmoryRegion, metricValue, raceOfId, regionLabel, slugFromSegment, UNKNOWN, validArmorySlug, } from "@/lib/armory"; import { armoryStore, type ArmoryGuild, type ArmoryMember } from "@/lib/armory-store"; +import { armoryGuildHidden, GUILD_DIRECTORY_PATH, rosterSummary, type RosterSummary } from "@/lib/armory-guilds"; +import { playerStore } from "@/lib/player-store"; import { className, classText } from "@/app/players/player-view"; -import { ArmoryCredit, armoryMetadata, day, link, NOT_FOUND_METADATA, Unreachable } from "../../../parts"; +import { ArmoryCredit, armoryMetadata, day, link, NOT_FOUND_METADATA, RegionChip, Unreachable } from "../../../parts"; -/** Read on every request, so a hidden character leaves the roster at once. */ +/** Read on every request, so a hidden character leaves the roster, and a hidden guild the site, at once. */ export const dynamic = "force-dynamic"; type Params = { region: string; slug: string }; @@ -22,8 +24,13 @@ const load = cache(async (region: string, segment: string): Promise<{ guild: Arm if (!isArmoryRegion(region) || slug === null || !validArmorySlug(slug)) return null; try { const store = armoryStore(); - const [guild, roster] = await Promise.all([store.guild(region, slug), store.roster(region, slug)]); - return guild ? { guild, roster } : null; + // The guild hide list (/guilds/hide) is read too; without it the page is withheld, never shown unchecked. + // playerStore() can throw before returning a promise, so it runs inside an async function. + const reads = [store.guild(region, slug), store.roster(region, slug), (async () => playerStore().hiddenGuilds())()] as const; + // Let every read settle first: Promise.all alone would leave the later failures unhandled. + await Promise.allSettled(reads); + const [guild, roster, hidden] = await Promise.all(reads); + return guild && !armoryGuildHidden(hidden, guild.region, guild.name) ? { guild, roster } : null; } catch { return "unreachable"; } @@ -99,12 +106,14 @@ export default async function ArmoryGuildPage(props: { params: Promise }
Created {created} : undefined} /> + +
Roster {members.length === 0 @@ -117,3 +126,52 @@ export default async function ArmoryGuildPage(props: { params: Promise } ); } + +/** Roster size, members read, average item level and last read, then the class mix and the level spread. */ +function Summary({ guild: g, members, summary: s }: { guild: ArmoryGuild; members: ArmoryMember[]; summary: RosterSummary }) { + const read = members.filter((m) => m.stored).length; + const most = Math.max(1, ...s.levels.map((l) => l.count)); + return ( +
+ + Summary + + {g.ruleset} }, + { label: "On the roster", value: members.length.toLocaleString("en-US"), numeric: true }, + { label: "Members read", value: read.toLocaleString("en-US"), numeric: true }, + { + label: "Average item level", + value: s.averageItemLevel === null ? "Not read" : `${metricValue("item-level", s.averageItemLevel)} (${s.itemLevelsRead} read)`, + numeric: s.averageItemLevel !== null, + }, + { label: "Roster read", value: day(g.fetchedAt) ?? "Not known", numeric: true }, + ]} /> +
+
+

Class mix

+ {s.classes.length === 0 ?

No class listed.

: ( +
    + {s.classes.map((c) => ( +
  • {className(c.token)} {c.count}
  • + ))} +
+ )} +
+
+

Levels

+
+ {s.levels.map((l) => ( +
+
{l.label}
+ +
{l.count}
+
+ ))} +
+ {s.levelUnknown > 0 &&

{s.levelUnknown} without a level on the roster.

} +
+
+
+ ); +} diff --git a/web/src/app/armory/guild-directory.test.tsx b/web/src/app/armory/guild-directory.test.tsx new file mode 100644 index 000000000..4735161d9 --- /dev/null +++ b/web/src/app/armory/guild-directory.test.tsx @@ -0,0 +1,140 @@ +import type { ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { BLIZZARD_CREDIT } from "@/lib/armory"; +import { armoryCharacter, armoryGuild } from "@/lib/armory.fixture"; +import { createCloudArmoryStore, createMemoryArmoryStore, type ArmoryStore, type MemoryArmoryStore } from "@/lib/armory-store"; +import { playerStore } from "@/lib/player-store"; +import { StorageError } from "@/lib/supabase/server"; +import { STORAGE_UNREACHABLE } from "@/lib/upload-store"; + +vi.mock("next/link", () => ({ + default: ({ href, children, className }: { href: string; children: ReactNode; className?: string }) => {children}, +})); +vi.mock("next/navigation", () => ({ + notFound: () => { throw new Error("NEXT_NOT_FOUND"); }, + usePathname: () => "/armory/guilds", useRouter: () => ({ push: () => {} }), useSearchParams: () => new URLSearchParams(), +})); + +const holder = vi.hoisted(() => ({ store: null as ArmoryStore | null })); +vi.mock("@/lib/armory-store", async (importOriginal) => ({ ...(await importOriginal()), armoryStore: () => holder.store })); + +const held = globalThis as typeof globalThis & { __everlootPlayers?: unknown }; +let mem: MemoryArmoryStore; +beforeEach(() => { + held.__everlootPlayers = undefined; + mem = createMemoryArmoryStore(() => new Date("2026-11-10T00:00:00Z")); + mem.putCharacter(armoryCharacter()); + mem.putCharacter(armoryCharacter({ slug: "torvin-ashbrook", name: "Torvin", surname: "Ashbrook", class: "Warrior", classId: 1, level: 44, itemLevel: 50, fetchedAt: "2026-11-09T11:30:00.000Z" })); + mem.putGuild(armoryGuild(), [ + { characterSlug: "velkara-duskmantle", name: "Velkara", surname: "Duskmantle", level: 60, classId: 3, raceId: 8, rank: 1 }, + { characterSlug: "torvin-ashbrook", name: "Torvin", surname: "Ashbrook", level: 44, classId: 1, raceId: 2, rank: 2 }, + { characterSlug: "brannoc-tide", name: "Brannoc", surname: "Tide", level: 41, classId: 3, raceId: 10, rank: 0 }, + ]); + mem.putGuild(armoryGuild({ region: "us", slug: "ash-pact", name: "Ash Pact", faction: "Alliance", rulesetId: 1, ruleset: "PvP", memberCount: 9 }), []); + holder.store = mem; + vi.stubEnv("EVERLOOT_ARMORY", "1"); +}); +afterEach(() => { vi.unstubAllEnvs(); vi.resetModules(); held.__everlootPlayers = undefined; }); + +const pages = { + directory: async (search: Record = {}) => (await import("./guilds/page")).default({ searchParams: Promise.resolve(search) }), + guild: async (region: string, slug: string) => (await import("./[region]/guilds/[slug]/page")).default({ params: Promise.resolve({ region, slug }) }), + board: async (metric: string) => (await import("./rankings/[metric]/page")).default({ params: Promise.resolve({ metric }), searchParams: Promise.resolve({}) }), +}; +const html = async (page: Promise) => renderToStaticMarkup(await page); + +describe("the guild directory", () => { + test("is a 404 with the armory switch off", async () => { + vi.stubEnv("EVERLOOT_ARMORY", ""); + await expect(pages.directory()).rejects.toThrow("NEXT_NOT_FOUND"); + }); + + test("lists guilds by members read with region chips, counts, the credit and sort and filter links in the address", async () => { + const out = await html(pages.directory()); + expect(out.indexOf("Ember Wardens")).toBeLessThan(out.indexOf("Ash Pact")); + expect(out).toContain('href="/armory/eu/guilds/ember-wardens"'); + expect(out).toContain('data-region="us"'); + expect(out).toContain("text-region-eu"); + expect(out).toContain(">53.7<"); + expect(out).toContain(BLIZZARD_CREDIT); + expect(out).toContain('href="/armory/guilds?sort=item-level"'); + expect(out).toContain('href="/armory/guilds?sort=level-60"'); + expect(out).toContain('href="/armory/guilds?region=us"'); + expect(out).toContain('href="/armory/guilds?ruleset=roleplay-pvp"'); + }); + + test("searches by name prefix, keeps filters in the form, and says when nothing matches", async () => { + const found = await html(pages.directory({ q: "ash", region: "us" })); + expect(found).toContain("Ash Pact"); + expect(found).not.toContain("Ember Wardens"); + expect(found).toContain('name="region" value="us"'); + expect(await html(pages.directory({ q: "zz" }))).toContain("No guild read yet starts with “zz”."); + expect(await html(pages.directory({ q: "a1" }))).toContain("Type 2 to 24 letters"); + }); + + test("pages through the list with page in the address", async () => { + for (let i = 0; i < 55; i++) mem.putGuild(armoryGuild({ slug: `hall-${i}`, name: `Hall ${String(i).padStart(2, "0")}` }), []); + const first = await html(pages.directory()); + expect(first).toContain('href="/armory/guilds?page=2"'); + const second = await html(pages.directory({ page: "2" })); + expect(second).toContain("Hall 54"); + expect(second).not.toContain("Ember Wardens"); + }); + + test("a guild hidden through /guilds/hide is left out, as is a hidden character's count", async () => { + await playerStore().suppressGuild("CAMWOW US1 Realm 4 PvP", "Ash Pact"); + await mem.hide("eu", "torvin-ashbrook"); + const out = await html(pages.directory()); + expect(out).not.toContain("Ash Pact"); + expect(out).toContain(">57.4<"); + }); + + test("before the migration it says the directory is not ready, and a search still finds guilds by name", async () => { + const guild = { region: "eu", slug: "ember-wardens", name: "Ember Wardens", faction: "Horde", ruleset: "Normal", member_count: 3 }; + holder.store = createCloudArmoryStore((async (path: string) => { + if (path === "rpc/armory_guild_directory") throw new StorageError(404, "PGRST202", "missing"); + return path === "rpc/armory_search_guilds" ? [guild] : []; + }) as never); + const bare = await html(pages.directory()); + expect(bare).toContain("Counts and sorting start once the directory's database update is applied."); + expect(bare).not.toContain(STORAGE_UNREACHABLE); + const found = await html(pages.directory({ q: "emb" })); + expect(found).toContain('href="/armory/eu/guilds/ember-wardens"'); + expect(found).not.toContain("Members read"); + }); + + test("storage out of reach says so", async () => { + holder.store = createCloudArmoryStore((async () => { throw new StorageError(500, null, "down"); }) as never); + const out = await html(pages.directory()); + expect(out).toContain(STORAGE_UNREACHABLE); + expect(out).toContain(BLIZZARD_CREDIT); + }); +}); + +describe("the guild page summary", () => { + test("shows the class mix, the level spread, the average item level of members read and the roster read time", async () => { + const out = await html(pages.guild("eu", "ember-wardens")); + expect(out).toContain("Class mix"); + expect(out).toMatch(/text-class-hunter[^>]*>Hunter<\/span> ]*>2]*>Warrior<\/span> ]*>1 { + await mem.hide("eu", "torvin-ashbrook"); + const out = await html(pages.guild("eu", "ember-wardens")); + expect(out).not.toContain("Torvin"); + expect(out).not.toContain("Warrior"); + expect(out).toContain("57.4 (1 read)"); + await playerStore().suppressGuild("EU1 Realm 2 Normal", "Ember Wardens"); + await expect(pages.guild("eu", "ember-wardens")).rejects.toThrow("NEXT_NOT_FOUND"); + }); +}); + +test("ranking rows carry the region chip", async () => { + expect(await html(pages.board("item-level"))).toMatch(/data-region="eu"[^>]*>EU<\/span>Normal/); +}); diff --git a/web/src/app/armory/guilds/page.tsx b/web/src/app/armory/guilds/page.tsx new file mode 100644 index 000000000..a32eb82fa --- /dev/null +++ b/web/src/app/armory/guilds/page.tsx @@ -0,0 +1,147 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { trailFor } from "@/lib/breadcrumbs"; +import { Container, DataTable, EmptyState, FilterBar, Input, PageHeader, ResultStrip, type Column, type FilterControl } from "@/components/ui"; +import { ARMORY_REGIONS, ARMORY_RULESETS, armoryGuildPath, armoryOn, metricValue, regionLabel } from "@/lib/armory"; +import type { ArmoryGuildRow } from "@/lib/armory-store"; +import { + directoryPrefix, GUILD_DIRECTORY_PAGE, GUILD_DIRECTORY_PATH, GUILD_SORTS, guildDirectoryHref, guildDirectoryQuery, loadGuildDirectory, + rulesetSlug, type GuildDirectoryQuery, +} from "@/lib/armory-guilds"; +import { guildsOn } from "@/lib/guild-switch"; +import { playerStore } from "@/lib/player-store"; +import { ArmoryCredit, armoryMetadata, day, first, link, newest, NOT_FOUND_METADATA, RegionRuleset, Unreachable } from "../parts"; + +/** Read on every request: the filters are in the address, and a hide takes effect at once. */ +export const dynamic = "force-dynamic"; + +type Search = Record; + +export async function generateMetadata(): Promise { + if (!armoryOn()) return NOT_FOUND_METADATA; + return armoryMetadata({ + title: "WoW Forever Guild Directory", + description: "WoW: Forever guilds Everloot has read from Blizzard's API, by members read, average item level and level 60 characters.", + path: GUILD_DIRECTORY_PATH, + }); +} + +const number = (n: number) => n.toLocaleString("en-US"); +const muted = (text: string) => {text}; + +function columns(counted: boolean): Column[] { + const all: Column[] = [ + { key: "name", header: "Guild", cell: (g) => {g.name} }, + { key: "where", header: "Region", nowrap: true, cell: (g) => }, + { key: "faction", header: "Faction", nowrap: true, cell: (g) => g.faction }, + { key: "roster", header: "Roster", numeric: true, cell: (g) => number(g.memberCount) }, + { key: "read", header: "Members read", numeric: true, cell: (g) => number(g.membersRead) }, + { key: "il", header: "Avg item level", numeric: true, cell: (g) => (g.averageItemLevel === null ? muted("Not read") : metricValue("item-level", g.averageItemLevel)) }, + { key: "l60", header: "Level 60", numeric: true, cell: (g) => number(g.level60) }, + { key: "at", header: "Last read", numeric: true, cell: (g) => {day(g.fetchedAt)} }, + ]; + // Before the directory's migration only the name, region, faction and roster size are known. + return counted ? all : all.filter((c) => ["name", "where", "faction", "roster"].includes(c.key)); +} + +function controls(d: GuildDirectoryQuery): FilterControl[] { + const href = (over: Partial) => guildDirectoryHref({ ...d, page: 1, ...over }); + return [ + { + type: "menu", key: "sort", label: `Sort: ${GUILD_SORTS.find((s) => s.slug === d.sort)!.label}`, + options: GUILD_SORTS.map((s) => ({ label: s.label, href: href({ sort: s.slug }), on: d.sort === s.slug, reset: s.slug === "members" })), + }, + { + type: "menu", key: "region", label: d.region ? regionLabel(d.region) : "Region", + options: [ + { label: "All regions", href: href({ region: null }), on: d.region === null, reset: true }, + ...ARMORY_REGIONS.map((r) => ({ label: regionLabel(r), href: href({ region: r }), on: d.region === r })), + ], + }, + { + type: "menu", key: "ruleset", label: ARMORY_RULESETS.find((r) => r.id === d.ruleset)?.label ?? "Ruleset", + options: [ + { label: "All rulesets", href: href({ ruleset: null }), on: d.ruleset === null, reset: true }, + ...ARMORY_RULESETS.map((r) => ({ label: r.label, href: href({ ruleset: r.id }), on: d.ruleset === r.id })), + ], + }, + ]; +} + +/** The guild hide list, or null when it could not be read (then no guild is listed). */ +async function hiddenGuilds(): Promise | null> { + try { return await playerStore().hiddenGuilds(); } catch { return null; } +} + +export default async function GuildDirectoryPage(props: { searchParams: Promise }) { + if (!armoryOn()) notFound(); + const params = await props.searchParams; + const raw = (first(params.q) ?? "").trim().slice(0, 24); + const invalid = directoryPrefix(raw) === "invalid"; + const d = guildDirectoryQuery(params); + const dir = await loadGuildDirectory(d, await hiddenGuilds()); + const active = [d.region, d.ruleset, d.prefix].filter((v) => v !== null).length + (d.sort === "members" ? 0 : 1); + const clearHref = guildDirectoryHref({}); + const ruleset = ARMORY_RULESETS.find((r) => r.id === d.ruleset); + + return ( + +
+ r.fetchedAt))} />} + /> +
+ + + {d.region && } + {ruleset && } + {d.sort !== "members" && } + +
+ {invalid &&

Type 2 to 24 letters from the start of the guild's name.

} + + {dir.state === "unreachable" ? : ( + <> + 0 && ( + guildDirectoryHref({ ...d, page })} /> + )} + /> + {dir.state === "not-ready" && ( +

+ Counts and sorting start once the directory's database update is applied. + {d.prefix ? " Until then a search finds guilds by name." : " Until then, search a guild by name."} +

+ )} + {dir.rows.length === 0 + ? 1 && dir.total > 0 ? "No guilds on this page." + : d.prefix ? `No guild read yet starts with “${d.prefix}”.` + : dir.state === "ready" ? "No guild matches these filters yet." : "No guild to list yet." + } /> + : `${g.region}/${g.slug}`} + meta={(g) => `${regionLabel(g.region)} ${g.ruleset} · ${number(g.memberCount)} on the roster`} + />} + + )} +

+ Members read counts the characters the armory has read whose guild this is; the roster is Blizzard's own count. + {guildsOn() && <> Raid progression comes from members' uploads, on Guilds.} +

+
+
+ ); +} diff --git a/web/src/app/armory/no-ads.test.ts b/web/src/app/armory/no-ads.test.ts index 50faad568..017c3d66d 100644 --- a/web/src/app/armory/no-ads.test.ts +++ b/web/src/app/armory/no-ads.test.ts @@ -21,7 +21,7 @@ test("no armory file places an ad", () => { // Not placing a slot is not enough: AdSense Auto ads fills any page its script loads on. The armory is on the ad-free // list, so the script never loads there (components/OptionalScripts.tsx) and a move to it loads a new document. test("the armory is an ad-free path, so the ad script never loads on it", () => { - for (const path of ["/armory", "/armory/us/a-character", "/armory/eu/guilds/a-guild", "/armory/rankings/item-level", "/armory/submit"]) { + for (const path of ["/armory", "/armory/us/a-character", "/armory/eu/guilds/a-guild", "/armory/guilds", "/armory/rankings/item-level", "/armory/submit"]) { expect(isAdFreePath(path), path).toBe(true); } expect(isAdFreePath("/armoryx")).toBe(false); diff --git a/web/src/app/armory/page.tsx b/web/src/app/armory/page.tsx index 4ab5bc95d..696b0be61 100644 --- a/web/src/app/armory/page.tsx +++ b/web/src/app/armory/page.tsx @@ -8,6 +8,8 @@ import { armoryGuildPath, armoryNameQuery, armoryOn, classTokenOfName, regionLabel, SEARCH_RULE, } from "@/lib/armory"; import { armoryStore, type ArmoryCount, type ArmoryGuildHit, type ArmoryHit } from "@/lib/armory-store"; +import { armoryGuildHidden, GUILD_DIRECTORY_PATH } from "@/lib/armory-guilds"; +import { playerStore } from "@/lib/player-store"; import { classText } from "@/app/players/player-view"; import { ArmoryCredit, armoryMetadata, first, link, newest, NOT_FOUND_METADATA, Unreachable } from "./parts"; @@ -81,7 +83,14 @@ export default async function ArmoryPage(props: { searchParams: Promise<{ q?: st const [counts, characters, guilds] = await Promise.all([ store.counts().catch(() => null), results(q, armoryNameQuery, (p) => store.search(p, SEARCH_LIMIT)), - results(g, guildQuery, (p) => store.searchGuilds(p, SEARCH_LIMIT)), + // A guild hidden through /guilds/hide is left out; without the hide list no guild is listed. + results(g, guildQuery, async (p) => { + // Both reads settle before either failure is raised, so neither rejection is left unhandled. + const reads = [store.searchGuilds(p, SEARCH_LIMIT), (async () => playerStore().hiddenGuilds())()] as const; + await Promise.allSettled(reads); + const [hits, hidden] = await Promise.all(reads); + return hits.filter((h) => !armoryGuildHidden(hidden, h.region, h.name)); + }), ]); return ( @@ -116,6 +125,7 @@ export default async function ArmoryPage(props: { searchParams: Promise<{ q?: st Rankings
    {ARMORY_METRICS.map((m) =>
  • {ARMORY_BOARDS[m].title}
  • )} +
  • Guild directory
diff --git a/web/src/app/armory/parts.tsx b/web/src/app/armory/parts.tsx index 6a2907989..d3fa1f983 100644 --- a/web/src/app/armory/parts.tsx +++ b/web/src/app/armory/parts.tsx @@ -1,6 +1,6 @@ import type { Metadata } from "next"; import { Card } from "@/components/ui"; -import { BLIZZARD_CREDIT, NAME_PATTERN, readLine, SURNAME_PATTERN } from "@/lib/armory"; +import { BLIZZARD_CREDIT, NAME_PATTERN, readLine, regionLabel, SURNAME_PATTERN } from "@/lib/armory"; import { pageMetadata } from "@/lib/seo"; import { STORAGE_UNREACHABLE } from "@/lib/upload-store"; @@ -27,6 +27,22 @@ export function ArmoryCredit({ at }: { at: string | null | undefined }) { ); } +const REGION_CHIP: Record = { us: "border-region-us text-region-us", eu: "border-region-eu text-region-eu" }; + +/** A region as a small coloured chip, "US" in blue and "EU" in gold, so a lopsided list shows at a glance. */ +export function RegionChip({ region }: { region: string }) { + return ( + + {regionLabel(region)} + + ); +} + +/** The chip, then the ruleset: where a character or guild plays. */ +export function RegionRuleset({ region, ruleset }: { region: string; ruleset: string }) { + return {ruleset}; +} + export const Unreachable = () =>

{STORAGE_UNREACHABLE}

; /** Above a form when storage did not answer: the form still shows, and says sending may fail. */ diff --git a/web/src/app/armory/rankings/[metric]/page.tsx b/web/src/app/armory/rankings/[metric]/page.tsx index 21ac156a0..27ecffbd9 100644 --- a/web/src/app/armory/rankings/[metric]/page.tsx +++ b/web/src/app/armory/rankings/[metric]/page.tsx @@ -9,7 +9,7 @@ import { } from "@/lib/armory"; import { armoryStore, type ArmoryBoardRow } from "@/lib/armory-store"; import { classText } from "@/app/players/player-view"; -import { ArmoryCredit, armoryMetadata, link, newest, NOT_FOUND_METADATA, Unreachable } from "../../parts"; +import { ArmoryCredit, armoryMetadata, link, newest, NOT_FOUND_METADATA, RegionRuleset, Unreachable } from "../../parts"; export const revalidate = 1800; @@ -57,7 +57,7 @@ function columns(metric: ArmoryMetric): Column[] { { key: "class", header: "Class", nowrap: true, cell: (r) => {r.class} }, { key: "race", header: "Race", nowrap: true, cell: (r) => r.race }, { key: "guild", header: "Guild", cell: (r) => r.guildName ?? None }, - { key: "where", header: "Realm", nowrap: true, cell: (r) => {regionLabel(r.region)} {r.ruleset} }, + { key: "where", header: "Realm", nowrap: true, cell: (r) => }, { key: "value", header: ARMORY_BOARDS[metric].column, numeric: true, cell: (r) => {metricValue(metric, r.value)} }, ]; } diff --git a/web/src/app/guilds/guilds.test.tsx b/web/src/app/guilds/guilds.test.tsx index 94792d19a..60a9d95b4 100644 --- a/web/src/app/guilds/guilds.test.tsx +++ b/web/src/app/guilds/guilds.test.tsx @@ -227,6 +227,19 @@ test("the hub's search finds guilds by the start of the name", async () => { expect(await hub({ q: "x" })).toContain("Type 2 to 24 letters"); }); +test("with the armory on, the hub links the armory's guild directory and carries a search over that its rule takes", async () => { + on(); + expect(await hub()).not.toContain("/armory/guilds"); + vi.stubEnv("EVERLOOT_ARMORY", "1"); + const plain = await hub(); + expect(plain).toContain('href="/armory/guilds"'); + expect(plain).not.toContain("Search it for"); + const searched = await hub({ q: "Nig" }); + expect(searched).toContain('href="/armory/guilds?q=nig"'); + expect(searched).toContain("1 guild starting with"); + expect(await hub({ q: "Night Watch" })).not.toContain("Search it for"); +}); + test("a players table that cannot be read leaves the hub's search as it was, and marks the answer partial", async () => { on(); vi.stubEnv("EVERLOOT_PLAYER_PAGES", "1"); diff --git a/web/src/app/guilds/page.tsx b/web/src/app/guilds/page.tsx index 547db5db3..642433e39 100644 --- a/web/src/app/guilds/page.tsx +++ b/web/src/app/guilds/page.tsx @@ -5,6 +5,7 @@ import { trailFor } from "@/lib/breadcrumbs"; import { Card, Container, DataTable, EmptyState, FilterBar, Input, PageHeader, ResultStrip, SectionHeading, type Column, type FilterControl } from "@/components/ui"; import { FAMILIES } from "@/data/families"; import { armoryOn } from "@/lib/armory"; +import { directoryPrefix, guildDirectoryHref } from "@/lib/armory-guilds"; import { dataAgeLabel } from "@/lib/data-age"; import { factionLabel, guildPath, guildSearchPrefix, guildsOn, ladderHref, loadGuildData, loadGuildRealms, loadGuildSearch, loadLadder, parseLadderQuery, raidsOpen, realmPath, @@ -140,7 +141,7 @@ export default async function GuildsPage(props: { searchParams: Promise meta={!data.unreachable && {dataAgeLabel(data.dataAsOf)}} />
- {armoryOn() &&

Guild rosters as Blizzard's API lists them are in the armory.

} + {armoryOn() && }
@@ -233,6 +234,22 @@ export default async function GuildsPage(props: { searchParams: Promise ); } +/** + * The armory's guild directory, linked rather than shown here: it is Blizzard's API data, which may only appear on + * an ad-free page, and /guilds is not one. A search typed here carries over when the armory's search rule takes it. + */ +function ArmoryDirectoryLine({ q }: { q: string }) { + const prefix = directoryPrefix(q); + const searched = typeof prefix === "string" && prefix !== "invalid" ? prefix : null; + return ( +

+ Every guild read from Blizzard's API, with its members, class mix and item level, is in the{" "} + guild directory. + {searched && <> Search it for “{searched}”.} +

+ ); +} + /** Before the first agreed kill: the start line, then what the ladder will hold. */ function StartState({ line }: { line: string }) { return ( diff --git a/web/src/design/tokens.ts b/web/src/design/tokens.ts index a7f992b4c..75eb58525 100644 --- a/web/src/design/tokens.ts +++ b/web/src/design/tokens.ts @@ -166,7 +166,7 @@ export type TokenName = | "canvas" | "panel" | "line" | "edge" | "fg" | "fg-2" | "muted" | "accent" | "danger" | "warning" | "tooltip" | "tooltip-border" | "tooltip-inner" | "accent-hover" | "blue-post" | `q-${(typeof QUALITIES)[number]}` | `class-${(typeof CLASSES)[number]}` | "chat-whisper" | "chat-guild" - | `realm-${(typeof REALM_RULESETS)[number]}` | "tip-yellow" | "coin-gold" | "coin-silver" | "coin-copper"; + | `realm-${(typeof REALM_RULESETS)[number]}` | "region-us" | "region-eu" | "tip-yellow" | "coin-gold" | "coin-silver" | "coin-copper"; // Tooltip frames stay dark in both modes, as in the game. const tooltip = { tooltip: "#080C18", "tooltip-border": "#5B6B8C", "tooltip-inner": "#26324F" } as const; @@ -212,6 +212,9 @@ export const tokens: Record> = { "realm-rp": "#73B3FF", "realm-rp-pvp": "#FF8040", "realm-hardcore": "#FFD100", + // An armory region's chip (app/armory/parts.tsx RegionChip): blue Americas, gold Europe. + "region-us": "#5CB8FF", + "region-eu": "#F2C230", // Item tooltip lines (components/ui/TooltipLines.tsx): the game's yellow for the item level, a set and the // flavour text, and the three coin metals of a sell price. "tip-yellow": "#FFD100", @@ -255,6 +258,8 @@ export const tokens: Record> = { "realm-rp": "#0057AD", "realm-rp-pvp": "#A84B00", "realm-hardcore": "#746500", + "region-us": "#0057AD", + "region-eu": "#7A5C00", "tip-yellow": "#746500", "coin-gold": "#7A5C00", "coin-silver": "#5E5E66", @@ -268,6 +273,7 @@ export const TEXT_TOKENS: TokenName[] = [ ...CLASSES.map((c) => `class-${c}` as const), "chat-whisper", "chat-guild", ...REALM_RULESETS.map((r) => `realm-${r}` as const), + "region-us", "region-eu", "tip-yellow", "coin-gold", "coin-silver", "coin-copper", ]; diff --git a/web/src/lib/armory-guilds.test.ts b/web/src/lib/armory-guilds.test.ts new file mode 100644 index 000000000..1483fed2f --- /dev/null +++ b/web/src/lib/armory-guilds.test.ts @@ -0,0 +1,157 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; +import { armoryCharacter, armoryGuild } from "./armory.fixture"; +import { createCloudArmoryStore, createMemoryArmoryStore, type ArmoryStore, type MemoryArmoryStore } from "./armory-store"; +import { guildHideKey } from "./player-store"; +import { StorageError } from "./supabase/server"; + +const holder = vi.hoisted(() => ({ store: null as ArmoryStore | null })); +vi.mock("./armory-store", async (importOriginal) => ({ ...(await importOriginal()), armoryStore: () => holder.store })); + +const { + armoryGuildHidden, directoryPrefix, GUILD_DIRECTORY_PAGE, guildDirectoryHref, guildDirectoryQuery, loadGuildDirectory, rosterSummary, +} = await import("./armory-guilds"); + +let mem: MemoryArmoryStore; +beforeEach(() => { + mem = createMemoryArmoryStore(() => new Date("2026-11-10T00:00:00Z")); + holder.store = mem; +}); + +/** Three guilds: Ember Wardens (EU Normal, 3 read), Ash Pact (US PvP, 1 read), Empty Hall (EU Normal, none read). */ +function fill() { + mem.putGuild(armoryGuild(), []); + mem.putGuild(armoryGuild({ region: "us", slug: "ash-pact", name: "Ash Pact", rulesetId: 1, ruleset: "PvP", memberCount: 12 }), []); + mem.putGuild(armoryGuild({ slug: "empty-hall", name: "Empty Hall", memberCount: 4, fetchedAt: "2026-11-01T00:00:00.000Z" }), []); + mem.putCharacter(armoryCharacter({ slug: "velkara-duskmantle", itemLevel: 60, level: 60 })); + mem.putCharacter(armoryCharacter({ slug: "torvin-ashbrook", name: "Torvin", surname: "Ashbrook", itemLevel: 50, level: 52, fetchedAt: "2026-11-09T12:00:00.000Z" })); + mem.putCharacter(armoryCharacter({ slug: "nyra-coldwell", name: "Nyra", surname: "Coldwell", itemLevel: null, level: 60 })); + mem.putCharacter(armoryCharacter({ region: "us", slug: "brask-ironhide", name: "Brask", surname: "Ironhide", guildSlug: "ash-pact", guildName: "Ash Pact", itemLevel: 80, level: 60, rulesetId: 1, ruleset: "PvP" })); +} + +describe("the directory's address", () => { + test("reads q, region, ruleset, sort and page, and drops what it does not know", () => { + expect(guildDirectoryQuery({ q: "Emb", region: "EU", ruleset: "roleplay-pvp", sort: "item-level", page: "3" })) + .toEqual({ prefix: "emb", region: "eu", ruleset: 15, sort: "item-level", page: 3 }); + expect(guildDirectoryQuery({ q: "e", region: "kr", ruleset: "4", sort: "dps", page: "-2" })) + .toEqual({ prefix: null, region: null, ruleset: null, sort: "members", page: 1 }); + expect(guildDirectoryQuery({ page: "1.5" }).page).toBe(1); + }); + + test("the search follows the armory's character search rule", () => { + expect(directoryPrefix(" Émber ")).toBe("émber"); + expect(directoryPrefix("")).toBeNull(); + for (const bad of ["E", "Em%", "Ember Wardens", "Em1"]) expect(directoryPrefix(bad)).toBe("invalid"); + }); + + test("writes only what differs from the defaults, and round-trips", () => { + expect(guildDirectoryHref({})).toBe("/armory/guilds"); + const q = { prefix: "emb", region: "us" as const, ruleset: 1, sort: "level-60" as const, page: 2 }; + const href = guildDirectoryHref(q); + expect(href).toBe("/armory/guilds?q=emb®ion=us&ruleset=pvp&sort=level-60&page=2"); + expect(guildDirectoryQuery(Object.fromEntries(new URL(href, "https://everloot.app").searchParams))).toEqual(q); + }); +}); + +describe("guild hides on armory guilds", () => { + const hidden = new Set([guildHideKey("CAMWOW US1 Realm 4 PvP", "Ash Pact")]); + test("a hide on a realm of a region covers the guild of that name in that region only", () => { + expect(armoryGuildHidden(hidden, "us", "Ash Pact")).toBe(true); + expect(armoryGuildHidden(hidden, "us", "ash pact")).toBe(true); + expect(armoryGuildHidden(hidden, "eu", "Ash Pact")).toBe(false); + expect(armoryGuildHidden(hidden, "us", "Ash Pactum")).toBe(false); + expect(armoryGuildHidden(new Set([guildHideKey("Forever Pioneer", "Ash Pact")]), "us", "Ash Pact")).toBe(false); + }); +}); + +describe("the directory", () => { + test("sorts by members read by default, with item level and level 60 as the other orders", async () => { + fill(); + const members = await loadGuildDirectory(guildDirectoryQuery({}), new Set()); + expect(members.state).toBe("ready"); + if (members.state !== "ready") return; + expect(members.rows.map((r) => r.slug)).toEqual(["ember-wardens", "ash-pact", "empty-hall"]); + expect(members.total).toBe(3); + expect(members.rows[0]).toMatchObject({ membersRead: 3, averageItemLevel: 55, level60: 2, fetchedAt: "2026-11-09T12:00:00.000Z" }); + expect(members.rows[2]).toMatchObject({ membersRead: 0, averageItemLevel: null, level60: 0 }); + + const il = await loadGuildDirectory(guildDirectoryQuery({ sort: "item-level" }), new Set()); + expect(il.state === "ready" && il.rows.map((r) => r.slug)).toEqual(["ash-pact", "ember-wardens", "empty-hall"]); + const l60 = await loadGuildDirectory(guildDirectoryQuery({ sort: "level-60" }), new Set()); + expect(l60.state === "ready" && l60.rows.map((r) => r.slug)).toEqual(["ember-wardens", "ash-pact", "empty-hall"]); + }); + + test("filters by search, region and ruleset, and pages", async () => { + fill(); + const search = await loadGuildDirectory(guildDirectoryQuery({ q: "em" }), new Set()); + expect(search.state === "ready" && search.rows.map((r) => r.slug)).toEqual(["ember-wardens", "empty-hall"]); + const us = await loadGuildDirectory(guildDirectoryQuery({ region: "us" }), new Set()); + expect(us.state === "ready" && us.rows.map((r) => r.slug)).toEqual(["ash-pact"]); + const pvp = await loadGuildDirectory(guildDirectoryQuery({ ruleset: "normal" }), new Set()); + expect(pvp.state === "ready" && pvp.rows.map((r) => r.slug)).toEqual(["ember-wardens", "empty-hall"]); + + for (let i = 0; i < GUILD_DIRECTORY_PAGE + 2; i++) mem.putGuild(armoryGuild({ slug: `zz-${i}`, name: `Zz ${i}` }), []); + const second = await loadGuildDirectory(guildDirectoryQuery({ page: "2" }), new Set()); + expect(second.state === "ready" && second.rows.length).toBe(5); + expect(second.state === "ready" && second.total).toBe(GUILD_DIRECTORY_PAGE + 5); + }); + + test("a hidden character is not counted; a hidden guild is not listed; no hide list means nothing listed", async () => { + fill(); + await mem.hide("eu", "velkara-duskmantle"); + const after = await loadGuildDirectory(guildDirectoryQuery({}), new Set([guildHideKey("EU2 Realm 1 Normal", "Empty Hall")])); + expect(after.state === "ready" && after.rows.map((r) => [r.slug, r.membersRead, r.level60])).toEqual([["ember-wardens", 2, 1], ["ash-pact", 1, 1]]); + expect(await loadGuildDirectory(guildDirectoryQuery({}), null)).toEqual({ state: "unreachable" }); + }); + + test("before the migration: no list without a search, the name search with one, and storage errors stay errors", async () => { + const guildRow = { region: "eu", slug: "ember-wardens", name: "Ember Wardens", faction: "Horde", ruleset: "Normal", member_count: 3 }; + const calls: string[] = []; + holder.store = createCloudArmoryStore((async (path: string) => { + calls.push(path); + if (path === "rpc/armory_guild_directory") throw new StorageError(404, "PGRST202", "Could not find the function"); + if (path === "rpc/armory_search_guilds") return [guildRow, { ...guildRow, region: "us", slug: "ember-two", name: "Ember Two", ruleset: "PvP" }]; + return []; + }) as never); + expect(await loadGuildDirectory(guildDirectoryQuery({}), new Set())).toEqual({ state: "not-ready", rows: [] }); + const found = await loadGuildDirectory(guildDirectoryQuery({ q: "emb", region: "eu" }), new Set()); + expect(found.state).toBe("not-ready"); + expect(found.state !== "unreachable" && found.rows.map((r) => [r.slug, r.rulesetId, r.memberCount])).toEqual([["ember-wardens", 2, 3]]); + expect(calls).toContain("rpc/armory_search_guilds"); + + holder.store = createCloudArmoryStore((async () => { throw new StorageError(500, null, "down"); }) as never); + expect(await loadGuildDirectory(guildDirectoryQuery({}), new Set())).toEqual({ state: "unreachable" }); + }); + + test("the cloud store reads the function's rows and its total", async () => { + let body: unknown; + const store = createCloudArmoryStore((async (_path: string, init?: RequestInit) => { + body = JSON.parse(String(init?.body)); + return [{ region: "us", slug: "ash-pact", name: "Ash Pact", faction: "Horde", ruleset_id: 1, ruleset: "PvP", member_count: 12, + members_read: 1, average_item_level: "80.0", level_60: 1, fetched_at: "2026-11-09T12:00:00+00:00", total: 7 }]; + }) as never); + const page = await store.guildDirectory({ prefix: null, region: "us", rulesetId: 1, sort: "level_60", limit: 50, offset: 50 }); + expect(body).toEqual({ p_prefix: null, p_region: "us", p_ruleset_id: 1, p_sort: "level_60", p_limit: 50, p_offset: 50 }); + expect(page).toEqual({ total: 7, rows: [expect.objectContaining({ slug: "ash-pact", averageItemLevel: 80, rulesetId: 1, level60: 1 })] }); + }); +}); + +describe("the roster summary", () => { + test("counts classes most first, bands levels, and averages only the item levels read", () => { + const m = (over: Partial[0][number]>) => ({ + characterSlug: "a-b", name: "A", surname: "B", level: 60, classId: 8, raceId: 1, rank: 1, itemLevel: null, gearScore: null, stored: false, ...over, + }); + const s = rosterSummary([ + m({ classId: 8, level: 60, itemLevel: 70, stored: true }), m({ classId: 8, level: 55, itemLevel: 61, stored: true }), + m({ classId: 1, level: 12 }), m({ classId: null, level: null }), m({ classId: 99, level: 41 }), + ]); + expect(s.classes).toEqual([{ token: "MAGE", count: 2 }, { token: "WARRIOR", count: 1 }]); + expect(s.levels).toEqual([ + { label: "60", count: 1 }, { label: "50–59", count: 1 }, { label: "40–49", count: 1 }, + { label: "30–39", count: 0 }, { label: "20–29", count: 0 }, { label: "1–19", count: 1 }, + ]); + expect(s.levelUnknown).toBe(1); + expect(s.averageItemLevel).toBe(65.5); + expect(s.itemLevelsRead).toBe(2); + expect(rosterSummary([]).averageItemLevel).toBeNull(); + }); +}); diff --git a/web/src/lib/armory-guilds.ts b/web/src/lib/armory-guilds.ts new file mode 100644 index 000000000..7dc7608ee --- /dev/null +++ b/web/src/lib/armory-guilds.ts @@ -0,0 +1,170 @@ +import { ARMORY_RULESETS, classTokenOfId, isArmoryRegion, SEARCH_RULE, type ArmoryRegion } from "./armory"; +import { armoryStore, type ArmoryGuildRow, type ArmoryGuildSort, type ArmoryMember } from "./armory-store"; + +/** + * The armory's guild directory (/armory/guilds) and the summary on an armory guild page, from Blizzard's API data. + * + * It is an armory page, not a section of /guilds: Blizzard's Developer API Terms allow no ad on a page that shows + * this data, and /armory is on the ad-free list while /guilds is not. /guilds keeps its ladder and its search over + * members' uploads and the players table, and links here, its search carrying over. The two lists are not merged row + * by row either: uploads name a guild by realm and name, the armory by region and slug, and nothing joins the two + * reliably yet, so one table holding both would double a guild or fold two different guilds into one. + * + * The filters live in the address: `q`, `region`, `ruleset`, `sort` and `page`. + */ + +export const GUILD_DIRECTORY_PATH = "/armory/guilds"; + +export const GUILD_DIRECTORY_PAGE = 50; + +export const GUILD_SORTS = [ + { slug: "members", key: "members", label: "Members read" }, + { slug: "item-level", key: "item_level", label: "Average item level" }, + { slug: "level-60", key: "level_60", label: "Level 60" }, +] as const satisfies readonly { slug: string; key: ArmoryGuildSort; label: string }[]; +export type GuildSortSlug = (typeof GUILD_SORTS)[number]["slug"]; + +/** "Roleplay PvP" -> "roleplay-pvp": a ruleset as the address names it. */ +export const rulesetSlug = (label: string) => label.toLowerCase().replace(/\s+/g, "-"); + +export interface GuildDirectoryQuery { + /** The start of a guild name, already checked by the caller's search rule; null to list every guild. */ + prefix: string | null; + region: ArmoryRegion | null; + ruleset: number | null; + sort: GuildSortSlug; + page: number; +} + +type Search = Record; +const one = (v: string | string[] | undefined) => (Array.isArray(v) ? v[0] : v); + +/** + * The start of a guild name the directory searches for, under the rule of the armory's character search: 2 to 24 + * letters, matched from the start of the name. Null for no search; "invalid" for text the rule refuses. + */ +export function directoryPrefix(raw: string | undefined): string | null | "invalid" { + const text = (raw ?? "").trim().slice(0, 24).normalize("NFC").toLowerCase(); + if (!text) return null; + return SEARCH_RULE.test(text) ? text : "invalid"; +} + +/** The directory's filters from the address; anything it does not know is dropped, never an error. */ +export function guildDirectoryQuery(search: Search): GuildDirectoryQuery { + const prefix = directoryPrefix(one(search.q)); + const region = one(search.region)?.toLowerCase(); + const rules = one(search.ruleset)?.toLowerCase(); + const sort = one(search.sort)?.toLowerCase(); + const page = Number(one(search.page)); + return { + prefix: prefix === "invalid" ? null : prefix, + region: isArmoryRegion(region) ? region : null, + ruleset: ARMORY_RULESETS.find((r) => rulesetSlug(r.label) === rules)?.id ?? null, + sort: GUILD_SORTS.find((s) => s.slug === sort)?.slug ?? "members", + page: Number.isInteger(page) && page > 1 && page <= 10_000 ? page : 1, + }; +} + +/** The address of a directory view; defaults (every region and ruleset, members read, page 1) are left out. */ +export function guildDirectoryHref(d: Partial): string { + const params = new URLSearchParams(); + if (d.prefix) params.set("q", d.prefix); + if (d.region) params.set("region", d.region); + const rules = ARMORY_RULESETS.find((r) => r.id === d.ruleset); + if (rules) params.set("ruleset", rulesetSlug(rules.label)); + if (d.sort && d.sort !== "members") params.set("sort", d.sort); + if (d.page && d.page > 1) params.set("page", String(d.page)); + const s = params.toString(); + return s ? `${GUILD_DIRECTORY_PATH}?${s}` : GUILD_DIRECTORY_PATH; +} + +/** + * Whether a guild hide (/guilds/hide, keyed by realm and name as `guildHideKey` writes it) covers an armory guild. The + * armory has no realm, so a hide on any realm whose name carries the region ("CAMWOW US1 Realm 4 PvP") hides the + * guild of that name in that region. The SQL directory applies the same rule. + */ +export function armoryGuildHidden(hidden: ReadonlySet, region: string, name: string): boolean { + const guild = name.trim().toLowerCase().replace(/\s+/g, " "); + const inRegion = new RegExp(`(^| )${region.toLowerCase()}[0-9]*( |$)`); + for (const key of hidden) { + const [realm, hiddenGuild] = key.split("\u0000"); + if (hiddenGuild === guild && realm !== undefined && inRegion.test(realm)) return true; + } + return false; +} + +export type GuildDirectory = + | { state: "ready"; rows: ArmoryGuildRow[]; total: number } + /** The migration is not applied: the guilds whose name starts with the search, without counts. */ + | { state: "not-ready"; rows: ArmoryGuildRow[] } + | { state: "unreachable" }; + +/** + * One page of the directory. `hidden` is the guild hide list (null when it could not be read: then no guild is + * listed, as /guilds lists none). A row it covers is dropped here too, so the development store, which knows no + * hides, follows the same rule as the SQL. + */ +export async function loadGuildDirectory(d: GuildDirectoryQuery, hidden: ReadonlySet | null): Promise { + if (hidden === null) return { state: "unreachable" }; + const shown = (rows: ArmoryGuildRow[]) => rows.filter((r) => !armoryGuildHidden(hidden, r.region, r.name)); + const store = armoryStore(); + try { + const sort = GUILD_SORTS.find((s) => s.slug === d.sort)!.key; + const page = await store.guildDirectory({ + prefix: d.prefix, region: d.region, rulesetId: d.ruleset, sort, limit: GUILD_DIRECTORY_PAGE, offset: (d.page - 1) * GUILD_DIRECTORY_PAGE, + }); + if (page) return { state: "ready", rows: shown(page.rows), total: page.total }; + if (!d.prefix) return { state: "not-ready", rows: [] }; + // Before the migration: the name search the armory already has, filtered here, with no counts to sort by. + const hits = await store.searchGuilds(d.prefix, GUILD_DIRECTORY_PAGE); + const rows = hits + .filter((h) => (d.region === null || h.region === d.region) && (d.ruleset === null || ARMORY_RULESETS.find((r) => r.id === d.ruleset)?.label === h.ruleset)) + .map((h): ArmoryGuildRow => ({ + region: h.region, slug: h.slug, name: h.name, faction: h.faction, ruleset: h.ruleset, + rulesetId: ARMORY_RULESETS.find((r) => r.label === h.ruleset)?.id ?? 0, memberCount: h.memberCount, + membersRead: 0, averageItemLevel: null, level60: 0, fetchedAt: "", + })); + return { state: "not-ready", rows: shown(rows) }; + } catch { + return { state: "unreachable" }; + } +} + +/** Level bands on a guild page, highest first. */ +export const LEVEL_BANDS = [ + { label: "60", min: 60, max: 60 }, + { label: "50–59", min: 50, max: 59 }, + { label: "40–49", min: 40, max: 49 }, + { label: "30–39", min: 30, max: 39 }, + { label: "20–29", min: 20, max: 29 }, + { label: "1–19", min: 1, max: 19 }, +] as const; + +export interface RosterSummary { + /** Class token ("MAGE") and count, most first; members whose class Blizzard did not give are left out. */ + classes: { token: string; count: number }[]; + levels: { label: string; count: number }[]; + /** Members whose level the roster does not give. */ + levelUnknown: number; + /** The average over members whose character has been read; null when none has. */ + averageItemLevel: number | null; + itemLevelsRead: number; +} + +/** The class mix, level spread and average item level of the roster as shown (hidden members are already out). */ +export function rosterSummary(members: readonly ArmoryMember[]): RosterSummary { + const classes = new Map(); + for (const m of members) { + const token = classTokenOfId(m.classId); + if (token) classes.set(token, (classes.get(token) ?? 0) + 1); + } + const levels = LEVEL_BANDS.map((b) => ({ label: b.label, count: members.filter((m) => m.level !== null && m.level >= b.min && m.level <= b.max).length })); + const read = members.map((m) => m.itemLevel).filter((v): v is number => v !== null); + return { + classes: [...classes].map(([token, count]) => ({ token, count })).sort((a, b) => b.count - a.count || a.token.localeCompare(b.token)), + levels, + levelUnknown: members.filter((m) => m.level === null || m.level < 1 || m.level > 60).length, + averageItemLevel: read.length ? Math.round((read.reduce((a, b) => a + b, 0) / read.length) * 10) / 10 : null, + itemLevelsRead: read.length, + }; +} diff --git a/web/src/lib/armory-store.ts b/web/src/lib/armory-store.ts index e4cb4e728..aaa33fa20 100644 --- a/web/src/lib/armory-store.ts +++ b/web/src/lib/armory-store.ts @@ -1,6 +1,6 @@ import { z } from "zod"; import { ARMORY_RECHECK_DAYS, armoryNameQuery, namesFromSlug, SEARCH_RULE, type ArmoryMetricKey } from "./armory"; -import { authQuery } from "./supabase/server"; +import { authQuery, StorageError } from "./supabase/server"; import { ArmoryDetails, type ProfileDetails } from "../../../kb/src/armory/details"; import type { CharacterRow } from "../../../kb/src/armory/parse"; @@ -38,6 +38,17 @@ export interface ArmoryMember { export interface ArmoryHit { region: string; slug: string; name: string; surname: string; level: number; class: string; race: string; ruleset: string; guildName: string | null } export interface ArmoryGuildHit { region: string; slug: string; name: string; faction: string; ruleset: string; memberCount: number } +/** How the guild directory sorts: characters read, their average item level, or how many of them are level 60. */ +export type ArmoryGuildSort = "members" | "item_level" | "level_60"; +export interface ArmoryGuildFilter { prefix: string | null; region: string | null; rulesetId: number | null; sort: ArmoryGuildSort; limit: number; offset: number } +/** One guild in the directory: its roster size from Blizzard, and what the armory has read of its characters. */ +export interface ArmoryGuildRow { + region: string; slug: string; name: string; faction: string; rulesetId: number; ruleset: string; memberCount: number; + membersRead: number; averageItemLevel: number | null; level60: number; fetchedAt: string; +} +/** One page of the directory and how many guilds the filters match. */ +export interface ArmoryGuildPage { rows: ArmoryGuildRow[]; total: number } + export interface ArmoryBoardRow { rank: number; region: string; slug: string; name: string; surname: string; level: number; class: string; race: string; faction: string; ruleset: string; rulesetId: number; guildName: string | null; value: number; fetchedAt: string; @@ -56,6 +67,11 @@ export interface ArmoryStore { /** Characters whose first name, surname or "first surname" starts with `prefix` (2 letters or more), name then surname order. */ search(prefix: string, limit: number): Promise; searchGuilds(prefix: string, limit: number): Promise; + /** + * One page of the guild directory (20261117170000_armory_guild_directory.sql), hidden characters out of every count. + * Null while that migration is not applied, so the page can say the directory is not ready rather than down. + */ + guildDirectory(filter: ArmoryGuildFilter): Promise; /** One board, highest first; a null region or ruleset means all of them. */ board(metric: ArmoryMetricKey, region: string | null, rulesetId: number | null, limit: number): Promise; rank(region: string, slug: string): Promise; @@ -135,6 +151,11 @@ const GuildHitRow = z.object({ region: z.string(), slug: z.string(), name: z.string(), faction: z.string(), ruleset: z.string(), member_count: num, }).transform((r): ArmoryGuildHit => ({ region: r.region, slug: r.slug, name: r.name, faction: r.faction, ruleset: r.ruleset, memberCount: r.member_count })); +const DirectoryRow = z.object({ + region: z.string(), slug: z.string(), name: z.string(), faction: z.string(), ruleset_id: num, ruleset: z.string(), member_count: num, + members_read: num, average_item_level: numOrNull, level_60: num, fetched_at: z.string(), total: num, +}); + const BoardRow = z.object({ rank: num, region: z.string(), slug: z.string(), name: z.string(), surname: z.string(), level: num, class: z.string(), race: z.string(), faction: z.string(), ruleset: z.string(), ruleset_id: num, guild_name: textOrNull, value: num, fetched_at: z.string(), @@ -162,6 +183,25 @@ export function createCloudArmoryStore(query: Query = authQuery): ArmoryStore { async roster(region, slug) { return rpc("armory_roster", { p_region: region, p_slug: slug }, z.array(MemberRow)); }, async search(prefix, limit) { return rpc("armory_search", { p_prefix: prefix, p_limit: limit }, z.array(HitRow)); }, async searchGuilds(prefix, limit) { return rpc("armory_search_guilds", { p_prefix: prefix, p_limit: limit }, z.array(GuildHitRow)); }, + async guildDirectory(f) { + let rows: z.output[]; + try { + rows = await rpc("armory_guild_directory", { + p_prefix: f.prefix, p_region: f.region, p_ruleset_id: f.rulesetId, p_sort: f.sort, p_limit: f.limit, p_offset: f.offset, + }, z.array(DirectoryRow)); + } catch (err) { + // PostgREST answers 404 PGRST202 (or 42883) for a function the database does not have yet. + if (err instanceof StorageError && err.status === 404 && (err.code === "PGRST202" || err.code === "42883")) return null; + throw err; + } + return { + total: rows[0]?.total ?? 0, + rows: rows.map((r) => ({ + region: r.region, slug: r.slug, name: r.name, faction: r.faction, rulesetId: r.ruleset_id, ruleset: r.ruleset, memberCount: r.member_count, + membersRead: r.members_read, averageItemLevel: r.average_item_level, level60: r.level_60, fetchedAt: r.fetched_at, + })), + }; + }, async board(metric, region, rulesetId, limit) { return rpc("armory_board", { p_metric: metric, p_region: region, p_ruleset_id: rulesetId, p_limit: limit }, z.array(BoardRow)); }, @@ -183,7 +223,7 @@ const unavailableReason = new WeakMap(); /** A store with nothing behind it: every call fails, so each page shows storage as out of reach. */ export function createUnavailableArmoryStore(reason: string): ArmoryStore { const fail = async (): Promise => { throw new Error(reason); }; - const store = { character: fail, guild: fail, roster: fail, search: fail, searchGuilds: fail, board: fail, rank: fail, counts: fail, hide: fail, enqueue: fail, refresh: fail, lookupRegions: fail, lookupMiss: fail, storeLookup: fail }; + const store = { character: fail, guild: fail, roster: fail, search: fail, searchGuilds: fail, guildDirectory: fail, board: fail, rank: fail, counts: fail, hide: fail, enqueue: fail, refresh: fail, lookupRegions: fail, lookupMiss: fail, storeLookup: fail }; unavailableReason.set(store, reason); return store; } @@ -251,6 +291,25 @@ export function createMemoryArmoryStore(now: () => Date = () => new Date()): Mem return [...guilds.values()].filter((g) => g.name.toLowerCase().startsWith(p)).sort((a, b) => a.name.localeCompare(b.name)).slice(0, limit) .map((g) => ({ region: g.region, slug: g.slug, name: g.name, faction: g.faction, ruleset: g.ruleset, memberCount: g.memberCount })); }, + async guildDirectory(f) { + const p = f.prefix === null ? null : prefixOf(f.prefix); + if (f.prefix !== null && !p) return { rows: [], total: 0 }; + const rows: ArmoryGuildRow[] = [...guilds.values()] + .filter((g) => (f.region === null || g.region === f.region) && (f.rulesetId === null || g.rulesetId === f.rulesetId) && (p === null || g.name.toLowerCase().startsWith(p))) + .map((g) => { + const read = [...characters.values()].filter((c) => c.region === g.region && c.guildSlug === g.slug); + const levels = read.map((c) => c.itemLevel).filter((v): v is number => v !== null); + const newest = [g.fetchedAt, ...read.map((c) => c.fetchedAt)].reduce((a, b) => (Date.parse(b) > Date.parse(a) ? b : a)); + return { + region: g.region, slug: g.slug, name: g.name, faction: g.faction, rulesetId: g.rulesetId, ruleset: g.ruleset, memberCount: g.memberCount, + membersRead: read.length, averageItemLevel: levels.length ? Math.round((levels.reduce((a, b) => a + b, 0) / levels.length) * 10) / 10 : null, + level60: read.filter((c) => c.level === 60).length, fetchedAt: newest, + }; + }); + const value = (r: ArmoryGuildRow) => (f.sort === "item_level" ? r.averageItemLevel : f.sort === "level_60" ? r.level60 : r.membersRead); + rows.sort((a, b) => (value(b) ?? -Infinity) - (value(a) ?? -Infinity) || b.membersRead - a.membersRead || a.name.localeCompare(b.name) || a.region.localeCompare(b.region)); + return { rows: rows.slice(f.offset, f.offset + Math.min(f.limit, 100)), total: rows.length }; + }, async board(metric, region, rulesetId, limit) { return ranked(metric, (c) => (region === null || c.region === region) && (rulesetId === null || c.rulesetId === rulesetId)).slice(0, limit).map((c, i) => ({ rank: i + 1, region: c.region, slug: c.slug, name: c.name, surname: c.surname, level: c.level, class: c.class, race: c.race, diff --git a/web/src/lib/breadcrumbs.ts b/web/src/lib/breadcrumbs.ts index 52b003d39..178eba005 100644 --- a/web/src/lib/breadcrumbs.ts +++ b/web/src/lib/breadcrumbs.ts @@ -26,6 +26,7 @@ const NAMES: Record = { "/armory": "Armory", "/armory/hide": "Hide a character", "/armory/submit": "Add a character", + "/armory/guilds": "Guild directory", "/showcase/character": "Sample character", "/about": "About", "/tools": "Tools", @@ -99,6 +100,7 @@ const PARENT: Record = { "/guilds/hide": "/guilds", "/armory/hide": "/armory", "/armory/submit": "/armory", + "/armory/guilds": "/armory", "/lore/coverage": "/lore", "/lore/npcs": "/lore", "/lore/items": "/lore",