diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 9db574eb4..f523fe4ed 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -140,9 +140,11 @@ Commit counts include replies and quotes. Commit-based badges and XP use non-del Badges are calculated from current account data, not permanently recorded awards. Removing qualifying activity can reduce progress or lock a badge again; for example, unstarring a commit can remove **stargazer**. **Shell shocked** depends only on when the account was created, so deleting activity does not remove it. When a commit posted on the web unlocks a badge, a toast names it and confetti drops; clicking an unlocked badge drops confetti again. Unlocking a badge does not normally give bonus XP; **shell shocked** contributes **100 XP** once. XP otherwise comes from **10 per commit**, **15 per day in the longest streak**, **5 per star received**, **5 per reply to another developer**, and **2 per star given to another developer**. The **luddite** penalty applies once while the badge is unlocked, not once per unfollow, and total XP cannot fall below zero. A qualifying reply contributes both commit XP and reply XP; pastéis do not add XP. +The achievements dialog's **XP log** tab lists where the XP of the last 90 days came from, a day at a time: commits, replies to other developers, streak days, stars received and given, and the shell shocked bonus. It is read from the same activity as the total, with the same visibility, and loads only when opened. The luddite penalty has no date, so it appears in the breakdown but not in the log. + XP also determines your Unix rank: **user** at 0 XP, **daemon** at 50, **operator** at 150, **maintainer** at 400, **wheel** at 1,000, and **root** at 2,500. The achievements dialog's **Ranks** tab shows the levels and progress. Level-up notifications use your public progress, so pending or rejected commits do not trigger them. Each level above the starting rank can notify you only once, even if you lose and regain the XP; jumping ahead does not send a notification for every skipped level. -Sources: [badge definitions](app/Enums/Achievement.php), [unlock conditions and XP calculation](app/Queries/UserAchievementsQuery.php), [streak calculation](app/Queries/UserStreakQuery.php), [Unix ranks](app/Enums/UnixRank.php), [level-up notifications](app/Actions/CreateLevelNotification.php), [achievements dialog](resources/js/components/achievements-dialog.tsx). +Sources: [badge definitions](app/Enums/Achievement.php), [unlock conditions and XP calculation](app/Queries/UserAchievementsQuery.php), [XP log](app/Queries/UserXpLogQuery.php), [streak calculation](app/Queries/UserStreakQuery.php), [Unix ranks](app/Enums/UnixRank.php), [level-up notifications](app/Actions/CreateLevelNotification.php), [achievements dialog](resources/js/components/achievements-dialog.tsx). ### Following developers and suggestions diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 348ec66ae..4004609dd 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -19,6 +19,7 @@ use App\Queries\UserCommitsQuery; use App\Queries\UserModerationQuery; use App\Queries\UserStreakQuery; +use App\Queries\UserXpLogQuery; use App\Services\PageMetadata; use Illuminate\Container\Attributes\CurrentUser; use Illuminate\Http\RedirectResponse; @@ -32,7 +33,7 @@ /** * Profiles are public, so guests and crawlers read the same page, with the profile's link preview. */ - public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser, User $user, UserActivityQuery $activity, UserStreakQuery $streaks, UserAchievementsQuery $achievements, PushAccessQuery $pushAccess, UserCommitsQuery $commits, PinnedCommitQuery $pinned, UserModerationQuery $moderation, FollowersYouKnowQuery $followersYouKnow, GitHubReadmeQuery $readme, PageMetadata $metadata): Response + public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser, User $user, UserActivityQuery $activity, UserStreakQuery $streaks, UserAchievementsQuery $achievements, UserXpLogQuery $xpLog, PushAccessQuery $pushAccess, UserCommitsQuery $commits, PinnedCommitQuery $pinned, UserModerationQuery $moderation, FollowersYouKnowQuery $followersYouKnow, GitHubReadmeQuery $readme, PageMetadata $metadata): Response { $blockerId = $currentUser?->blockerIdWith($user); @@ -68,6 +69,7 @@ public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser 'activity' => fn (): array => $activity->get($user, $currentUser), 'streaks' => $getStreaks, 'achievements' => fn (): array => $achievements->get($user, $currentUser, $getStreaks()), + 'xpLog' => Inertia::optional(fn (): array => $xpLog->get($user, $currentUser)), 'moderation' => fn (): ?array => $currentUser?->isAdmin() === true && ! $user->isAdmin() ? $moderation->get([$user])[$user->id] : null, 'tab' => $request->tab(...), 'pinnedCommit' => fn (): ?Commit => $request->tab() === 'commits' ? $pinned->get($user, $currentUser) : null, diff --git a/app/Queries/UserXpLogQuery.php b/app/Queries/UserXpLogQuery.php new file mode 100644 index 000000000..b984c5ed4 --- /dev/null +++ b/app/Queries/UserXpLogQuery.php @@ -0,0 +1,134 @@ +} + */ +final readonly class UserXpLogQuery +{ + private const int DAYS = 90; + + /** + * Where the XP of the last 90 days came from, a day at a time, newest first. Days follow the activity graph and the + * streak: the date of `created_at`. Nothing is stored for this; it is read from the same commits and stars that make + * up the XP total, with the same visibility as the profile. + * + * @return list + */ + public function get(User $user, ?User $viewer): array + { + // Today is the first of the 90 days. + $since = CarbonImmutable::now()->subDays(self::DAYS - 1)->startOfDay(); + $visible = $user->commits()->visibleTo($viewer); + + /** @var Collection $commits */ + $commits = (clone $visible) + ->where('commits.created_at', '>=', $since) + ->leftJoin('commits as parents', fn (JoinClause $join): JoinClause => $join + ->on('parents.id', '=', 'commits.parent_id') + ->where('parents.user_id', '!=', $user->id)) + ->selectRaw('date(commits.created_at) as day, count(*) as commits, count(parents.id) as replies') + ->groupBy('day') + ->toBase() + ->get(); + + /** @var Collection $starsReceived */ + $starsReceived = DB::table('stars') + ->whereIn('commit_id', (clone $visible)->select('commits.id')) + ->where('user_id', '!=', $user->id) + ->where('created_at', '>=', $since) + ->selectRaw('date(created_at) as day, count(*) as count') + ->groupBy('day') + ->get(); + + /** @var Collection $starsGiven */ + $starsGiven = $user->starredCommits() + ->where('commits.user_id', '!=', $user->id) + ->where(fn (CommitBuilder $query): CommitBuilder => $query->visibleTo($viewer)) + ->where('stars.created_at', '>=', $since) + ->selectRaw('date(stars.created_at) as day, count(*) as count') + ->groupBy('day') + ->toBase() + ->get(); + + /** @var array> $days */ + $days = []; + $add = function (string $day, string $source, int $count, int $multiplier) use (&$days): void { + if ($count > 0) { + $days[$day][] = ['source' => $source, 'count' => $count, 'xp' => $count * $multiplier]; + } + }; + + foreach ($commits as $row) { + $add($row->day, 'commits', (int) $row->commits, 10); + $add($row->day, 'replies', (int) $row->replies, 5); + } + + foreach ($this->longestStreakDays($user, $viewer) as $day) { + if ($day >= $since->toDateString()) { + $add($day, 'streak', 1, 15); + } + } + + foreach ($starsReceived as $row) { + $add($row->day, 'stars_received', (int) $row->count, 5); + } + + foreach ($starsGiven as $row) { + $add($row->day, 'stars_given', (int) $row->count, 2); + } + + if ($user->created_at->lt('2026-10-21 14:00:00 UTC') && $user->created_at->gte($since)) { + $add($user->created_at->toDateString(), 'shell_shocked', 1, 100); + } + + krsort($days); + + return array_map(fn (string $day, array $entries): array => [ + 'date' => $day, + 'xp' => array_sum(array_column($entries, 'xp')), + 'entries' => $entries, + ], array_keys($days), $days); + } + + /** + * The days of the longest streak, the ones that earn streak XP, found the way the streak itself is counted. Equal + * streaks resolve to the most recent one. + * + * @return list + */ + private function longestStreakDays(User $user, ?User $viewer): array + { + /** @var list $days */ + $days = $user->commits() + ->visibleTo($viewer) + ->selectRaw('date(created_at) as day') + ->distinct() + ->orderBy('day') + ->pluck('day') + ->all(); + + $longest = []; + $run = []; + $previous = null; + + foreach ($days as $day) { + $date = CarbonImmutable::parse($day); + $run = $previous?->addDay()->isSameDay($date) ? [...$run, $day] : [$day]; + $longest = count($run) >= count($longest) ? $run : $longest; + $previous = $date; + } + + return $longest; + } +} diff --git a/resources/js/components/achievements-dialog.tsx b/resources/js/components/achievements-dialog.tsx index 392a93367..0ab146532 100644 --- a/resources/js/components/achievements-dialog.tsx +++ b/resources/js/components/achievements-dialog.tsx @@ -1,3 +1,4 @@ +import { router } from '@inertiajs/react'; import { Bomb, BotOff, @@ -15,7 +16,7 @@ import { Zap, } from 'lucide-react'; import type { CSSProperties } from 'react'; -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { DragonBallIcon } from '@/components/dragon-ball-icon'; import { Dialog, @@ -24,11 +25,18 @@ import { DialogHeader, DialogTitle, } from '@/components/ui/dialog'; +import { Skeleton } from '@/components/ui/skeleton'; import { WordmarkText } from '@/components/wordmark-text'; import { dropConfetti } from '@/lib/confetti'; import { formatCount, formatExactCount } from '@/lib/numbers'; -import { cn, laneTint } from '@/lib/utils'; -import type { Achievements, Profile, User } from '@/types'; +import { cn, formatFullDate, laneTint } from '@/lib/utils'; +import type { + Achievements, + Profile, + User, + XpLogDay, + XpLogEntry, +} from '@/types'; const iconMap: Record> = { terminal: Terminal, @@ -48,20 +56,66 @@ const iconMap: Record> = { 'dragon-ball': DragonBallIcon, }; +const xpSources: Record = { + commits: ['commit', 'commits'], + replies: ['reply to someone else', 'replies to others'], + streak: ['streak day', 'streak days'], + stars_received: ['star received', 'stars received'], + stars_given: ['star given', 'stars given'], + shell_shocked: ['shell shocked bonus', 'shell shocked bonus'], +}; + +function XpLogSkeleton() { + return ( +
+ {[0, 1, 2].map((index) => ( +
+
+ + +
+
+ + +
+
+ ))} +
+ ); +} + export function AchievementsDialog({ open, onOpenChange, achievements, + xpLog, user, lane, }: { open: boolean; onOpenChange: (open: boolean) => void; achievements: Achievements; + xpLog?: XpLogDay[]; user: User | Profile; lane: string; }) { - const [tab, setTab] = useState<'badges' | 'ranks'>('badges'); + const [tab, setTab] = useState<'badges' | 'ranks' | 'xp'>('badges'); + const [hasFailed, setHasFailed] = useState(false); + + // The log is only loaded once someone looks at it, so a profile visit stays as light as before. + useEffect(() => { + if (open && tab === 'xp' && xpLog === undefined) { + router.reload({ + only: ['xpLog'], + onStart: () => setHasFailed(false), + onError: () => setHasFailed(true), + onNetworkError: () => setHasFailed(true), + }); + } + }, [open, tab, xpLog]); const unlockedCount = achievements.badges.filter((b) => b.unlocked).length; const nextRank = achievements.ranks.find( @@ -162,6 +216,18 @@ export function AchievementsDialog({ > Unix Ranks ({achievements.ranks.length}) + {/* Badges Grid */} @@ -338,6 +404,72 @@ export function AchievementsDialog({ )} + {/* XP Log */} + {tab === 'xp' && ( +
+ {hasFailed ? ( +

+ The XP log couldn't be loaded. Try again in a + minute. +

+ ) : xpLog === undefined ? ( + + ) : xpLog.length === 0 ? ( +

+ No XP in the last 90 days. +

+ ) : ( +
    + {xpLog.map((day) => ( +
  1. +
    + + + +{formatExactCount(day.xp)} XP + +
    +
      + {day.entries.map((entry) => ( +
    • + + {entry.count}{' '} + { + xpSources[ + entry.source + ][ + entry.count === + 1 + ? 0 + : 1 + ] + } + + + +{entry.xp} + +
    • + ))} +
    +
  2. + ))} +
+ )} +
+ )} + {/* Dry Unix XP Formula Footnote */}

