diff --git a/frontend/src/api.js b/frontend/src/api.js
index 3678734..0e82e81 100644
--- a/frontend/src/api.js
+++ b/frontend/src/api.js
@@ -44,5 +44,8 @@ export const api = {
me: (token) => request('/api/me', { token }),
+ getMatches: (token, { start = 0, count = 20 } = {}) =>
+ request(`/api/matches?start=${start}&count=${count}`, { token }),
+
logout: (token) => request('/api/logout', { method: 'DELETE', token }),
}
diff --git a/frontend/src/components/MatchesModal.jsx b/frontend/src/components/MatchesModal.jsx
new file mode 100644
index 0000000..2f097f8
--- /dev/null
+++ b/frontend/src/components/MatchesModal.jsx
@@ -0,0 +1,240 @@
+import { useEffect, useState, useCallback } from 'react'
+import { api } from '../api'
+
+const PAGE_SIZE = 10
+
+function getMatchOutcome(match, userId) {
+ const isPlayer1 = match.player1?.id === userId
+
+ if (match.status === 'ongoing') {
+ return { type: 'ongoing', label: 'Не завершён' }
+ }
+ if (match.status === 'abandoned') {
+ return { type: 'abandoned', label: 'Не завершён' }
+ }
+ if (match.status === 'draw') {
+ return { type: 'draw', label: 'Ничья' }
+ }
+ if (match.status === 'player1_won') {
+ return isPlayer1
+ ? { type: 'victory', label: 'Победа' }
+ : { type: 'defeat', label: 'Поражение' }
+ }
+ if (match.status === 'player2_won') {
+ return isPlayer1
+ ? { type: 'defeat', label: 'Поражение' }
+ : { type: 'victory', label: 'Победа' }
+ }
+ return { type: 'ongoing', label: 'Не завершён' }
+}
+
+function formatDate(dateString) {
+ if (!dateString) return ''
+ try {
+ const date = new Date(dateString)
+ return new Intl.DateTimeFormat('ru-RU', {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ }).format(date)
+ } catch {
+ return dateString
+ }
+}
+
+function formatDuration(seconds) {
+ if (seconds == null) return '—'
+ const total = Math.max(0, Math.floor(seconds))
+ const minutes = Math.floor(total / 60)
+ const remainingSeconds = total % 60
+ if (minutes === 0) return `${remainingSeconds} сек`
+ if (remainingSeconds === 0) return `${minutes} мин`
+ return `${minutes} мин ${remainingSeconds} сек`
+}
+
+export default function MatchesModal({ token, user, onClose }) {
+ const [matches, setMatches] = useState([])
+ const [total, setTotal] = useState(null)
+ const [loading, setLoading] = useState(true)
+ const [loadingMore, setLoadingMore] = useState(false)
+ const [error, setError] = useState(null)
+
+ const loadMatches = useCallback(
+ async (offset, append = false) => {
+ if (append) {
+ setLoadingMore(true)
+ } else {
+ setLoading(true)
+ setError(null)
+ }
+
+ try {
+ const data = await api.getMatches(token, { start: offset, count: PAGE_SIZE })
+ setMatches((prev) => (append ? [...prev, ...(data.matches || [])] : data.matches || []))
+ if (typeof data.total === 'number') {
+ setTotal(data.total)
+ }
+ } catch (err) {
+ setError(err.message || 'Не удалось загрузить историю матчей')
+ } finally {
+ setLoading(false)
+ setLoadingMore(false)
+ }
+ },
+ [token]
+ )
+
+ useEffect(() => {
+ loadMatches(0, false)
+ }, [loadMatches])
+
+ useEffect(() => {
+ const handleKeyDown = (e) => {
+ if (e.key === 'Escape') onClose()
+ }
+ document.addEventListener('keydown', handleKeyDown)
+ return () => document.removeEventListener('keydown', handleKeyDown)
+ }, [onClose])
+
+ const handleLoadMore = () => {
+ if (loadingMore || loading) return
+ loadMatches(matches.length, true)
+ }
+
+ const hasMore = total != null ? matches.length < total : false
+
+ return (
+
+
e.stopPropagation()}>
+
+
+
+
Мои матчи
+ {total != null && (
+ Всего: {total}
+ )}
+
+
+
+ {loading && matches.length === 0 ? (
+
+
+
+
+
+
+
Загрузка истории матчей…
+
+ ) : error && matches.length === 0 ? (
+
+
{error}
+
+
+ ) : matches.length === 0 ? (
+
+
⚓
+
У вас пока нет сыгранных матчей
+
+ Сыграйте случайный бой, чтобы здесь появилась история ваших сражений!
+
+
+ ) : (
+
+ {matches.map((match) => {
+ const isPlayer1 = match.player1?.id === user?.id
+ const me = isPlayer1 ? match.player1 : match.player2
+ const opponent = isPlayer1 ? match.player2 : match.player1
+ const outcome = getMatchOutcome(match, user?.id)
+
+ return (
+
+ {/* Текущий пользователь всегда слева */}
+
+ {me?.avatar_url ? (
+

+ ) : (
+
+ {me?.nickname?.[0]?.toUpperCase()}
+
+ )}
+
+
+ {me?.nickname}
+
+ Вы
+
+
+
+ {/* Центр: исход, дата и длительность */}
+
+
+ {outcome.label}
+
+
+
+ {formatDate(match.started_at)}
+
+ •
+
+ {formatDuration(match.duration_seconds)}
+
+
+
+
+ {/* Соперник справа */}
+
+
+
+ {opponent?.nickname}
+
+ Соперник
+
+ {opponent?.avatar_url ? (
+

+ ) : (
+
+ {opponent?.nickname?.[0]?.toUpperCase()}
+
+ )}
+
+
+ )
+ })}
+
+ {hasMore && (
+
+
+
+ )}
+
+ )}
+
+
+
+ )
+}
diff --git a/frontend/src/components/ProfileBar.jsx b/frontend/src/components/ProfileBar.jsx
index ba1d290..d26d206 100644
--- a/frontend/src/components/ProfileBar.jsx
+++ b/frontend/src/components/ProfileBar.jsx
@@ -1,8 +1,36 @@
+import { useState, useRef, useEffect } from 'react'
import { useAuth, useAuthModal } from '../auth'
+import MatchesModal from './MatchesModal'
export default function ProfileBar() {
- const { user, loading, logout } = useAuth()
+ const { user, token, loading, logout } = useAuth()
const { openAuthModal } = useAuthModal()
+ const [menuOpen, setMenuOpen] = useState(false)
+ const [matchesModalOpen, setMatchesModalOpen] = useState(false)
+ const menuContainerRef = useRef(null)
+
+ useEffect(() => {
+ if (!menuOpen) return
+
+ const handlePointerDown = (e) => {
+ if (menuContainerRef.current && !menuContainerRef.current.contains(e.target)) {
+ setMenuOpen(false)
+ }
+ }
+
+ const handleKeyDown = (e) => {
+ if (e.key === 'Escape') {
+ setMenuOpen(false)
+ }
+ }
+
+ document.addEventListener('pointerdown', handlePointerDown)
+ document.addEventListener('keydown', handleKeyDown)
+ return () => {
+ document.removeEventListener('pointerdown', handlePointerDown)
+ document.removeEventListener('keydown', handleKeyDown)
+ }
+ }, [menuOpen])
return (
<>
@@ -10,18 +38,58 @@ export default function ProfileBar() {
{loading ? (
Загрузка…
) : user ? (
-
- {user.avatar_url ? (
-

- ) : (
-
- {user.nickname[0]?.toUpperCase()}
+
+ {menuOpen && (
+
+
)}
-
{user.nickname}
-
+
+
+
+
+
) : (
)}
+
+ {matchesModalOpen && (
+
setMatchesModalOpen(false)}
+ />
+ )}
>
)
}
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
index dc2b545..40ebcc7 100644
--- a/frontend/src/styles.css
+++ b/frontend/src/styles.css
@@ -295,12 +295,112 @@ input:not([type]), input[type="text"] {
backdrop-filter: blur(6px);
}
+.profile-user-wrapper {
+ position: relative;
+ display: flex;
+ align-items: center;
+}
+
.profile-user {
display: flex;
align-items: center;
gap: 12px;
}
+.profile-user-trigger {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ background: none;
+ border: none;
+ cursor: pointer;
+ padding: 6px 10px;
+ border-radius: 12px;
+ font-family: inherit;
+ color: inherit;
+ transition: background-color 0.18s ease, transform 0.1s ease;
+}
+
+.profile-user-trigger:hover {
+ background: rgba(47, 128, 237, 0.08);
+}
+
+.profile-user-trigger:active {
+ transform: scale(0.98);
+}
+
+.profile-dropup-arrow {
+ font-size: 11px;
+ color: var(--text-soft);
+ margin-left: 2px;
+ transition: transform 0.2s ease, color 0.2s ease;
+}
+
+.profile-user-trigger:hover .profile-dropup-arrow {
+ color: var(--primary);
+}
+
+.profile-dropup-arrow.open {
+ transform: rotate(180deg);
+ color: var(--primary);
+}
+
+.profile-dropup-menu {
+ position: absolute;
+ bottom: calc(100% + 12px);
+ left: 0;
+ background: #ffffff;
+ border: 1px solid rgba(30, 58, 95, 0.12);
+ border-radius: 16px;
+ box-shadow: 0 12px 32px rgba(30, 58, 95, 0.18);
+ padding: 8px;
+ min-width: 190px;
+ z-index: 50;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ animation: dropup-fade-in 0.15s cubic-bezier(0.16, 1, 0.3, 1);
+}
+
+@keyframes dropup-fade-in {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+.profile-menu-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 10px 14px;
+ border: none;
+ background: transparent;
+ border-radius: 10px;
+ color: var(--text);
+ font-family: inherit;
+ font-size: 15px;
+ font-weight: 700;
+ cursor: pointer;
+ text-align: left;
+ transition: background-color 0.15s ease, color 0.15s ease;
+}
+
+.profile-menu-item:hover {
+ background: var(--primary-soft);
+ color: var(--primary-dark);
+}
+
+.profile-menu-icon {
+ flex-shrink: 0;
+ color: var(--primary);
+}
+
.profile-avatar {
width: 44px;
height: 44px;
@@ -1127,3 +1227,285 @@ body.is-dragging * {
transform: rotate(-90deg) !important;
}
}
+
+/* Окно истории матчей */
+.matches-modal {
+ width: min(720px, 96vw);
+ max-height: 85vh;
+ padding: 28px;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+}
+
+.matches-modal-header {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ gap: 12px;
+}
+
+.matches-total-badge {
+ font-size: 13px;
+ font-weight: 700;
+ background: var(--primary-soft);
+ color: var(--primary-dark);
+ padding: 3px 10px;
+ border-radius: 20px;
+}
+
+.matches-modal-content {
+ overflow-y: auto;
+ padding-right: 4px;
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 200px;
+}
+
+.matches-loading {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 16px;
+ padding: 48px 0;
+ color: var(--text-soft);
+ font-weight: 600;
+}
+
+.matches-empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 48px 16px;
+ text-align: center;
+ gap: 10px;
+}
+
+.matches-empty-icon {
+ font-size: 48px;
+ margin-bottom: 6px;
+}
+
+.matches-empty-title {
+ font-size: 20px;
+ font-weight: 700;
+ color: var(--text);
+}
+
+.matches-empty-desc {
+ font-size: 15px;
+ color: var(--text-soft);
+ max-width: 380px;
+}
+
+.matches-error-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 36px 16px;
+ gap: 14px;
+ color: var(--danger);
+ font-weight: 600;
+ text-align: center;
+}
+
+.matches-list {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+/* Карточка матча */
+.match-card {
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ align-items: center;
+ gap: 16px;
+ padding: 14px 18px;
+ background: #fbfdff;
+ border: 1.5px solid rgba(30, 58, 95, 0.1);
+ border-radius: 16px;
+ box-shadow: 0 2px 8px rgba(30, 58, 95, 0.04);
+ transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
+}
+
+.match-card:hover {
+ transform: translateY(-1px);
+ border-color: rgba(47, 128, 237, 0.35);
+ box-shadow: 0 4px 14px rgba(30, 58, 95, 0.08);
+}
+
+.match-card-side {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ min-width: 0;
+}
+
+.match-side-me {
+ justify-content: flex-start;
+}
+
+.match-side-opponent {
+ justify-content: flex-end;
+}
+
+.match-player-avatar {
+ width: 42px;
+ height: 42px;
+ border-radius: 50%;
+ object-fit: cover;
+ flex-shrink: 0;
+ border: 2px solid #fff;
+ box-shadow: 0 2px 6px rgba(30, 58, 95, 0.15);
+}
+
+.match-player-avatar-placeholder {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--primary);
+ color: #fff;
+ font-weight: 700;
+ font-size: 18px;
+}
+
+.match-side-opponent .match-player-avatar-placeholder {
+ background: #8b5cf6;
+}
+
+.match-player-info {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+
+.opponent-info {
+ align-items: flex-end;
+ text-align: right;
+}
+
+.match-player-name {
+ font-weight: 700;
+ font-size: 15px;
+ color: var(--text);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 140px;
+}
+
+.match-player-tag {
+ font-size: 11px;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.me-tag {
+ color: var(--primary);
+}
+
+.opponent-tag {
+ color: var(--text-soft);
+}
+
+/* Центральная колонка карточки матча */
+.match-card-center {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ text-align: center;
+}
+
+.match-outcome-badge {
+ font-size: 13px;
+ font-weight: 800;
+ padding: 4px 12px;
+ border-radius: 20px;
+ letter-spacing: 0.3px;
+ text-transform: uppercase;
+}
+
+.badge-victory {
+ background: #dcfce7;
+ color: #15803d;
+ box-shadow: 0 1px 4px rgba(21, 128, 61, 0.15);
+}
+
+.badge-defeat {
+ background: #fee2e2;
+ color: #b91c1c;
+ box-shadow: 0 1px 4px rgba(185, 28, 28, 0.15);
+}
+
+.badge-draw {
+ background: #e0f2fe;
+ color: #0369a1;
+ box-shadow: 0 1px 4px rgba(3, 105, 161, 0.15);
+}
+
+.badge-ongoing,
+.badge-abandoned {
+ background: #fef3c7;
+ color: #b45309;
+ box-shadow: 0 1px 4px rgba(180, 83, 9, 0.15);
+}
+
+.match-meta-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-soft);
+ white-space: nowrap;
+}
+
+.match-meta-divider {
+ font-size: 10px;
+ opacity: 0.6;
+}
+
+.matches-load-more-wrapper {
+ display: flex;
+ justify-content: center;
+ padding: 12px 0 4px;
+}
+
+.matches-load-more-btn {
+ font-size: 14px;
+ padding: 8px 24px;
+}
+
+@media (max-width: 640px) {
+ .matches-modal {
+ padding: 20px 16px;
+ }
+
+ .match-card {
+ grid-template-columns: 1fr;
+ gap: 12px;
+ padding: 12px;
+ }
+
+ .match-card-side {
+ justify-content: center;
+ }
+
+ .match-side-opponent {
+ flex-direction: row-reverse;
+ }
+
+ .opponent-info {
+ align-items: flex-start;
+ text-align: left;
+ }
+}
diff --git a/main-server/API.md b/main-server/API.md
index 85576c5..92cbd76 100644
--- a/main-server/API.md
+++ b/main-server/API.md
@@ -325,6 +325,72 @@ Action Cable использует формат JSON-сообщений чере
---
+### История матчей
+
+Возвращает постраничный список матчей текущего авторизованного пользователя, отсортированный от новых к старым (по дате начала `started_at`).
+
+**URL:** `GET /api/matches`
+
+**Auth:** требуется (JWT пользователя)
+
+**Параметры query string:**
+
+| Параметр | Тип | Обязательный | По умолчанию | Описание |
+|----------|-----|--------------|--------------|----------|
+| `start` / `from` | integer | — | `0` | Смещение (offset) от начала списка |
+| `count` | integer | — | `20` | Количество возвращаемых матчей (максимум 100) |
+
+**Пример запроса:**
+
+```bash
+curl -X GET "http://localhost:3000/api/matches?start=0&count=10" \
+ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
+```
+
+**Успешный ответ (200 OK):**
+
+```json
+{
+ "matches": [
+ {
+ "id": "145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f",
+ "status": "player1_won",
+ "game_server": "ws://localhost:8081/ws",
+ "started_at": "2026-11-09T12:00:00.000Z",
+ "finished_at": "2026-11-09T12:02:05.000Z",
+ "duration_seconds": 125,
+ "player1": {
+ "id": 1,
+ "nickname": "CaptainNemo",
+ "avatar_url": "http://localhost:3000/rails/active_storage/blobs/...",
+ "rating_before": 100,
+ "rating_change": 0
+ },
+ "player2": {
+ "id": 2,
+ "nickname": "CaptainHook",
+ "avatar_url": null,
+ "rating_before": 100,
+ "rating_change": 0
+ },
+ "your_rating_before": 100,
+ "your_rating_change": 0
+ }
+ ],
+ "total": 1,
+ "start": 0,
+ "count": 10
+}
+```
+
+**Ошибки:**
+
+| Код | Описание |
+|-----|----------|
+| `401` | отсутствует/невалиден токен |
+
+---
+
### Детали матча
Возвращает подробную информацию о матче: итог, длительность и дельту рейтинга
@@ -362,12 +428,14 @@ curl -X GET http://localhost:3000/api/matches/145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e
"player1": {
"id": 1,
"nickname": "CaptainNemo",
+ "avatar_url": "http://localhost:3000/rails/active_storage/blobs/...",
"rating_before": 100,
"rating_change": 0
},
"player2": {
"id": 2,
"nickname": "CaptainHook",
+ "avatar_url": null,
"rating_before": 100,
"rating_change": 0
},
diff --git a/main-server/app/controllers/api/matches_controller.rb b/main-server/app/controllers/api/matches_controller.rb
index 4c0ee7f..b0f4a51 100644
--- a/main-server/app/controllers/api/matches_controller.rb
+++ b/main-server/app/controllers/api/matches_controller.rb
@@ -2,6 +2,29 @@
# a non-participant (or an unknown uuid) gets 404 to avoid leaking
# information about other players' matches.
class Api::MatchesController < ApplicationController
+ def index
+ offset = (params[:start] || params[:from] || 0).to_i
+ offset = 0 if offset < 0
+
+ count = params[:count].present? ? params[:count].to_i : 20
+ count = 20 if count <= 0
+ count = 100 if count > 100
+
+ scope = Match.for_user(current_user)
+ .includes(player1: { avatar_attachment: :blob }, player2: { avatar_attachment: :blob })
+ .order(started_at: :desc, id: :desc)
+
+ total = scope.count
+ matches = scope.offset(offset).limit(count)
+
+ render json: {
+ matches: matches.map { |match| MatchSerializer.as_json(match, viewer: current_user) },
+ total: total,
+ start: offset,
+ count: count
+ }
+ end
+
def show
match = Match.for_user(current_user).find_by(uuid: params[:uuid])
return render json: { error: "Match not found" }, status: :not_found unless match
diff --git a/main-server/app/models/user.rb b/main-server/app/models/user.rb
index d1c7d1f..a074f66 100644
--- a/main-server/app/models/user.rb
+++ b/main-server/app/models/user.rb
@@ -22,6 +22,13 @@ class User < ApplicationRecord
.order(finished_at: :desc)
end
+ def avatar_url
+ return nil unless avatar.attached?
+
+ options = Rails.application.routes.default_url_options.presence || { host: "localhost", port: 3000 }
+ Rails.application.routes.url_helpers.rails_blob_url(avatar, options)
+ end
+
private
def avatar_content_type
unless avatar.blob.content_type.in?(%w[image/png image/jpeg image/gif image/webp])
diff --git a/main-server/app/serializers/match_serializer.rb b/main-server/app/serializers/match_serializer.rb
index c34adbd..8dbdee8 100644
--- a/main-server/app/serializers/match_serializer.rb
+++ b/main-server/app/serializers/match_serializer.rb
@@ -32,6 +32,7 @@ class MatchSerializer
{
id: user.id,
nickname: user.nickname,
+ avatar_url: user.avatar_url,
rating_before: rating_before,
rating_change: rating_change
}
diff --git a/main-server/config/routes.rb b/main-server/config/routes.rb
index 80b9dbd..618b035 100644
--- a/main-server/config/routes.rb
+++ b/main-server/config/routes.rb
@@ -11,6 +11,7 @@ Rails.application.routes.draw do
# (see app/channels/matchmaking_channel.rb).
# Match details for the participants of the match.
+ get "matches", to: "matches#index"
get "matches/:uuid", to: "matches#show"
# Intended for the game-server only; authenticated via HMAC (see
diff --git a/main-server/spec/models/user_spec.rb b/main-server/spec/models/user_spec.rb
index 7f85e19..3fe38ba 100644
--- a/main-server/spec/models/user_spec.rb
+++ b/main-server/spec/models/user_spec.rb
@@ -61,6 +61,23 @@ RSpec.describe User, type: :model do
end
end
+ describe "#avatar_url" do
+ let(:user) { User.create!(valid_attributes) }
+
+ it "returns nil when avatar is not attached" do
+ expect(user.avatar_url).to be_nil
+ end
+
+ it "returns full url when avatar is attached" do
+ user.avatar.attach(
+ io: StringIO.new("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15c4"),
+ filename: "avatar.png",
+ content_type: "image/png"
+ )
+ expect(user.avatar_url).to include("avatar.png")
+ end
+ end
+
describe "rating" do
it "defaults to the neutral initial value of 100" do
expect(User.create!(valid_attributes).rating).to eq(100)
diff --git a/main-server/spec/requests/api/matches_spec.rb b/main-server/spec/requests/api/matches_spec.rb
index 3a3a88b..c76163d 100644
--- a/main-server/spec/requests/api/matches_spec.rb
+++ b/main-server/spec/requests/api/matches_spec.rb
@@ -91,4 +91,129 @@ RSpec.describe "Match details API", type: :request do
expect(json["match"]["duration_seconds"]).to be_nil
end
end
+
+ describe "GET /api/matches" do
+ let!(:match1) do
+ Match.create!(
+ player1: player1,
+ player2: player2,
+ status: :player1_won,
+ game_server: "ws://game-server:8080/ws",
+ started_at: 20.minutes.ago,
+ finished_at: 10.minutes.ago,
+ duration_seconds: 600,
+ player1_rating_before: 100,
+ player2_rating_before: 100,
+ player1_rating_change: 12,
+ player2_rating_change: -12
+ )
+ end
+
+ let!(:match2) do
+ Match.create!(
+ player1: player2,
+ player2: player1,
+ status: :player2_won,
+ game_server: "ws://game-server:8080/ws",
+ started_at: 10.minutes.ago,
+ finished_at: 5.minutes.ago,
+ duration_seconds: 300,
+ player1_rating_before: 88,
+ player2_rating_before: 112,
+ player1_rating_change: -10,
+ player2_rating_change: 10
+ )
+ end
+
+ let!(:other_match) do
+ Match.create!(
+ player1: player2,
+ player2: outsider,
+ status: :player1_won,
+ game_server: "ws://game-server:8080/ws",
+ started_at: 5.minutes.ago,
+ finished_at: Time.current,
+ duration_seconds: 300,
+ player1_rating_before: 100,
+ player2_rating_before: 100,
+ player1_rating_change: 15,
+ player2_rating_change: -15
+ )
+ end
+
+ it "returns 401 without authentication" do
+ get "/api/matches"
+
+ expect(response).to have_http_status(:unauthorized)
+ end
+
+ it "returns the list of matches for current_user newest first" do
+ get "/api/matches", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
+
+ expect(response).to have_http_status(:ok)
+ json = JSON.parse(response.body)
+
+ expect(json["total"]).to eq(2)
+ expect(json["matches"].size).to eq(2)
+ expect(json["matches"].first["id"]).to eq(match2.uuid)
+ expect(json["matches"].second["id"]).to eq(match1.uuid)
+
+ first_item = json["matches"].first
+ expect(first_item["your_rating_change"]).to eq(10)
+ expect(first_item["player1"]["nickname"]).to eq("player_two")
+ expect(first_item["player2"]["nickname"]).to eq("player_one")
+ end
+
+ it "paginates results using start and count" do
+ get "/api/matches?start=1&count=1", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
+
+ expect(response).to have_http_status(:ok)
+ json = JSON.parse(response.body)
+
+ expect(json["total"]).to eq(2)
+ expect(json["start"]).to eq(1)
+ expect(json["count"]).to eq(1)
+ expect(json["matches"].size).to eq(1)
+ expect(json["matches"].first["id"]).to eq(match1.uuid)
+ end
+
+ it "supports from parameter as alias for start" do
+ get "/api/matches?from=1&count=1", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
+
+ expect(response).to have_http_status(:ok)
+ json = JSON.parse(response.body)
+
+ expect(json["start"]).to eq(1)
+ expect(json["matches"].size).to eq(1)
+ expect(json["matches"].first["id"]).to eq(match1.uuid)
+ end
+
+ it "returns an empty list when user has no matches" do
+ get "/api/matches", headers: { "Authorization" => "Bearer #{token_for(outsider)}" }
+
+ expect(response).to have_http_status(:ok)
+ json = JSON.parse(response.body)
+
+ expect(json["total"]).to eq(1) # outsider has other_match
+ expect(json["matches"].size).to eq(1)
+ expect(json["matches"].first["id"]).to eq(other_match.uuid)
+ end
+
+ it "includes player avatar_url if attached" do
+ player1.avatar.attach(
+ io: StringIO.new("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15c4"),
+ filename: "avatar.png",
+ content_type: "image/png"
+ )
+
+ get "/api/matches", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
+
+ expect(response).to have_http_status(:ok)
+ json = JSON.parse(response.body)
+ first_item = json["matches"].first
+ # in match2, player1 is player2 and player2 is player1
+ expect(first_item["player2"]["avatar_url"]).to include("avatar.png")
+ expect(first_item["player1"]["avatar_url"]).to be_nil
+ end
+ end
end