コミットを比較
1
コミット
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
efcc363537 |
@@ -0,0 +1,33 @@
|
||||
class SubmissionsController < ApplicationController
|
||||
def index
|
||||
page_value = params[:page].to_s
|
||||
page = page_value.match?(/\A[1-9][0-9]{0,5}\z/) ? page_value.to_i : 1
|
||||
scope = Submission.public_listing
|
||||
submissions = scope.includes(:user).order(created_at: :desc, id: :desc)
|
||||
.limit(Submission::PAGE_SIZE).offset((page - 1) * Submission::PAGE_SIZE)
|
||||
|
||||
render json: { submissions: submissions.map { repr(_1) },
|
||||
count: scope.count,
|
||||
page_size: Submission::PAGE_SIZE }
|
||||
end
|
||||
|
||||
def create
|
||||
return head :unauthorized unless current_user
|
||||
|
||||
submission = Submission.create!(
|
||||
params.permit(:category, :target_id, :content).merge(user: current_user))
|
||||
|
||||
render json: repr(submission), status: :created
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def repr(submission)
|
||||
{ id: submission.id,
|
||||
category: submission.category,
|
||||
target_id: submission.target_id,
|
||||
content: submission.content,
|
||||
user: UserRepr.base(submission.user),
|
||||
created_at: submission.created_at }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,49 @@
|
||||
class Submission < ApplicationRecord
|
||||
TARGETS = { 'post_removal' => [Post, PostVersion, :post_id],
|
||||
'tag_removal' => [Tag, TagVersion, :tag_id],
|
||||
'material_removal' => [Material, MaterialVersion, :material_id] }.freeze
|
||||
CATEGORIES = (TARGETS.keys + ['opinion']).freeze
|
||||
PAGE_SIZE = 20
|
||||
|
||||
belongs_to :user
|
||||
|
||||
validates :category, inclusion: { in: CATEGORIES }
|
||||
validates :content, presence: true, length: { maximum: 5000 }
|
||||
validates :target_id, absence: true, if: -> { category == 'opinion' }
|
||||
validates :target_id, numericality: { only_integer: true,
|
||||
greater_than: 0, less_than: 2**63 },
|
||||
if: -> { TARGETS.key?(category) }
|
||||
validate :validate_target
|
||||
|
||||
def self.target_scope(category)
|
||||
model, version_model = TARGETS.fetch(category)
|
||||
HistoryAccess.current(model.all, version_model)
|
||||
end
|
||||
|
||||
def self.public_listing
|
||||
return all if HistoryAccess.admin?
|
||||
|
||||
TARGETS.keys.reduce(where(category: 'opinion')) do |scope, category|
|
||||
_model, version_model, key = TARGETS.fetch(category)
|
||||
# Keep pre-removal submissions private even after the target is restored.
|
||||
boundaries = version_model.where(event_type: 'discard').where(
|
||||
version_model.arel_table[:version_no].gteq(arel_table[:target_version_no]))
|
||||
scope.or(where(category:, target_id: target_scope(category).select(:id))
|
||||
.where.not(target_version_no: nil)
|
||||
.where.not(target_id: boundaries.select(key)))
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_target
|
||||
return unless TARGETS.key?(category) && errors[:target_id].empty?
|
||||
target = self.class.target_scope(category).find_by(id: target_id)
|
||||
if target
|
||||
self.target_version_no = target.version_no if new_record?
|
||||
return
|
||||
end
|
||||
|
||||
errors.add(:target_id, :invalid)
|
||||
end
|
||||
end
|
||||
@@ -15,6 +15,7 @@ Rails.application.routes.draw do
|
||||
get 'counts/tags', to: 'counts_tags#index'
|
||||
|
||||
resources :locales, only: [:index]
|
||||
resources :submissions, only: [:index, :create]
|
||||
resources :sitemap_entries, only: [:index, :show], param: :resource
|
||||
|
||||
resources :tag_groups, only: [:index, :show, :create, :update]
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
class CreateSubmissions < ActiveRecord::Migration[8.0]
|
||||
def change
|
||||
create_table :submissions do |t|
|
||||
t.references :user, null: false, foreign_key: true
|
||||
t.string :category, null: false
|
||||
t.bigint :target_id
|
||||
t.integer :target_version_no
|
||||
t.text :content, null: false
|
||||
t.timestamps
|
||||
t.index [:created_at, :id]
|
||||
end
|
||||
end
|
||||
end
|
||||
生成ファイル
+15
-1
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
ActiveRecord::Schema[8.0].define(version: 2026_11_18_000000) do
|
||||
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "record_type", null: false
|
||||
@@ -439,6 +439,19 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
t.index ["user_id"], name: "index_settings_on_user_id", unique: true
|
||||
end
|
||||
|
||||
create_table "submissions", charset: "utf8mb4",
|
||||
collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.bigint "user_id", null: false
|
||||
t.string "category", null: false
|
||||
t.bigint "target_id"
|
||||
t.integer "target_version_no"
|
||||
t.text "content", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["created_at", "id"], name: "index_submissions_on_created_at_and_id"
|
||||
t.index ["user_id"], name: "index_submissions_on_user_id"
|
||||
end
|
||||
|
||||
create_table "tag_description_versions", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||
t.bigint "tag_id", null: false
|
||||
t.string "language_code", limit: 16, null: false
|
||||
@@ -816,6 +829,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_08_020000) do
|
||||
add_foreign_key "post_versions", "users", column: "created_by_user_id"
|
||||
add_foreign_key "posts", "users", column: "uploaded_user_id"
|
||||
add_foreign_key "settings", "users"
|
||||
add_foreign_key "submissions", "users"
|
||||
add_foreign_key "tag_description_versions", "tag_description_versions", column: ["tag_id", "source_language_code", "source_version_no"], primary_key: ["tag_id", "language_code", "version_no"]
|
||||
add_foreign_key "tag_descriptions", "languages", column: "language_code", primary_key: "code"
|
||||
add_foreign_key "tag_descriptions", "tag_description_versions", column: ["tag_id", "source_language_code", "source_version_no"], primary_key: ["tag_id", "language_code", "version_no"]
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
require 'rails_helper'
|
||||
|
||||
RSpec.describe 'Submissions', type: :request do
|
||||
let(:user) { create(:user) }
|
||||
let(:admin) { create(:user, :admin) }
|
||||
let(:opinion) { { category: 'opinion', content: '御意見です.' } }
|
||||
|
||||
def record_version(target, event_type)
|
||||
recorder = { Post => [PostVersionRecorder, :post],
|
||||
Tag => [TagVersionRecorder, :tag],
|
||||
Material => [MaterialVersionRecorder, :material] }.fetch(target.class)
|
||||
recorder.first.record!(**{ recorder.last => target },
|
||||
event_type:, created_by_user: admin)
|
||||
target.reload
|
||||
end
|
||||
|
||||
describe 'POST /submissions' do
|
||||
it 'requires an authenticated user' do
|
||||
expect { post '/submissions', params: opinion }
|
||||
.not_to change(Submission, :count)
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
['guest', 'member', 'admin'].each do |role|
|
||||
it "accepts opinions from #{ role } users using server identity" do
|
||||
actor = create(:user, role:)
|
||||
|
||||
expect {
|
||||
post '/submissions', params: opinion.merge(user_id: admin.id, role: 'admin'),
|
||||
headers: cookie_headers(actor)
|
||||
}.to change(Submission, :count).by(1)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(Submission.last.user).to eq(actor)
|
||||
expect(Submission.last.target_id).to be_nil
|
||||
expect(response.parsed_body.fetch('user')).to eq(
|
||||
{ 'id' => actor.id, 'name' => actor.name })
|
||||
expect(response.body).not_to include(actor.inheritance_code)
|
||||
end
|
||||
end
|
||||
|
||||
[{ content: '' }, { content: ' ' }, { content: 'x' * 5001 },
|
||||
{ category: 'unknown' }, { target_id: 1 }].each do |attributes|
|
||||
it "rejects invalid opinion attributes #{ attributes.keys }" do
|
||||
sign_in_as(user)
|
||||
|
||||
expect { post '/submissions', params: opinion.merge(attributes) }
|
||||
.not_to change(Submission, :count)
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(response.parsed_body.fetch('type')).to eq('validation_error')
|
||||
end
|
||||
end
|
||||
|
||||
it 'rejects banned users' do
|
||||
sign_in_as(create(:user, :banned))
|
||||
|
||||
expect { post '/submissions', params: opinion }
|
||||
.not_to change(Submission, :count)
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
|
||||
it 'rejects banned IP addresses for reads and writes' do
|
||||
create(:ip_address, :banned, ip_address: IPAddr.new('192.0.2.1').hton)
|
||||
headers = { 'REMOTE_ADDR' => '192.0.2.1' }
|
||||
sign_in_as(user)
|
||||
|
||||
expect { post '/submissions', params: opinion, headers: }
|
||||
.not_to change(Submission, :count)
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
|
||||
get '/submissions', headers:
|
||||
expect(response).to have_http_status(:forbidden)
|
||||
end
|
||||
end
|
||||
|
||||
describe 'GET /submissions' do
|
||||
it 'allows anonymous browsing without exposing user credentials' do
|
||||
submission = Submission.create!(**opinion, user:)
|
||||
|
||||
get '/submissions'
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
expect(response.parsed_body.fetch('submissions')).to contain_exactly(
|
||||
include('id' => submission.id, 'content' => opinion[:content],
|
||||
'user' => { 'id' => user.id, 'name' => user.name }))
|
||||
expect(response.body).not_to include(user.inheritance_code)
|
||||
expect(response.headers['Cache-Control']).to include('no-store')
|
||||
end
|
||||
|
||||
it 'paginates newest first with stable ordering and a public count' do
|
||||
submissions = Array.new(21) { Submission.create!(**opinion, user:) }
|
||||
|
||||
get '/submissions'
|
||||
expect(response.parsed_body.fetch('count')).to eq(21)
|
||||
expect(response.parsed_body.fetch('page_size')).to eq(20)
|
||||
expect(response.parsed_body.fetch('submissions').pluck('id'))
|
||||
.to eq(submissions.reverse.first(20).map(&:id))
|
||||
|
||||
get '/submissions', params: { page: 2 }
|
||||
expect(response.parsed_body.fetch('submissions').pluck('id'))
|
||||
.to eq([submissions.first.id])
|
||||
end
|
||||
end
|
||||
|
||||
['post_removal', 'tag_removal', 'material_removal'].each do |category|
|
||||
context category do
|
||||
let(:target) do
|
||||
case category
|
||||
when 'post_removal' then create(:post)
|
||||
when 'tag_removal' then create(:tag)
|
||||
when 'material_removal' then Material.create!(url: 'https://example.com/material')
|
||||
end
|
||||
end
|
||||
let(:attributes) { { category:, target_id: target.id, content: '除票を申請します.' } }
|
||||
|
||||
it 'stores a guest request without changing the target or its history' do
|
||||
sign_in_as(user)
|
||||
original = target.attributes
|
||||
version_model = Submission::TARGETS.fetch(category)[1]
|
||||
|
||||
expect {
|
||||
post '/submissions', params: attributes.merge(target_version_no: 99999)
|
||||
}.not_to change(version_model, :count)
|
||||
|
||||
expect(response).to have_http_status(:created)
|
||||
expect(target.reload.attributes).to eq(original)
|
||||
expect(Submission.last).to have_attributes(
|
||||
category:, target_id: target.id, target_version_no: target.version_no, user:)
|
||||
|
||||
sign_out
|
||||
get '/submissions'
|
||||
expect(response.parsed_body.fetch('submissions').pluck('id'))
|
||||
.to eq([Submission.last.id])
|
||||
end
|
||||
|
||||
[nil, 0, -1, '1.5', '1x', 2**63].each do |target_id|
|
||||
it "rejects invalid target ID #{ target_id.inspect }" do
|
||||
sign_in_as(user)
|
||||
|
||||
expect { post '/submissions', params: attributes.merge(target_id:) }
|
||||
.not_to change(Submission, :count)
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(response.parsed_body.fetch('errors')).to have_key('target_id')
|
||||
end
|
||||
end
|
||||
|
||||
it 'rejects a missing target' do
|
||||
sign_in_as(user)
|
||||
|
||||
post '/submissions', params: attributes.merge(target_id: 2**62)
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it 'hides pre-removal requests after restores and every later removal' do
|
||||
record_version(target, 'create')
|
||||
original = Submission.create!(**attributes, user:)
|
||||
record_version(target, 'discard')
|
||||
|
||||
sign_in_as(user)
|
||||
post '/submissions', params: attributes
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
boundary = HistoryAccess.set(user: admin) { Submission.create!(**attributes, user: admin) }
|
||||
|
||||
record_version(target, 'restore')
|
||||
restored = Submission.create!(**attributes, user:)
|
||||
|
||||
[nil, user, create(:user, :member)].each do |actor|
|
||||
sign_in_as(actor)
|
||||
get '/submissions', params: { role: 'admin' }
|
||||
expect(response.parsed_body.fetch('submissions').pluck('id')).to eq([restored.id])
|
||||
expect(response.parsed_body.fetch('count')).to eq(1)
|
||||
end
|
||||
|
||||
record_version(target, 'discard')
|
||||
record_version(target, 'restore')
|
||||
sign_out
|
||||
get '/submissions'
|
||||
expect(response.parsed_body.fetch('submissions')).to eq([])
|
||||
expect(response.parsed_body.fetch('count')).to eq(0)
|
||||
|
||||
sign_in_as(admin)
|
||||
get '/submissions'
|
||||
expect(response.parsed_body.fetch('submissions').pluck('id'))
|
||||
.to eq([restored.id, boundary.id, original.id])
|
||||
expect(response.parsed_body.fetch('count')).to eq(3)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -83,6 +83,7 @@ const MaterialSyncSuppressionsPage = lazyPage (
|
||||
() => import ('@/pages/materials/MaterialSyncSuppressionsPage'))
|
||||
const CountsResourcePage = lazyPage (() => import ('@/pages/counts/CountsResourcePage'))
|
||||
const MorePage = lazyPage (() => import ('@/pages/MorePage'))
|
||||
const SubmissionsPage = lazyPage (() => import ('@/pages/SubmissionsPage'))
|
||||
const GekanatorUnavailablePage = lazyPage (() => import ('@/pages/GekanatorUnavailablePage'))
|
||||
const NicoTagListPage = lazyPage (() => import ('@/pages/tags/NicoTagListPage'))
|
||||
const TOSPage = lazyPage (() => import ('@/pages/TOSPage'))
|
||||
@@ -217,6 +218,8 @@ export const pageRoutes = (
|
||||
handle: { preload: CountsResourcePage.preload, prefetch: false, robots: 'noindex' } },
|
||||
{ path: 'more', element: <MorePage/>,
|
||||
handle: { preload: MorePage.preload, sitemap: ['static'] } },
|
||||
{ path: 'submissions', element: <SubmissionsPage user={user}/>,
|
||||
handle: { preload: SubmissionsPage.preload, robots: 'noindex' } },
|
||||
{ path: '*', element: <NotFound/>, handle: { notFound: true } }]
|
||||
|
||||
|
||||
|
||||
@@ -129,6 +129,8 @@ export const menuOutline = (
|
||||
{ ...message ('list'), to: '/users', visible: false },
|
||||
{ ...message ('currentUser'), to: `/users/${ user?.id }`, visible: false },
|
||||
{ ...message ('settings'), to: '/users/settings', visible: Boolean (user) }] },
|
||||
{ ...message ('submissions'), visible: false, subMenu: [
|
||||
{ ...message ('list'), to: '/submissions' }] },
|
||||
{ ...message ('legal'), visible: false, subMenu: [
|
||||
{ ...message ('terms'), to: '/tos' }] }]
|
||||
}
|
||||
|
||||
@@ -11,6 +11,11 @@ export const localesKeys = {
|
||||
root: ['locales'] as const,
|
||||
index: ['locales', 'index'] as const }
|
||||
|
||||
export const submissionsKeys = {
|
||||
root: ['submissions'] as const,
|
||||
index: (page: number, locale: LocaleCode) =>
|
||||
['submissions', locale, 'index', page] as const }
|
||||
|
||||
export const postsKeys = {
|
||||
root: ['posts'] as const,
|
||||
index: (
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { apiGet, apiPost } from '@/lib/api'
|
||||
|
||||
import type { LocaleCode } from '@/lib/locales'
|
||||
import type { Submission, SubmissionCategory } from '@/types'
|
||||
|
||||
export type SubmissionIndex = { submissions: Submission[]
|
||||
count: number
|
||||
pageSize: number }
|
||||
|
||||
export const fetchSubmissions = (
|
||||
page: number,
|
||||
locale: LocaleCode,
|
||||
): Promise<SubmissionIndex> =>
|
||||
apiGet ('/submissions', { locale, params: { page } })
|
||||
|
||||
export const createSubmission = (
|
||||
attributes: { category: SubmissionCategory
|
||||
targetId: string
|
||||
content: string },
|
||||
locale: LocaleCode,
|
||||
): Promise<Submission> =>
|
||||
apiPost ('/submissions', { category: attributes.category,
|
||||
target_id: attributes.category === 'opinion' ? null : attributes.targetId,
|
||||
content: attributes.content }, { locale })
|
||||
@@ -26,5 +26,7 @@
|
||||
"terms": "エイワンケ イレンカ",
|
||||
"more": "モㇱマ アン ペ »",
|
||||
"counts": "ウコピㇱキ",
|
||||
"externalTags": "ソイタ シロシ"
|
||||
"externalTags": "ソイタ シロシ",
|
||||
"submissions": "$t(submissions:title)",
|
||||
"_untranslated": ["submissions"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"_untranslated": ["*"],
|
||||
"title": "申請・御意見板",
|
||||
"category": "種別",
|
||||
"targetId": "対象 ID",
|
||||
"submit": "送信",
|
||||
"error": "申請の取得に失敗しました.",
|
||||
"categories": {
|
||||
"post_removal": "投稿の除票申請",
|
||||
"tag_removal": "タグの除票申請",
|
||||
"material_removal": "素材の除票申請",
|
||||
"opinion": "御意見板"
|
||||
}
|
||||
}
|
||||
@@ -25,4 +25,5 @@
|
||||
"settings": "設定",
|
||||
"legal": "法規",
|
||||
"terms": "利用規約",
|
||||
"submissions": "$t(submissions:title)",
|
||||
"more": "その他 »" }
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"title": "申請・御意見板",
|
||||
"category": "種別",
|
||||
"targetId": "対象 ID",
|
||||
"submit": "送信",
|
||||
"error": "申請の取得に失敗しました.",
|
||||
"categories": {
|
||||
"post_removal": "投稿の除票申請",
|
||||
"tag_removal": "タグの除票申請",
|
||||
"material_removal": "素材の除票申請",
|
||||
"opinion": "御意見板"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import SubmissionsPage from '@/pages/SubmissionsPage'
|
||||
import { buildUser } from '@/test/factories'
|
||||
import { renderWithProviders } from '@/test/render'
|
||||
|
||||
const api = vi.hoisted (() => (
|
||||
{ apiGet: vi.fn (), apiPost: vi.fn (), isApiError: vi.fn () }))
|
||||
const toastApi = vi.hoisted (() => ({ toast: vi.fn () }))
|
||||
|
||||
vi.mock ('@/lib/api', () => api)
|
||||
vi.mock ('@/components/ui/use-toast', () => toastApi)
|
||||
|
||||
const opinion = { id: 1,
|
||||
category: 'opinion',
|
||||
targetId: null,
|
||||
content: '<script>public opinion</script>',
|
||||
user: { id: 2, name: 'reader' },
|
||||
createdAt: '2026-11-18T00:00:00Z' }
|
||||
|
||||
describe ('SubmissionsPage', () => {
|
||||
beforeEach (() => {
|
||||
vi.clearAllMocks ()
|
||||
api.apiGet.mockResolvedValue ({ submissions: [opinion], count: 1, pageSize: 20 })
|
||||
api.apiPost.mockResolvedValue ({ id: 2 })
|
||||
api.isApiError.mockReturnValue (false)
|
||||
})
|
||||
|
||||
it ('allows anonymous reading and renders submitted content as plain text', async () => {
|
||||
const { container } = renderWithProviders (<SubmissionsPage user={null}/>, {
|
||||
route: '/ja/submissions' })
|
||||
|
||||
expect (await screen.findByText (opinion.content)).toBeInTheDocument ()
|
||||
expect (container.querySelector ('script')).toBeNull ()
|
||||
expect (screen.getByRole ('button', { name: '送信' })).toBeDisabled ()
|
||||
})
|
||||
|
||||
for (const category of ['post_removal', 'tag_removal', 'material_removal'])
|
||||
{
|
||||
it (`submits ${category} for a guest and refreshes the public list`, async () => {
|
||||
renderWithProviders (<SubmissionsPage user={buildUser ({ role: 'guest' })}/>, {
|
||||
route: '/ja/submissions' })
|
||||
await screen.findByText (opinion.content)
|
||||
fireEvent.change (screen.getByRole ('combobox'), { target: { value: category } })
|
||||
fireEvent.change (screen.getByLabelText ('対象 ID'), { target: { value: '42' } })
|
||||
fireEvent.change (screen.getByLabelText ('内容'), { target: { value: '除票の理由' } })
|
||||
const calls = api.apiGet.mock.calls.length
|
||||
fireEvent.click (screen.getByRole ('button', { name: '送信' }))
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiPost).toHaveBeenCalledWith ('/submissions', {
|
||||
category, target_id: '42', content: '除票の理由' }, { locale: 'ja' })
|
||||
expect (api.apiGet.mock.calls.length).toBeGreaterThan (calls)
|
||||
expect (screen.getByLabelText ('内容')).toHaveValue ('')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
it ('submits opinions without a target and preserves free text', async () => {
|
||||
renderWithProviders (<SubmissionsPage user={buildUser ()}/>, {
|
||||
route: '/ja/submissions' })
|
||||
fireEvent.change (screen.getByLabelText ('対象 ID'), { target: { value: '42' } })
|
||||
fireEvent.change (screen.getByRole ('combobox'), { target: { value: 'opinion' } })
|
||||
expect (screen.queryByLabelText ('対象 ID')).not.toBeInTheDocument ()
|
||||
const content = '空白 を含む,御意見\n二行目'
|
||||
fireEvent.change (screen.getByLabelText ('内容'), { target: { value: content } })
|
||||
fireEvent.click (screen.getByRole ('button', { name: '送信' }))
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiPost).toHaveBeenCalledWith ('/submissions', {
|
||||
category: 'opinion', target_id: null, content }, { locale: 'ja' })
|
||||
})
|
||||
})
|
||||
|
||||
it ('retains inputs and shows server validation errors', async () => {
|
||||
api.isApiError.mockReturnValue (true)
|
||||
api.apiPost.mockRejectedValue ({ response: { status: 422, data: {
|
||||
type: 'validation_error', errors: { target_id: ['対象が不正です.'] },
|
||||
base_errors: [] } } })
|
||||
renderWithProviders (<SubmissionsPage user={buildUser ()}/>, {
|
||||
route: '/ja/submissions' })
|
||||
fireEvent.change (screen.getByLabelText ('対象 ID'), { target: { value: '42' } })
|
||||
fireEvent.change (screen.getByLabelText ('内容'), { target: { value: '理由' } })
|
||||
fireEvent.click (screen.getByRole ('button', { name: '送信' }))
|
||||
|
||||
expect (await screen.findByText ('対象が不正です.')).toBeInTheDocument ()
|
||||
expect (screen.getByLabelText ('対象 ID')).toHaveAttribute ('aria-invalid', 'true')
|
||||
expect (screen.getByLabelText ('内容')).toHaveValue ('理由')
|
||||
})
|
||||
|
||||
it ('uses the existing pagination and Japanese fallback language metadata', async () => {
|
||||
api.apiGet.mockResolvedValue ({ submissions: [], count: 41, pageSize: 20 })
|
||||
renderWithProviders (<SubmissionsPage user={null}/>, {
|
||||
route: '/ain-Kana/submissions?page=2' })
|
||||
|
||||
await waitFor (() => {
|
||||
expect (api.apiGet).toHaveBeenCalledWith ('/submissions', {
|
||||
locale: 'ain-Kana', params: { page: 2 } })
|
||||
})
|
||||
expect (await screen.findByRole ('navigation')).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('option', { name: '御意見板' })).toHaveAttribute ('lang', 'ja')
|
||||
expect (screen.getByRole ('heading', { name: '申請・御意見板' })).toBeInTheDocument ()
|
||||
expect (screen.getByRole ('link', { name: '3' }))
|
||||
.toHaveAttribute ('href', '/ain-Kana/submissions?page=3')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,153 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
|
||||
import FieldError from '@/components/common/FieldError'
|
||||
import Form from '@/components/common/Form'
|
||||
import FormField from '@/components/common/FormField'
|
||||
import PageHead from '@/components/common/PageHead'
|
||||
import PageTitle from '@/components/common/PageTitle'
|
||||
import Pagination from '@/components/common/Pagination'
|
||||
import TextArea from '@/components/common/TextArea'
|
||||
import MainArea from '@/components/layout/MainArea'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/use-toast'
|
||||
import { submissionsKeys } from '@/lib/queryKeys'
|
||||
import { createSubmission, fetchSubmissions } from '@/lib/submissions'
|
||||
import { useLocale, useLocaleNavigate } from '@/lib/useLocale'
|
||||
import { useUITranslation } from '@/lib/useUITranslation'
|
||||
import { useValidationErrors } from '@/lib/useValidationErrors'
|
||||
import { inputClass, localisedDateString } from '@/lib/utils'
|
||||
|
||||
import type { FC, FormEvent } from 'react'
|
||||
|
||||
import type { SubmissionCategory, User } from '@/types'
|
||||
|
||||
const CATEGORIES: SubmissionCategory[] = [
|
||||
'post_removal', 'tag_removal', 'material_removal', 'opinion']
|
||||
|
||||
const SubmissionsPage: FC<{ user: User | null }> = ({ user }) => {
|
||||
const locale = useLocale ()
|
||||
const navigate = useLocaleNavigate ()
|
||||
const { message, label } = useUITranslation ('submissions')
|
||||
const client = useQueryClient ()
|
||||
const [query] = useSearchParams ()
|
||||
const pageValue = query.get ('page') ?? ''
|
||||
const page =
|
||||
pageValue.match (/^[1-9][0-9]{0,5}$/)?.[0] === pageValue
|
||||
? Number (pageValue)
|
||||
: 1
|
||||
const [category, setCategory] = useState<SubmissionCategory> ('post_removal')
|
||||
const [targetId, setTargetId] = useState ('')
|
||||
const [content, setContent] = useState ('')
|
||||
const { baseErrors, fieldErrors, clearValidationErrors, applyValidationError } =
|
||||
useValidationErrors<'category' | 'targetId' | 'content'> ()
|
||||
const { data, isLoading: loading, isError: errorFlg } = useQuery ({
|
||||
queryKey: submissionsKeys.index (page, locale),
|
||||
queryFn: () => fetchSubmissions (page, locale) })
|
||||
const { mutate, isPending: pending } = useMutation ({
|
||||
mutationFn: () => createSubmission ({ category, targetId, content }, locale),
|
||||
onSuccess: async () => {
|
||||
setTargetId ('')
|
||||
setContent ('')
|
||||
await client.invalidateQueries ({ queryKey: submissionsKeys.root })
|
||||
navigate ('/submissions')
|
||||
toast ({ title: label ('shared:messages.postSuccess') })
|
||||
},
|
||||
onError: error => {
|
||||
applyValidationError (error)
|
||||
toast ({ title: label ('shared:messages.postFailed') })
|
||||
} })
|
||||
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault ()
|
||||
if (pending || user == null) return
|
||||
clearValidationErrors ()
|
||||
mutate ()
|
||||
}
|
||||
|
||||
return (
|
||||
<MainArea>
|
||||
<PageHead title={message ('title')}/>
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
<PageTitle>{label ('title')}</PageTitle>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<fieldset disabled={pending || user == null}>
|
||||
<Form>
|
||||
<FieldError messages={baseErrors}/>
|
||||
<FormField label={label ('category')} messages={fieldErrors.category}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<select
|
||||
value={category}
|
||||
onChange={event => {
|
||||
setCategory (event.target.value as SubmissionCategory)
|
||||
setTargetId ('')
|
||||
clearValidationErrors ()
|
||||
}}
|
||||
aria-label={message ('category').text}
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={invalid}
|
||||
className={inputClass (invalid)}>
|
||||
{CATEGORIES.map (value => (
|
||||
<option key={value} value={value}
|
||||
lang={message (`categories.${value}`).language}>
|
||||
{message (`categories.${value}`).text}
|
||||
</option>))}
|
||||
</select>)}
|
||||
</FormField>
|
||||
{category !== 'opinion' && (
|
||||
<FormField label={label ('targetId')} messages={fieldErrors.targetId}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<input
|
||||
value={targetId}
|
||||
onChange={event => setTargetId (event.target.value)}
|
||||
inputMode="numeric"
|
||||
pattern="[1-9][0-9]*"
|
||||
required
|
||||
aria-label={message ('targetId').text}
|
||||
aria-describedby={describedBy}
|
||||
aria-invalid={invalid}
|
||||
className={inputClass (invalid)}/>)}
|
||||
</FormField>)}
|
||||
<FormField label={label ('shared:labels.content')} messages={fieldErrors.content}>
|
||||
{({ describedBy, invalid }) => (
|
||||
<TextArea
|
||||
value={content}
|
||||
onChange={event => setContent (event.target.value)}
|
||||
required
|
||||
maxLength={5000}
|
||||
aria-label={message ('shared:labels.content').text}
|
||||
aria-describedby={describedBy}
|
||||
invalid={invalid}/>)}
|
||||
</FormField>
|
||||
<Button type="submit">{label ('submit')}</Button>
|
||||
</Form>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
{loading && <p>{label ('shared:messages.loading')}</p>}
|
||||
{errorFlg && <FieldError messages={[label ('error')]}/>}
|
||||
<div className="space-y-4">
|
||||
{data?.submissions.map (submission => (
|
||||
<article key={submission.id} className="border-b pb-4">
|
||||
<h2 className="font-semibold">
|
||||
{label (`categories.${submission.category}`)}
|
||||
</h2>
|
||||
{submission.targetId != null && (
|
||||
<p>{label ('targetId')}: {submission.targetId}</p>)}
|
||||
<p className="whitespace-pre-wrap break-words">{submission.content}</p>
|
||||
<div className="text-sm">
|
||||
{submission.user.name || label ('shared:labels.anonymous')}
|
||||
{' / '}
|
||||
<time dateTime={submission.createdAt} lang={locale}>
|
||||
{localisedDateString (submission.createdAt, locale)}
|
||||
</time>
|
||||
</div>
|
||||
</article>))}
|
||||
</div>
|
||||
{data != null && data.count > data.pageSize && (
|
||||
<Pagination page={page} totalPages={Math.ceil (data.count / data.pageSize)}/>)}
|
||||
</div>
|
||||
</MainArea>)
|
||||
}
|
||||
export default SubmissionsPage
|
||||
@@ -10,6 +10,19 @@ import type { LocaleCode } from '@/lib/locales'
|
||||
|
||||
export type Category = typeof CATEGORIES[number]
|
||||
|
||||
export type SubmissionCategory =
|
||||
| 'post_removal'
|
||||
| 'tag_removal'
|
||||
| 'material_removal'
|
||||
| 'opinion'
|
||||
|
||||
export type Submission = { id: number
|
||||
category: SubmissionCategory
|
||||
targetId: number | null
|
||||
content: string
|
||||
user: Pick<User, 'id' | 'name'>
|
||||
createdAt: string }
|
||||
|
||||
export type Deerjikist = { platform: Platform; code: string }
|
||||
|
||||
export type FetchPostsOrder = `${ FetchPostsOrderField }:${ 'asc' | 'desc' }`
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする