From efcc363537bf355742f40bb7bd3fee004568b3ff Mon Sep 17 00:00:00 2001 From: Codex Night Worker Date: Thu, 19 Nov 2026 12:29:23 +0900 Subject: [PATCH] WIP: preserve failed Codex job issue-205-idew24v8 --- .../app/controllers/submissions_controller.rb | 33 +++ backend/app/models/submission.rb | 49 +++++ backend/config/routes.rb | 1 + .../20261118000000_create_submissions.rb | 13 ++ backend/db/schema.rb | 16 +- backend/spec/requests/submissions_spec.rb | 190 ++++++++++++++++++ frontend/src/App.tsx | 3 + frontend/src/components/TopNav.tsx | 2 + frontend/src/lib/queryKeys.ts | 5 + frontend/src/lib/submissions.ts | 24 +++ frontend/src/locales/ain-Kana/navigation.json | 4 +- .../src/locales/ain-Kana/submissions.json | 14 ++ frontend/src/locales/ja/navigation.json | 1 + frontend/src/locales/ja/submissions.json | 13 ++ frontend/src/pages/SubmissionsPage.test.tsx | 107 ++++++++++ frontend/src/pages/SubmissionsPage.tsx | 153 ++++++++++++++ frontend/src/types.ts | 13 ++ 17 files changed, 639 insertions(+), 2 deletions(-) create mode 100644 backend/app/controllers/submissions_controller.rb create mode 100644 backend/app/models/submission.rb create mode 100644 backend/db/migrate/20261118000000_create_submissions.rb create mode 100644 backend/spec/requests/submissions_spec.rb create mode 100644 frontend/src/lib/submissions.ts create mode 100644 frontend/src/locales/ain-Kana/submissions.json create mode 100644 frontend/src/locales/ja/submissions.json create mode 100644 frontend/src/pages/SubmissionsPage.test.tsx create mode 100644 frontend/src/pages/SubmissionsPage.tsx diff --git a/backend/app/controllers/submissions_controller.rb b/backend/app/controllers/submissions_controller.rb new file mode 100644 index 0000000..e5e9434 --- /dev/null +++ b/backend/app/controllers/submissions_controller.rb @@ -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 diff --git a/backend/app/models/submission.rb b/backend/app/models/submission.rb new file mode 100644 index 0000000..93cc5aa --- /dev/null +++ b/backend/app/models/submission.rb @@ -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 diff --git a/backend/config/routes.rb b/backend/config/routes.rb index 62f7f3f..0714852 100644 --- a/backend/config/routes.rb +++ b/backend/config/routes.rb @@ -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] diff --git a/backend/db/migrate/20261118000000_create_submissions.rb b/backend/db/migrate/20261118000000_create_submissions.rb new file mode 100644 index 0000000..5f819a3 --- /dev/null +++ b/backend/db/migrate/20261118000000_create_submissions.rb @@ -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 diff --git a/backend/db/schema.rb b/backend/db/schema.rb index 723fe34..e2f56b6 100644 --- a/backend/db/schema.rb +++ b/backend/db/schema.rb @@ -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"] diff --git a/backend/spec/requests/submissions_spec.rb b/backend/spec/requests/submissions_spec.rb new file mode 100644 index 0000000..1557a4c --- /dev/null +++ b/backend/spec/requests/submissions_spec.rb @@ -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 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a6799ad..f9c5734 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -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: , handle: { preload: MorePage.preload, sitemap: ['static'] } }, + { path: 'submissions', element: , + handle: { preload: SubmissionsPage.preload, robots: 'noindex' } }, { path: '*', element: , handle: { notFound: true } }] diff --git a/frontend/src/components/TopNav.tsx b/frontend/src/components/TopNav.tsx index 22dc2dd..79244b4 100644 --- a/frontend/src/components/TopNav.tsx +++ b/frontend/src/components/TopNav.tsx @@ -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' }] }] } diff --git a/frontend/src/lib/queryKeys.ts b/frontend/src/lib/queryKeys.ts index 7e1d09c..e47af0e 100644 --- a/frontend/src/lib/queryKeys.ts +++ b/frontend/src/lib/queryKeys.ts @@ -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: ( diff --git a/frontend/src/lib/submissions.ts b/frontend/src/lib/submissions.ts new file mode 100644 index 0000000..4e87520 --- /dev/null +++ b/frontend/src/lib/submissions.ts @@ -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 => + apiGet ('/submissions', { locale, params: { page } }) + +export const createSubmission = ( + attributes: { category: SubmissionCategory + targetId: string + content: string }, + locale: LocaleCode, +): Promise => + apiPost ('/submissions', { category: attributes.category, + target_id: attributes.category === 'opinion' ? null : attributes.targetId, + content: attributes.content }, { locale }) diff --git a/frontend/src/locales/ain-Kana/navigation.json b/frontend/src/locales/ain-Kana/navigation.json index 02e4509..5c8d645 100644 --- a/frontend/src/locales/ain-Kana/navigation.json +++ b/frontend/src/locales/ain-Kana/navigation.json @@ -26,5 +26,7 @@ "terms": "エイワンケ イレンカ", "more": "モㇱマ アン ペ »", "counts": "ウコピㇱキ", - "externalTags": "ソイタ シロシ" + "externalTags": "ソイタ シロシ", + "submissions": "$t(submissions:title)", + "_untranslated": ["submissions"] } diff --git a/frontend/src/locales/ain-Kana/submissions.json b/frontend/src/locales/ain-Kana/submissions.json new file mode 100644 index 0000000..c7965b0 --- /dev/null +++ b/frontend/src/locales/ain-Kana/submissions.json @@ -0,0 +1,14 @@ +{ + "_untranslated": ["*"], + "title": "申請・御意見板", + "category": "種別", + "targetId": "対象 ID", + "submit": "送信", + "error": "申請の取得に失敗しました.", + "categories": { + "post_removal": "投稿の除票申請", + "tag_removal": "タグの除票申請", + "material_removal": "素材の除票申請", + "opinion": "御意見板" + } +} diff --git a/frontend/src/locales/ja/navigation.json b/frontend/src/locales/ja/navigation.json index 5e00f5e..48b7b11 100644 --- a/frontend/src/locales/ja/navigation.json +++ b/frontend/src/locales/ja/navigation.json @@ -25,4 +25,5 @@ "settings": "設定", "legal": "法規", "terms": "利用規約", + "submissions": "$t(submissions:title)", "more": "その他 »" } diff --git a/frontend/src/locales/ja/submissions.json b/frontend/src/locales/ja/submissions.json new file mode 100644 index 0000000..9803026 --- /dev/null +++ b/frontend/src/locales/ja/submissions.json @@ -0,0 +1,13 @@ +{ + "title": "申請・御意見板", + "category": "種別", + "targetId": "対象 ID", + "submit": "送信", + "error": "申請の取得に失敗しました.", + "categories": { + "post_removal": "投稿の除票申請", + "tag_removal": "タグの除票申請", + "material_removal": "素材の除票申請", + "opinion": "御意見板" + } +} diff --git a/frontend/src/pages/SubmissionsPage.test.tsx b/frontend/src/pages/SubmissionsPage.test.tsx new file mode 100644 index 0000000..ceac94c --- /dev/null +++ b/frontend/src/pages/SubmissionsPage.test.tsx @@ -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: '', + 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 (, { + 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 (, { + 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 (, { + 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 (, { + 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 (, { + 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') + }) +}) diff --git a/frontend/src/pages/SubmissionsPage.tsx b/frontend/src/pages/SubmissionsPage.tsx new file mode 100644 index 0000000..cd1447f --- /dev/null +++ b/frontend/src/pages/SubmissionsPage.tsx @@ -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 ('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 ( + + +
+ {label ('title')} +
+
+ + + + {({ describedBy, invalid }) => ( + )} + + {category !== 'opinion' && ( + + {({ describedBy, invalid }) => ( + 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)}/>)} + )} + + {({ describedBy, invalid }) => ( +