XP: 10/commit · 15/day streak · 5/star received · 5/reply · diff --git a/resources/js/pages/user/show.tsx b/resources/js/pages/user/show.tsx index 28cc13e3b..e95ab202e 100644 --- a/resources/js/pages/user/show.tsx +++ b/resources/js/pages/user/show.tsx @@ -54,6 +54,7 @@ import type { CursorPaginated, Profile, Streaks, + XpLogDay, } from '@/types'; function pluralize(count: number, singular: string, plural: string) { @@ -72,6 +73,7 @@ export default function Show({ activity, streaks, achievements, + xpLog, commits, tab, pinnedCommit, @@ -88,6 +90,7 @@ export default function Show({ activity: Activity; streaks: Streaks; achievements: Achievements; + xpLog?: XpLogDay[]; commits: CursorPaginated; tab: 'commits' | 'replies' | 'readme'; pinnedCommit: Commit | null; @@ -426,6 +429,7 @@ export default function Show({ open={isAchievementsOpen} onOpenChange={setIsAchievementsOpen} achievements={achievements} + xpLog={xpLog} user={user} lane={lane} /> diff --git a/resources/js/types/achievement.ts b/resources/js/types/achievement.ts index 91a9faa07..1d7335639 100644 --- a/resources/js/types/achievement.ts +++ b/resources/js/types/achievement.ts @@ -32,6 +32,24 @@ export type XpBreakdown = { shell_shocked: XpMetric; }; +export type XpLogEntry = { + source: + | 'commits' + | 'replies' + | 'streak' + | 'stars_received' + | 'stars_given' + | 'shell_shocked'; + count: number; + xp: number; +}; + +export type XpLogDay = { + date: string; + xp: number; + entries: XpLogEntry[]; +}; + export type Achievements = { level: number; rank: string; diff --git a/tests/Feature/Controllers/UserControllerTest.php b/tests/Feature/Controllers/UserControllerTest.php index 3bca2cec5..aeef372e4 100644 --- a/tests/Feature/Controllers/UserControllerTest.php +++ b/tests/Feature/Controllers/UserControllerTest.php @@ -41,6 +41,7 @@ ->where('isFollowing', true) ->where('followsYou', false) ->has('achievements') + ->missing('xpLog') ->has('commits.data', 2) ->where('commits.data.0.body', 'Newer') ->where('commits.data.0.user.handle', 'octocat') @@ -778,3 +779,21 @@ ->get(route('user.show', $user)) ->assertInertia(fn ($page) => $page->where('followersYouKnow', null)); }); + +it('loads the xp log only when the achievements dialog asks for it', function (): void { + $this->travelTo(now()->setDate(2026, 10, 22)->setTime(12, 0)); + $user = User::factory()->create(['handle' => 'octocat', 'created_at' => '2026-10-01 10:00:00']); + Commit::factory()->for($user)->create(['created_at' => '2026-10-21 09:00:00']); + + $this->withHeaders([ + 'X-Inertia' => 'true', + 'X-Inertia-Version' => (string) new HandleInertiaRequests()->version(request()), + 'X-Inertia-Partial-Component' => 'user/show', + 'X-Inertia-Partial-Data' => 'xpLog', + ])->get(route('user.show', $user))->assertOk() + ->assertJsonPath('props.xpLog.0.date', '2026-10-21') + ->assertJsonPath('props.xpLog.0.xp', 25) + ->assertJsonPath('props.xpLog.1.date', '2026-10-01') + ->assertJsonPath('props.xpLog.1.entries.0.source', 'shell_shocked') + ->assertJsonMissingPath('props.commits'); +}); diff --git a/tests/Unit/Queries/UserXpLogQueryTest.php b/tests/Unit/Queries/UserXpLogQueryTest.php new file mode 100644 index 000000000..032358476 --- /dev/null +++ b/tests/Unit/Queries/UserXpLogQueryTest.php @@ -0,0 +1,83 @@ +travelTo(now()->setDate(2026, 10, 22)->setTime(12, 0)); +}); + +it('lists where the xp of each day came from, newest first', function (): void { + $user = User::factory()->create(['created_at' => '2026-10-20 10:00:00']); + $other = User::factory()->create(); + $first = Commit::factory()->for($user)->create(['created_at' => '2026-10-20 09:00:00']); + Commit::factory()->for($user)->create(['created_at' => '2026-10-21 09:00:00']); + Commit::factory()->for($user)->create(['created_at' => '2026-10-21 10:00:00']); + $theirs = Commit::factory()->for($other)->create(['created_at' => '2026-10-21 08:00:00']); + Commit::factory()->for($user)->for($theirs, 'parent')->create(['created_at' => '2026-10-21 11:00:00']); + Commit::factory()->for($user)->for($first, 'parent')->create(['created_at' => '2026-10-21 12:00:00']); + $first->stars()->attach($other, ['created_at' => '2026-10-22 08:00:00', 'updated_at' => '2026-10-22 08:00:00']); + $first->stars()->attach($user, ['created_at' => '2026-10-22 08:00:00', 'updated_at' => '2026-10-22 08:00:00']); + $user->starredCommits()->attach($theirs, ['created_at' => '2026-10-22 09:00:00', 'updated_at' => '2026-10-22 09:00:00']); + + $log = resolve(UserXpLogQuery::class)->get($user, $user); + + expect($log)->toBe([ + ['date' => '2026-10-22', 'xp' => 7, 'entries' => [ + ['source' => 'stars_received', 'count' => 1, 'xp' => 5], + ['source' => 'stars_given', 'count' => 1, 'xp' => 2], + ]], + ['date' => '2026-10-21', 'xp' => 60, 'entries' => [ + ['source' => 'commits', 'count' => 4, 'xp' => 40], + ['source' => 'replies', 'count' => 1, 'xp' => 5], + ['source' => 'streak', 'count' => 1, 'xp' => 15], + ]], + ['date' => '2026-10-20', 'xp' => 125, 'entries' => [ + ['source' => 'commits', 'count' => 1, 'xp' => 10], + ['source' => 'streak', 'count' => 1, 'xp' => 15], + ['source' => 'shell_shocked', 'count' => 1, 'xp' => 100], + ]], + ]); +}); + +it('only counts the days of the longest streak', function (): void { + $user = User::factory()->create(); + foreach (['2026-10-10', '2026-10-11', '2026-10-12', '2026-10-15', '2026-10-16'] as $day) { + Commit::factory()->for($user)->create(['created_at' => "{$day} 09:00:00"]); + } + + $days = collect(resolve(UserXpLogQuery::class)->get($user, $user)) + ->filter(fn (array $day): bool => collect($day['entries'])->contains('source', 'streak')) + ->pluck('date')->all(); + + expect($days)->toBe(['2026-10-12', '2026-10-11', '2026-10-10']); +}); + +it('shows pending commits to their author only and leaves old days out', function (): void { + $user = User::factory()->create(['created_at' => '2026-05-01 10:00:00']); + Commit::factory()->for($user)->create(['status' => CommitStatus::Pending, 'created_at' => '2026-10-22 09:00:00']); + Commit::factory()->for($user)->create(['created_at' => '2026-07-01 09:00:00']); + + $query = resolve(UserXpLogQuery::class); + + expect($query->get($user, $user))->toBe([ + ['date' => '2026-10-22', 'xp' => 25, 'entries' => [ + ['source' => 'commits', 'count' => 1, 'xp' => 10], + ['source' => 'streak', 'count' => 1, 'xp' => 15], + ]], + ])->and($query->get($user, null))->toBe([]); +}); + +it('covers 90 calendar days, today included', function (): void { + $user = User::factory()->create(['created_at' => '2026-05-01 10:00:00']); + Commit::factory()->for($user)->create(['created_at' => '2026-07-25 09:00:00']); // day 90, counting today + Commit::factory()->for($user)->create(['created_at' => '2026-07-24 23:59:00']); // day 91, outside the log + + $dates = array_column(resolve(UserXpLogQuery::class)->get($user, $user), 'date'); + + expect($dates)->toBe(['2026-07-25']); +});