Reviewed-on: #362 Co-authored-by: miteruzo <miteruzo@naver.com> Co-committed-by: miteruzo <miteruzo@naver.com>
このコミットはPull リクエスト #362 でマージされました.
このコミットが含まれているのは:
@@ -126,12 +126,16 @@ npm run preview
|
|||||||
- In TypeScript and TSX only, replace every leading run of 8 spaces with a tab.
|
- In TypeScript and TSX only, replace every leading run of 8 spaces with a tab.
|
||||||
- Tabs are only for leading indentation, never for spaces after non-space text.
|
- Tabs are only for leading indentation, never for spaces after non-space text.
|
||||||
- Do not add production dependencies without explicit approval.
|
- Do not add production dependencies without explicit approval.
|
||||||
|
- Do not create, modify, or run tests unless the user explicitly asks for
|
||||||
|
test work. When the user asks for tests, keep working and rerun them until
|
||||||
|
they pass or the remaining failure is clearly blocked.
|
||||||
|
|
||||||
## Backend rules
|
## Backend rules
|
||||||
|
|
||||||
- Inspect existing routes, controllers, models, services, and specs before
|
- Inspect existing routes, controllers, models, services, and specs before
|
||||||
editing backend behavior.
|
editing backend behavior.
|
||||||
- For API behavior changes, add or update request specs under `backend/spec/requests`.
|
- For API behavior changes, add or update request specs under
|
||||||
|
`backend/spec/requests` only when the user explicitly asks for tests.
|
||||||
- Prefer RSpec for new backend tests; existing minitest files under
|
- Prefer RSpec for new backend tests; existing minitest files under
|
||||||
`backend/test` do not make minitest the default for new coverage.
|
`backend/test` do not make minitest the default for new coverage.
|
||||||
- Do not weaken authentication, BAN user checks, or IP BAN checks.
|
- Do not weaken authentication, BAN user checks, or IP BAN checks.
|
||||||
@@ -211,10 +215,11 @@ function PostFormTagsArea ({ tags, setTags }: Props) {
|
|||||||
`node_modules`, `dist`, `tmp`, `log`, and `storage` unless explicitly needed.
|
`node_modules`, `dist`, `tmp`, `log`, and `storage` unless explicitly needed.
|
||||||
- Before touching wiki, tag, versioning, BAN, IP BAN, or authentication
|
- Before touching wiki, tag, versioning, BAN, IP BAN, or authentication
|
||||||
behavior, inspect the related request specs and service objects.
|
behavior, inspect the related request specs and service objects.
|
||||||
- If frontend code changes, run the existing frontend verification commands
|
- If frontend code changes, run only non-test verification commands that
|
||||||
that apply: `npm run build`, `npm run lint`, and `npm run test:run`.
|
apply, such as `npm run build` and `npm run lint`. Run `npm run test:run`
|
||||||
- If backend code changes, run the relevant RSpec command; for broad backend
|
only when the user explicitly asks for tests.
|
||||||
changes, run `bundle exec rspec`.
|
- If backend code changes, do not run RSpec unless the user explicitly asks
|
||||||
|
for tests.
|
||||||
- If a verification command cannot be run or fails, report the exact command and failure.
|
- If a verification command cannot be run or fails, report the exact command and failure.
|
||||||
|
|
||||||
## Completion criteria
|
## Completion criteria
|
||||||
@@ -222,7 +227,8 @@ function PostFormTagsArea ({ tags, setTags }: Props) {
|
|||||||
A task is complete only when:
|
A task is complete only when:
|
||||||
|
|
||||||
- implementation is complete,
|
- implementation is complete,
|
||||||
- relevant verification commands pass, or failures are clearly explained,
|
- relevant non-test verification commands pass, or failures are clearly
|
||||||
|
explained,
|
||||||
- unrelated files are not changed,
|
- unrelated files are not changed,
|
||||||
- migrations and schema are consistent when schema changes are made,
|
- migrations and schema are consistent when schema changes are made,
|
||||||
- user-facing behavior is documented when needed.
|
- user-facing behavior is documented when needed.
|
||||||
|
|||||||
+11
-4
@@ -47,6 +47,10 @@ bundle exec rspec
|
|||||||
|
|
||||||
If a command cannot be run or fails, report the exact command and failure.
|
If a command cannot be run or fails, report the exact command and failure.
|
||||||
|
|
||||||
|
Do not create, modify, or run tests unless the user explicitly asks for test
|
||||||
|
work. When the user asks for tests, keep working and rerun them until they
|
||||||
|
pass or the remaining failure is clearly blocked.
|
||||||
|
|
||||||
## Rails structure
|
## Rails structure
|
||||||
|
|
||||||
- `app/controllers`: API controllers.
|
- `app/controllers`: API controllers.
|
||||||
@@ -116,7 +120,8 @@ service, representation, and spec.
|
|||||||
- `User#banned?` and `IpAddress#banned?` check `banned_at.present?`.
|
- `User#banned?` and `IpAddress#banned?` check `banned_at.present?`.
|
||||||
- Do not weaken BAN or IP BAN behavior.
|
- Do not weaken BAN or IP BAN behavior.
|
||||||
- If changing request authentication or controller before actions, add or
|
- If changing request authentication or controller before actions, add or
|
||||||
update request specs covering banned users and banned IP addresses.
|
update request specs covering banned users and banned IP addresses only when
|
||||||
|
the user explicitly asks for tests.
|
||||||
|
|
||||||
## RSpec
|
## RSpec
|
||||||
|
|
||||||
@@ -130,8 +135,9 @@ service, representation, and spec.
|
|||||||
- `AuthHelper#sign_in_as(user)` stubs
|
- `AuthHelper#sign_in_as(user)` stubs
|
||||||
`ApplicationController#current_user`; use it when matching existing
|
`ApplicationController#current_user`; use it when matching existing
|
||||||
request spec style.
|
request spec style.
|
||||||
- Add or update request specs for API behavior changes, especially status
|
- Add or update request specs for API behavior changes only when the user
|
||||||
codes, permissions, response shape, and version conflict behavior.
|
explicitly asks for tests, especially status codes, permissions, response
|
||||||
|
shape, and version conflict behavior.
|
||||||
|
|
||||||
## Migrations
|
## Migrations
|
||||||
|
|
||||||
@@ -164,7 +170,8 @@ service, representation, and spec.
|
|||||||
the record `version_no`.
|
the record `version_no`.
|
||||||
- Do not update versioned records without considering whether a version snapshot must be created.
|
- Do not update versioned records without considering whether a version snapshot must be created.
|
||||||
- For optimistic concurrency paths, preserve `base_version_no`, `force`, and
|
- For optimistic concurrency paths, preserve `base_version_no`, `force`, and
|
||||||
`merge` semantics and cover conflicts in request specs.
|
`merge` semantics. Cover conflicts in request specs only when the user
|
||||||
|
explicitly asks for tests.
|
||||||
|
|
||||||
## Domain cautions
|
## Domain cautions
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
class GekanatorGamesController < ApplicationController
|
||||||
|
def create
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
guessed_post_id = params.require(:guessed_post_id)
|
||||||
|
correct_post_id = params[:correct_post_id].presence
|
||||||
|
answers = params.require(:answers).as_json
|
||||||
|
|
||||||
|
game = GekanatorGame.new(
|
||||||
|
user: current_user,
|
||||||
|
guessed_post_id:,
|
||||||
|
correct_post_id:,
|
||||||
|
won: correct_post_id.present? && guessed_post_id.to_i == correct_post_id.to_i,
|
||||||
|
question_count: answers.length,
|
||||||
|
answers:)
|
||||||
|
|
||||||
|
if game.save
|
||||||
|
render json: { id: game.id }, status: :created
|
||||||
|
else
|
||||||
|
render json: { errors: game.errors.full_messages }, status: :unprocessable_entity
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def extra_questions
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
game = GekanatorGame.find_by(id: params[:id])
|
||||||
|
return head :not_found unless game
|
||||||
|
|
||||||
|
asked_ids = Array(game.answers).filter_map { |answer| answer_question_id(answer) }
|
||||||
|
existing_example_ids =
|
||||||
|
GekanatorQuestionExample.where(post_id: game.correct_post_id)
|
||||||
|
.select(:gekanator_question_id)
|
||||||
|
# Direct examples only for now; post_similarity-based expansion is deferred.
|
||||||
|
questions =
|
||||||
|
GekanatorQuestion
|
||||||
|
.accepted
|
||||||
|
.where(kind: 'post_similarity', source: 'user_suggested')
|
||||||
|
.where.not(id: existing_example_ids)
|
||||||
|
.order(priority_weight: :desc, id: :asc)
|
||||||
|
|
||||||
|
render json: {
|
||||||
|
questions: questions.filter_map { |question|
|
||||||
|
json = extra_question_json(question)
|
||||||
|
next if asked_ids.include?(json[:id].to_s)
|
||||||
|
next if asked_ids.include?("post-similarity:#{ json[:id] }")
|
||||||
|
|
||||||
|
json
|
||||||
|
}.first(2)
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def extra_question_answers
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
game = GekanatorGame.find_by(id: params[:id])
|
||||||
|
return head :not_found unless game
|
||||||
|
|
||||||
|
answer_params = params.require(:answers)
|
||||||
|
if !answer_params.is_a?(Array)
|
||||||
|
return render_validation_error fields: { answers: ['配列で指定してください.'] }
|
||||||
|
end
|
||||||
|
|
||||||
|
answers = answer_params.map { |answer|
|
||||||
|
{
|
||||||
|
question_id: answer.require(:question_id).to_i,
|
||||||
|
answer: answer.require(:answer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
questions = GekanatorQuestion.where(id: answers.map { _1[:question_id] })
|
||||||
|
question_by_id = questions.index_by(&:id)
|
||||||
|
if questions.length != answers.length
|
||||||
|
return render_validation_error fields: { answers: ['質問が見つかりません.'] }
|
||||||
|
end
|
||||||
|
if questions.any? { |question| question.status != 'accepted' || question.kind != 'post_similarity' }
|
||||||
|
return render_validation_error fields: { answers: ['質問が不正です.'] }
|
||||||
|
end
|
||||||
|
|
||||||
|
ActiveRecord::Base.transaction do
|
||||||
|
answers.each do |item|
|
||||||
|
question = question_by_id[item[:question_id]]
|
||||||
|
example =
|
||||||
|
GekanatorQuestionExample.find_or_initialize_by(
|
||||||
|
gekanator_question: question,
|
||||||
|
post: game.correct_post,
|
||||||
|
user: current_user)
|
||||||
|
example.assign_attributes(
|
||||||
|
gekanator_game: game,
|
||||||
|
answer: item[:answer],
|
||||||
|
source: 'post_game_extra',
|
||||||
|
weight: 1.0)
|
||||||
|
example.save!
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: { count: answers.length }, status: :created
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def extra_question_json question
|
||||||
|
{
|
||||||
|
id: question.id,
|
||||||
|
text: question.text,
|
||||||
|
source: question.source,
|
||||||
|
priority_weight: question.priority_weight
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def answer_question_id answer
|
||||||
|
value = if answer.is_a?(Hash)
|
||||||
|
answer['question_id'].presence || answer[:question_id].presence ||
|
||||||
|
answer['questionId'].presence || answer[:questionId].presence
|
||||||
|
end
|
||||||
|
|
||||||
|
value&.to_s
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
class GekanatorPostsController < ApplicationController
|
||||||
|
def index
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
posts =
|
||||||
|
Post
|
||||||
|
.preload(tags: :tag_name)
|
||||||
|
.with_attached_thumbnail
|
||||||
|
.order(Arel.sql(
|
||||||
|
'COALESCE(posts.original_created_before - INTERVAL 1 MINUTE, ' \
|
||||||
|
'posts.original_created_from, posts.created_at) DESC, posts.id DESC'))
|
||||||
|
|
||||||
|
render json: { posts: posts.map { |post| post_json(post) } }
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def post_json post
|
||||||
|
{
|
||||||
|
id: post.id,
|
||||||
|
url: post.url,
|
||||||
|
title: post.title,
|
||||||
|
thumbnail: thumbnail_url(post),
|
||||||
|
thumbnail_base: post.thumbnail_base,
|
||||||
|
original_created_from: post.original_created_from,
|
||||||
|
original_created_before: post.original_created_before,
|
||||||
|
tags: post.tags.map { |tag| tag_json(tag) }
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def tag_json tag
|
||||||
|
{
|
||||||
|
id: tag.id,
|
||||||
|
name: tag.name,
|
||||||
|
category: tag.category
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
def thumbnail_url post
|
||||||
|
return nil unless post.thumbnail.attached?
|
||||||
|
|
||||||
|
rails_storage_proxy_url(post.thumbnail, only_path: false)
|
||||||
|
rescue
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
class GekanatorQuestionSuggestionsController < ApplicationController
|
||||||
|
def create
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
game = GekanatorGame.find_by(id: params.require(:gekanator_game_id))
|
||||||
|
return head :not_found unless game
|
||||||
|
|
||||||
|
suggestion = GekanatorQuestionSuggestion.new(
|
||||||
|
gekanator_game: game,
|
||||||
|
user: current_user,
|
||||||
|
question_text: params.require(:question_text),
|
||||||
|
answer: params.require(:answer))
|
||||||
|
|
||||||
|
if suggestion.valid?
|
||||||
|
ActiveRecord::Base.transaction do
|
||||||
|
suggestion.save!
|
||||||
|
Gekanator::QuestionSuggestionPromoter.call(
|
||||||
|
suggestion: suggestion,
|
||||||
|
user: current_user)
|
||||||
|
end
|
||||||
|
|
||||||
|
render json: {
|
||||||
|
id: suggestion.id,
|
||||||
|
count: game.question_suggestions.count
|
||||||
|
}, status: :created
|
||||||
|
else
|
||||||
|
render_validation_error suggestion
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def ai_convert
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
suggestion = GekanatorQuestionSuggestion.find_by(id: params[:id])
|
||||||
|
return head :not_found unless suggestion
|
||||||
|
if Gekanator::AiRunBudget.exceeded_after_next_run?
|
||||||
|
suggestion.gekanator_ai_runs.create!(
|
||||||
|
model: 'budget_guard',
|
||||||
|
status: 'blocked_budget',
|
||||||
|
input_tokens: 0,
|
||||||
|
output_tokens: 0,
|
||||||
|
estimated_cost_jpy: 0)
|
||||||
|
return head :payment_required
|
||||||
|
end
|
||||||
|
|
||||||
|
Gekanator::QuestionSuggestionAiConverter.call(
|
||||||
|
suggestion: suggestion,
|
||||||
|
user: current_user)
|
||||||
|
head :no_content
|
||||||
|
rescue NotImplementedError
|
||||||
|
head :not_implemented
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
class GekanatorQuestionsController < ApplicationController
|
||||||
|
def index
|
||||||
|
return head :not_found unless current_user&.admin?
|
||||||
|
|
||||||
|
questions =
|
||||||
|
GekanatorQuestion
|
||||||
|
.accepted
|
||||||
|
.includes(:gekanator_question_examples)
|
||||||
|
.order(priority_weight: :desc, id: :asc)
|
||||||
|
|
||||||
|
render json: {
|
||||||
|
questions: questions.map { |question| question_json(question) }
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def question_json question
|
||||||
|
json = {
|
||||||
|
id: question_id_for(question),
|
||||||
|
text: question.text,
|
||||||
|
kind: question.kind,
|
||||||
|
condition: condition_json(question.condition),
|
||||||
|
source: question.source,
|
||||||
|
priority_weight: question.priority_weight
|
||||||
|
}
|
||||||
|
if question.kind == 'post_similarity'
|
||||||
|
json[:example_answers] = example_answers_json(question)
|
||||||
|
end
|
||||||
|
json
|
||||||
|
end
|
||||||
|
|
||||||
|
def question_id_for question
|
||||||
|
condition = condition_json(question.condition).deep_symbolize_keys
|
||||||
|
|
||||||
|
case condition[:type]
|
||||||
|
when 'tag'
|
||||||
|
"tag:#{ condition[:key] }"
|
||||||
|
when 'source'
|
||||||
|
"source:#{ condition[:host] }"
|
||||||
|
when 'original-year'
|
||||||
|
"original-year:#{ condition[:year] }"
|
||||||
|
when 'original-month'
|
||||||
|
"original-month:#{ condition[:month] }"
|
||||||
|
when 'original-month-day'
|
||||||
|
"original-month-day:#{ condition[:monthDay] || condition[:month_day] }"
|
||||||
|
when 'title-length-greater-than'
|
||||||
|
"title:length-greater-than:#{ condition[:length] }"
|
||||||
|
when 'title-has-ascii'
|
||||||
|
'title:ascii'
|
||||||
|
when 'post-similarity'
|
||||||
|
"post-similarity:#{ question.id }"
|
||||||
|
else
|
||||||
|
"catalog:#{ question.id }"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def condition_json condition
|
||||||
|
json = condition.deep_dup.as_json
|
||||||
|
|
||||||
|
if json['type'] == 'original-month-day' && json['monthDay'].blank?
|
||||||
|
json['monthDay'] = json.delete('month_day')
|
||||||
|
end
|
||||||
|
|
||||||
|
json
|
||||||
|
end
|
||||||
|
|
||||||
|
def example_answers_json question
|
||||||
|
question
|
||||||
|
.gekanator_question_examples
|
||||||
|
.group_by(&:post_id)
|
||||||
|
.transform_values { |examples| aggregate_answer(examples) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def aggregate_answer examples
|
||||||
|
examples
|
||||||
|
.group_by(&:answer)
|
||||||
|
.map { |answer, grouped| [answer, grouped.sum(&:weight), grouped.max_by(&:updated_at)&.updated_at] }
|
||||||
|
.sort_by { |(_answer, weight, updated_at)| [-weight, -(updated_at&.to_f || 0)] }
|
||||||
|
.first
|
||||||
|
&.first
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
class GekanatorAiRun < ApplicationRecord
|
||||||
|
STATUSES = ['pending', 'running', 'succeeded', 'failed', 'blocked_budget'].freeze
|
||||||
|
|
||||||
|
belongs_to :gekanator_question_suggestion
|
||||||
|
|
||||||
|
validates :model, presence: true, length: { maximum: 255 }
|
||||||
|
validates :status, presence: true, inclusion: { in: STATUSES }
|
||||||
|
validates :input_tokens,
|
||||||
|
presence: true,
|
||||||
|
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
||||||
|
validates :output_tokens,
|
||||||
|
presence: true,
|
||||||
|
numericality: { only_integer: true, greater_than_or_equal_to: 0 }
|
||||||
|
validates :estimated_cost_jpy,
|
||||||
|
presence: true,
|
||||||
|
numericality: { greater_than_or_equal_to: 0 }
|
||||||
|
|
||||||
|
scope :this_month, lambda {
|
||||||
|
where(created_at: Time.current.beginning_of_month..Time.current.end_of_month)
|
||||||
|
}
|
||||||
|
end
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
class GekanatorGame < ApplicationRecord
|
||||||
|
belongs_to :user
|
||||||
|
belongs_to :guessed_post, class_name: 'Post'
|
||||||
|
belongs_to :correct_post, class_name: 'Post'
|
||||||
|
has_many :question_suggestions,
|
||||||
|
class_name: 'GekanatorQuestionSuggestion',
|
||||||
|
dependent: :delete_all
|
||||||
|
has_many :question_examples,
|
||||||
|
class_name: 'GekanatorQuestionExample',
|
||||||
|
dependent: :delete_all
|
||||||
|
|
||||||
|
validates :answers, presence: true
|
||||||
|
validates :question_count, numericality: { greater_than_or_equal_to: 0 }
|
||||||
|
validates :won, inclusion: { in: [true, false] }
|
||||||
|
end
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
class GekanatorQuestion < ApplicationRecord
|
||||||
|
KINDS = ['tag', 'source', 'title', 'original_date', 'post_similarity'].freeze
|
||||||
|
SOURCES = ['user_suggested', 'ai_generated', 'admin_curated'].freeze
|
||||||
|
STATUSES = ['pending', 'accepted', 'rejected', 'disabled'].freeze
|
||||||
|
|
||||||
|
belongs_to :gekanator_question_suggestion, optional: true
|
||||||
|
belongs_to :created_by, class_name: 'User', optional: true
|
||||||
|
has_many :gekanator_question_examples, dependent: :delete_all
|
||||||
|
|
||||||
|
validates :kind, presence: true, inclusion: { in: KINDS }
|
||||||
|
validates :source, presence: true, inclusion: { in: SOURCES }
|
||||||
|
validates :status, presence: true, inclusion: { in: STATUSES }
|
||||||
|
validates :text, presence: true, length: { maximum: 1000 }
|
||||||
|
validates :condition, presence: true
|
||||||
|
validates :priority_weight,
|
||||||
|
presence: true,
|
||||||
|
numericality: {
|
||||||
|
greater_than: 0,
|
||||||
|
less_than_or_equal_to: 3
|
||||||
|
}
|
||||||
|
|
||||||
|
scope :accepted, -> { where(status: 'accepted') }
|
||||||
|
end
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
class GekanatorQuestionExample < ApplicationRecord
|
||||||
|
ANSWERS = GekanatorQuestionSuggestion::ANSWERS
|
||||||
|
SOURCES = ['initial_suggestion', 'post_game_extra'].freeze
|
||||||
|
|
||||||
|
belongs_to :gekanator_question
|
||||||
|
belongs_to :post
|
||||||
|
belongs_to :user
|
||||||
|
belongs_to :gekanator_game, optional: true
|
||||||
|
|
||||||
|
validates :answer, presence: true, inclusion: { in: ANSWERS }
|
||||||
|
validates :source, presence: true, inclusion: { in: SOURCES }
|
||||||
|
validates :weight,
|
||||||
|
presence: true,
|
||||||
|
numericality: {
|
||||||
|
greater_than: 0
|
||||||
|
}
|
||||||
|
end
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
class GekanatorQuestionSuggestion < ApplicationRecord
|
||||||
|
MAX_QUESTIONS_PER_GAME = 3
|
||||||
|
ANSWERS = ['yes', 'no', 'partial', 'probably_no', 'unknown'].freeze
|
||||||
|
|
||||||
|
belongs_to :gekanator_game
|
||||||
|
belongs_to :user
|
||||||
|
has_many :gekanator_questions, dependent: :nullify
|
||||||
|
has_many :gekanator_ai_runs, dependent: :destroy
|
||||||
|
|
||||||
|
validates :question_text, presence: true, length: { maximum: 1000 }
|
||||||
|
validates :answer, presence: true, inclusion: { in: ANSWERS }
|
||||||
|
validates :processed, inclusion: { in: [true, false] }
|
||||||
|
validate :question_suggestion_limit_per_game, on: :create
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def question_suggestion_limit_per_game
|
||||||
|
return if gekanator_game_id.blank?
|
||||||
|
|
||||||
|
count = GekanatorQuestionSuggestion.where(gekanator_game_id:).count
|
||||||
|
if count >= MAX_QUESTIONS_PER_GAME
|
||||||
|
errors.add(:base, '質問追加数を超えてゐます.')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -11,6 +11,17 @@ class Post < ApplicationRecord
|
|||||||
has_many :user_post_views, dependent: :delete_all
|
has_many :user_post_views, dependent: :delete_all
|
||||||
has_many :post_similarities, dependent: :delete_all
|
has_many :post_similarities, dependent: :delete_all
|
||||||
has_many :post_versions
|
has_many :post_versions
|
||||||
|
has_many :gekanator_guessed_games,
|
||||||
|
class_name: 'GekanatorGame',
|
||||||
|
foreign_key: :guessed_post_id,
|
||||||
|
dependent: :delete_all,
|
||||||
|
inverse_of: :guessed_post
|
||||||
|
has_many :gekanator_correct_games,
|
||||||
|
class_name: 'GekanatorGame',
|
||||||
|
foreign_key: :correct_post_id,
|
||||||
|
dependent: :delete_all,
|
||||||
|
inverse_of: :correct_post
|
||||||
|
has_many :gekanator_question_examples, dependent: :delete_all
|
||||||
|
|
||||||
has_many :parent_post_implications,
|
has_many :parent_post_implications,
|
||||||
class_name: 'PostImplication',
|
class_name: 'PostImplication',
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
module Gekanator
|
||||||
|
class AiRunBudget
|
||||||
|
MONTHLY_LIMIT_JPY = BigDecimal('450').freeze
|
||||||
|
MAX_RUN_ESTIMATED_COST_JPY = BigDecimal('5').freeze
|
||||||
|
|
||||||
|
def self.remaining_monthly_budget_jpy
|
||||||
|
MONTHLY_LIMIT_JPY - monthly_cost_jpy
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.monthly_cost_jpy
|
||||||
|
GekanatorAiRun.this_month.sum(:estimated_cost_jpy)
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.exceeded?
|
||||||
|
monthly_cost_jpy >= MONTHLY_LIMIT_JPY
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.exceeded_after_next_run?
|
||||||
|
monthly_cost_jpy + MAX_RUN_ESTIMATED_COST_JPY >= MONTHLY_LIMIT_JPY
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
module Gekanator
|
||||||
|
class QuestionSuggestionAiConverter
|
||||||
|
def self.call(...) = new(...).call
|
||||||
|
|
||||||
|
def initialize suggestion:, user:
|
||||||
|
@suggestion = suggestion
|
||||||
|
@user = user
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
raise NotImplementedError, 'AI question conversion is not implemented yet.'
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
attr_reader :suggestion, :user
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
module Gekanator
|
||||||
|
class QuestionSuggestionPromoter
|
||||||
|
def self.call(...) = new(...).call
|
||||||
|
|
||||||
|
def initialize suggestion:, user:
|
||||||
|
@suggestion = suggestion
|
||||||
|
@user = user
|
||||||
|
end
|
||||||
|
|
||||||
|
def call
|
||||||
|
suggestion.with_lock do
|
||||||
|
return promoted_question if suggestion.processed?
|
||||||
|
return suggestion if suggestion.answer == 'unknown'
|
||||||
|
|
||||||
|
question = GekanatorQuestion.create!(
|
||||||
|
text: suggestion.question_text,
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: 'user_suggested',
|
||||||
|
status: 'accepted',
|
||||||
|
priority_weight: 1.2,
|
||||||
|
condition: {
|
||||||
|
type: 'post-similarity',
|
||||||
|
postId: suggestion.gekanator_game.correct_post_id,
|
||||||
|
answer: suggestion.answer,
|
||||||
|
threshold: 0.65
|
||||||
|
},
|
||||||
|
gekanator_question_suggestion: suggestion,
|
||||||
|
created_by: user)
|
||||||
|
GekanatorQuestionExample.create!(
|
||||||
|
gekanator_question: question,
|
||||||
|
post: suggestion.gekanator_game.correct_post,
|
||||||
|
user: user,
|
||||||
|
gekanator_game: suggestion.gekanator_game,
|
||||||
|
answer: suggestion.answer,
|
||||||
|
source: 'initial_suggestion')
|
||||||
|
suggestion.update!(processed: true)
|
||||||
|
question
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
attr_reader :suggestion, :user
|
||||||
|
|
||||||
|
def promoted_question
|
||||||
|
suggestion.gekanator_questions.order(id: :desc).first
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -63,6 +63,24 @@ Rails.application.routes.draw do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
namespace :gekanator do
|
||||||
|
resources :games, only: [:create], controller: '/gekanator_games' do
|
||||||
|
member do
|
||||||
|
get :extra_questions
|
||||||
|
post :extra_question_answers
|
||||||
|
end
|
||||||
|
end
|
||||||
|
resources :posts, only: [:index], controller: '/gekanator_posts'
|
||||||
|
resources :questions, only: [:index], controller: '/gekanator_questions'
|
||||||
|
resources :question_suggestions,
|
||||||
|
only: [:create],
|
||||||
|
controller: '/gekanator_question_suggestions' do
|
||||||
|
member do
|
||||||
|
post :ai_convert
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
resources :users, only: [:create, :update] do
|
resources :users, only: [:create, :update] do
|
||||||
collection do
|
collection do
|
||||||
post :verify
|
post :verify
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
class CreateGekanatorGames < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :gekanator_games do |t|
|
||||||
|
t.references :user, null: false, foreign_key: true
|
||||||
|
t.references :guessed_post, null: false, foreign_key: { to_table: :posts }
|
||||||
|
t.references :correct_post, null: false, foreign_key: { to_table: :posts }
|
||||||
|
t.boolean :won, null: false
|
||||||
|
t.integer :question_count, null: false
|
||||||
|
t.json :answers, null: false
|
||||||
|
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
|
||||||
|
add_check_constraint :gekanator_games,
|
||||||
|
'question_count >= 0',
|
||||||
|
name: 'chk_gekanator_games_question_count_nonnegative'
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
class CreateGekanatorQuestionSuggestions < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :gekanator_question_suggestions do |t|
|
||||||
|
t.references :gekanator_game,
|
||||||
|
null: false,
|
||||||
|
foreign_key: { on_delete: :cascade }
|
||||||
|
t.references :user, null: false, foreign_key: true
|
||||||
|
t.text :question_text, null: false
|
||||||
|
t.boolean :processed, null: false, default: false
|
||||||
|
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
class AddAnswerToGekanatorQuestionSuggestions < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
add_column :gekanator_question_suggestions, :answer, :string, null: false
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
class CreateGekanatorQuestions < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :gekanator_questions do |t|
|
||||||
|
t.string :text, null: false
|
||||||
|
t.string :kind, null: false
|
||||||
|
t.json :condition, null: false
|
||||||
|
t.string :source, null: false, default: 'ai_generated'
|
||||||
|
t.string :status, null: false, default: 'pending'
|
||||||
|
t.float :priority_weight, null: false, default: 1.0
|
||||||
|
t.references :gekanator_question_suggestion,
|
||||||
|
null: true,
|
||||||
|
foreign_key: true
|
||||||
|
t.references :created_by,
|
||||||
|
null: true,
|
||||||
|
foreign_key: { to_table: :users }
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
class CreateGekanatorAiRuns < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :gekanator_ai_runs do |t|
|
||||||
|
t.string :model, null: false
|
||||||
|
t.integer :input_tokens, null: false, default: 0
|
||||||
|
t.integer :output_tokens, null: false, default: 0
|
||||||
|
t.decimal :estimated_cost_jpy, precision: 8, scale: 3, null: false, default: 0
|
||||||
|
t.string :status, null: false, default: 'pending'
|
||||||
|
t.references :gekanator_question_suggestion, null: false, foreign_key: true
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
class CreateGekanatorQuestionExamples < ActiveRecord::Migration[8.0]
|
||||||
|
def change
|
||||||
|
create_table :gekanator_question_examples do |t|
|
||||||
|
t.references :gekanator_question, null: false, foreign_key: true
|
||||||
|
t.references :post, null: false, foreign_key: true
|
||||||
|
t.references :user, null: false, foreign_key: true
|
||||||
|
t.references :gekanator_game, null: true, foreign_key: true
|
||||||
|
t.string :answer, null: false
|
||||||
|
t.string :source, null: false, default: 'post_game_extra'
|
||||||
|
t.float :weight, null: false, default: 1.0
|
||||||
|
t.timestamps
|
||||||
|
end
|
||||||
|
|
||||||
|
add_index :gekanator_question_examples,
|
||||||
|
[:gekanator_question_id, :post_id, :user_id],
|
||||||
|
unique: true,
|
||||||
|
name: 'idx_gekanator_question_examples_on_question_post_user'
|
||||||
|
end
|
||||||
|
end
|
||||||
生成ファイル
+84
-1
@@ -10,7 +10,7 @@
|
|||||||
#
|
#
|
||||||
# It's strongly recommended that you check this file into your version control system.
|
# It's strongly recommended that you check this file into your version control system.
|
||||||
|
|
||||||
ActiveRecord::Schema[8.0].define(version: 2026_06_06_000000) do
|
ActiveRecord::Schema[8.0].define(version: 2026_06_10_000000) do
|
||||||
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "active_storage_attachments", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.string "name", null: false
|
t.string "name", null: false
|
||||||
t.string "record_type", null: false
|
t.string "record_type", null: false
|
||||||
@@ -48,6 +48,77 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_06_000000) do
|
|||||||
t.index ["tag_id"], name: "index_deerjikists_on_tag_id"
|
t.index ["tag_id"], name: "index_deerjikists_on_tag_id"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
create_table "gekanator_ai_runs", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.string "model", null: false
|
||||||
|
t.integer "input_tokens", default: 0, null: false
|
||||||
|
t.integer "output_tokens", default: 0, null: false
|
||||||
|
t.decimal "estimated_cost_jpy", precision: 8, scale: 3, default: "0.0", null: false
|
||||||
|
t.string "status", default: "pending", null: false
|
||||||
|
t.bigint "gekanator_question_suggestion_id", null: false
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["gekanator_question_suggestion_id"], name: "index_gekanator_ai_runs_on_gekanator_question_suggestion_id"
|
||||||
|
end
|
||||||
|
|
||||||
|
create_table "gekanator_games", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.bigint "user_id", null: false
|
||||||
|
t.bigint "guessed_post_id", null: false
|
||||||
|
t.bigint "correct_post_id", null: false
|
||||||
|
t.boolean "won", null: false
|
||||||
|
t.integer "question_count", null: false
|
||||||
|
t.json "answers", null: false
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["correct_post_id"], name: "index_gekanator_games_on_correct_post_id"
|
||||||
|
t.index ["guessed_post_id"], name: "index_gekanator_games_on_guessed_post_id"
|
||||||
|
t.index ["user_id"], name: "index_gekanator_games_on_user_id"
|
||||||
|
t.check_constraint "`question_count` >= 0", name: "chk_gekanator_games_question_count_nonnegative"
|
||||||
|
end
|
||||||
|
|
||||||
|
create_table "gekanator_question_examples", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.bigint "gekanator_question_id", null: false
|
||||||
|
t.bigint "post_id", null: false
|
||||||
|
t.bigint "user_id", null: false
|
||||||
|
t.bigint "gekanator_game_id"
|
||||||
|
t.string "answer", null: false
|
||||||
|
t.string "source", default: "post_game_extra", null: false
|
||||||
|
t.float "weight", default: 1.0, null: false
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["gekanator_game_id"], name: "index_gekanator_question_examples_on_gekanator_game_id"
|
||||||
|
t.index ["gekanator_question_id", "post_id", "user_id"], name: "idx_gekanator_question_examples_on_question_post_user", unique: true
|
||||||
|
t.index ["gekanator_question_id"], name: "index_gekanator_question_examples_on_gekanator_question_id"
|
||||||
|
t.index ["post_id"], name: "index_gekanator_question_examples_on_post_id"
|
||||||
|
t.index ["user_id"], name: "index_gekanator_question_examples_on_user_id"
|
||||||
|
end
|
||||||
|
|
||||||
|
create_table "gekanator_question_suggestions", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.bigint "gekanator_game_id", null: false
|
||||||
|
t.bigint "user_id", null: false
|
||||||
|
t.text "question_text", null: false
|
||||||
|
t.boolean "processed", default: false, null: false
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.string "answer", null: false
|
||||||
|
t.index ["gekanator_game_id"], name: "index_gekanator_question_suggestions_on_gekanator_game_id"
|
||||||
|
t.index ["user_id"], name: "index_gekanator_question_suggestions_on_user_id"
|
||||||
|
end
|
||||||
|
|
||||||
|
create_table "gekanator_questions", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
|
t.string "text", null: false
|
||||||
|
t.string "kind", null: false
|
||||||
|
t.json "condition", null: false
|
||||||
|
t.string "source", default: "ai_generated", null: false
|
||||||
|
t.string "status", default: "pending", null: false
|
||||||
|
t.float "priority_weight", default: 1.0, null: false
|
||||||
|
t.bigint "gekanator_question_suggestion_id"
|
||||||
|
t.bigint "created_by_id"
|
||||||
|
t.datetime "created_at", null: false
|
||||||
|
t.datetime "updated_at", null: false
|
||||||
|
t.index ["created_by_id"], name: "index_gekanator_questions_on_created_by_id"
|
||||||
|
t.index ["gekanator_question_suggestion_id"], name: "index_gekanator_questions_on_gekanator_question_suggestion_id"
|
||||||
|
end
|
||||||
|
|
||||||
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
create_table "ip_addresses", charset: "utf8mb4", collation: "utf8mb4_0900_ai_ci", force: :cascade do |t|
|
||||||
t.binary "ip_address", limit: 16, null: false
|
t.binary "ip_address", limit: 16, null: false
|
||||||
t.datetime "banned_at"
|
t.datetime "banned_at"
|
||||||
@@ -478,6 +549,18 @@ ActiveRecord::Schema[8.0].define(version: 2026_06_06_000000) do
|
|||||||
|
|
||||||
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
|
||||||
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
|
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
|
||||||
|
add_foreign_key "gekanator_ai_runs", "gekanator_question_suggestions"
|
||||||
|
add_foreign_key "gekanator_games", "posts", column: "correct_post_id"
|
||||||
|
add_foreign_key "gekanator_games", "posts", column: "guessed_post_id"
|
||||||
|
add_foreign_key "gekanator_games", "users"
|
||||||
|
add_foreign_key "gekanator_question_examples", "gekanator_games"
|
||||||
|
add_foreign_key "gekanator_question_examples", "gekanator_questions"
|
||||||
|
add_foreign_key "gekanator_question_examples", "posts"
|
||||||
|
add_foreign_key "gekanator_question_examples", "users"
|
||||||
|
add_foreign_key "gekanator_question_suggestions", "gekanator_games", on_delete: :cascade
|
||||||
|
add_foreign_key "gekanator_question_suggestions", "users"
|
||||||
|
add_foreign_key "gekanator_questions", "gekanator_question_suggestions"
|
||||||
|
add_foreign_key "gekanator_questions", "users", column: "created_by_id"
|
||||||
add_foreign_key "material_versions", "materials"
|
add_foreign_key "material_versions", "materials"
|
||||||
add_foreign_key "material_versions", "materials", column: "parent_id"
|
add_foreign_key "material_versions", "materials", column: "parent_id"
|
||||||
add_foreign_key "material_versions", "tags"
|
add_foreign_key "material_versions", "tags"
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe 'Gekanator games API', type: :request do
|
||||||
|
let!(:admin) { create_admin_user! }
|
||||||
|
let!(:user) { create_member_user! }
|
||||||
|
let!(:guessed_post) { Post.create!(title: 'guess', url: 'https://example.com/guess') }
|
||||||
|
let!(:correct_post) { Post.create!(title: 'correct', url: 'https://example.com/correct') }
|
||||||
|
|
||||||
|
describe 'POST /gekanator/games' do
|
||||||
|
it 'stores a won game' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
correct_post_id: guessed_post.id,
|
||||||
|
answers: [{ question_id: 'tag:1', answer: 'yes' }] }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
game = GekanatorGame.find(json['id'])
|
||||||
|
expect(game.user).to eq(admin)
|
||||||
|
expect(game.guessed_post).to eq(guessed_post)
|
||||||
|
expect(game.correct_post).to eq(guessed_post)
|
||||||
|
expect(game.won).to eq(true)
|
||||||
|
expect(game.question_count).to eq(1)
|
||||||
|
expect(game.answers).to eq([{ 'question_id' => 'tag:1', 'answer' => 'yes' }])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'stores a lost game with the correct post' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
correct_post_id: correct_post.id,
|
||||||
|
question_count: 4,
|
||||||
|
answers: [{ question_id: 'tag:1', answer: 'no' }] }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
game = GekanatorGame.find(json['id'])
|
||||||
|
expect(game.correct_post).to eq(correct_post)
|
||||||
|
expect(game.won).to eq(false)
|
||||||
|
expect(game.question_count).to eq(1)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'rejects a game without the correct post' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
question_count: 4,
|
||||||
|
answers: [{ question_id: 'tag:1', answer: 'no' }] }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns not found without an admin user' do
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
correct_post_id: guessed_post.id,
|
||||||
|
answers: [] }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns not found for a non-admin user' do
|
||||||
|
sign_in_as user
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
correct_post_id: guessed_post.id,
|
||||||
|
answers: [{ question_id: 'tag:1', answer: 'yes' }] }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,588 @@
|
|||||||
|
require 'rails_helper'
|
||||||
|
|
||||||
|
RSpec.describe 'Gekanator learning API', type: :request do
|
||||||
|
let(:admin) { create(:user, :admin) }
|
||||||
|
let(:member) { create(:user, :member) }
|
||||||
|
let(:other_user) { create(:user, :member) }
|
||||||
|
|
||||||
|
let!(:guessed_post) do
|
||||||
|
Post.create!(
|
||||||
|
title: 'guessed',
|
||||||
|
url: 'https://example.com/guessed'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:correct_post) do
|
||||||
|
Post.create!(
|
||||||
|
title: 'correct',
|
||||||
|
url: 'https://example.com/correct'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:other_post) do
|
||||||
|
Post.create!(
|
||||||
|
title: 'other',
|
||||||
|
url: 'https://example.com/other'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
let!(:game) do
|
||||||
|
GekanatorGame.create!(
|
||||||
|
user: admin,
|
||||||
|
guessed_post: guessed_post,
|
||||||
|
correct_post: correct_post,
|
||||||
|
won: false,
|
||||||
|
question_count: 1,
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
'question_id' => 'tag:character:喜多郁代',
|
||||||
|
'question_text' => '喜多ちゃんが関係してる?',
|
||||||
|
'answer' => 'yes',
|
||||||
|
'original_answer' => 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def create_post_similarity_question!(
|
||||||
|
text: '喜多ちゃんが泣いてる?',
|
||||||
|
post: correct_post,
|
||||||
|
answer: 'yes',
|
||||||
|
status: 'accepted',
|
||||||
|
source: 'user_suggested',
|
||||||
|
priority_weight: 1.2
|
||||||
|
)
|
||||||
|
GekanatorQuestion.create!(
|
||||||
|
text: text,
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: source,
|
||||||
|
status: status,
|
||||||
|
priority_weight: priority_weight,
|
||||||
|
condition: {
|
||||||
|
type: 'post-similarity',
|
||||||
|
postId: post.id,
|
||||||
|
answer: answer,
|
||||||
|
threshold: 0.65
|
||||||
|
},
|
||||||
|
created_by: admin
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /gekanator/games' do
|
||||||
|
it 'stores a game result for an admin user' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
correct_post_id: correct_post.id,
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: 'tag:character:喜多郁代',
|
||||||
|
question_text: '喜多ちゃんが関係してる?',
|
||||||
|
answer: 'yes',
|
||||||
|
original_answer: 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
created = GekanatorGame.find(json['id'])
|
||||||
|
expect(created.user).to eq(admin)
|
||||||
|
expect(created.guessed_post).to eq(guessed_post)
|
||||||
|
expect(created.correct_post).to eq(correct_post)
|
||||||
|
expect(created.won).to eq(false)
|
||||||
|
expect(created.question_count).to eq(1)
|
||||||
|
expect(created.answers).to eq([
|
||||||
|
{
|
||||||
|
'question_id' => 'tag:character:喜多郁代',
|
||||||
|
'question_text' => '喜多ちゃんが関係してる?',
|
||||||
|
'answer' => 'yes',
|
||||||
|
'original_answer' => 'yes'
|
||||||
|
}
|
||||||
|
])
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'stores a won game when guessed_post_id equals correct_post_id' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: correct_post.id,
|
||||||
|
correct_post_id: correct_post.id,
|
||||||
|
answers: []
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(GekanatorGame.find(json['id']).won).to eq(true)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'rejects a game without correct_post_id' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
answers: []
|
||||||
|
}
|
||||||
|
}.not_to change { GekanatorGame.count }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns not found for a non-admin user' do
|
||||||
|
sign_in_as member
|
||||||
|
|
||||||
|
post '/gekanator/games', params: {
|
||||||
|
guessed_post_id: guessed_post.id,
|
||||||
|
correct_post_id: correct_post.id,
|
||||||
|
answers: []
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /gekanator/question_suggestions' do
|
||||||
|
it 'creates a suggestion and promotes yes answer to an accepted post_similarity question' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/gekanator/question_suggestions', params: {
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
question_text: '喜多ちゃんが泣いてる?',
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
}.to change { GekanatorQuestionSuggestion.count }.by(1)
|
||||||
|
.and change { GekanatorQuestion.count }.by(1)
|
||||||
|
.and change { GekanatorQuestionExample.count }.by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
|
||||||
|
suggestion = GekanatorQuestionSuggestion.last
|
||||||
|
question = GekanatorQuestion.last
|
||||||
|
example = GekanatorQuestionExample.last
|
||||||
|
|
||||||
|
expect(json).to include(
|
||||||
|
'id' => suggestion.id,
|
||||||
|
'count' => 1
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(suggestion).to have_attributes(
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
user_id: admin.id,
|
||||||
|
question_text: '喜多ちゃんが泣いてる?',
|
||||||
|
answer: 'yes',
|
||||||
|
processed: true
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(question).to have_attributes(
|
||||||
|
text: '喜多ちゃんが泣いてる?',
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: 'user_suggested',
|
||||||
|
status: 'accepted',
|
||||||
|
priority_weight: 1.2,
|
||||||
|
gekanator_question_suggestion_id: suggestion.id,
|
||||||
|
created_by_id: admin.id
|
||||||
|
)
|
||||||
|
expect(question.condition).to include(
|
||||||
|
'type' => 'post-similarity',
|
||||||
|
'postId' => correct_post.id,
|
||||||
|
'answer' => 'yes',
|
||||||
|
'threshold' => 0.65
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(example).to have_attributes(
|
||||||
|
gekanator_question_id: question.id,
|
||||||
|
post_id: correct_post.id,
|
||||||
|
user_id: admin.id,
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
answer: 'yes',
|
||||||
|
source: 'initial_suggestion',
|
||||||
|
weight: 1.0
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'promotes no, partial, and probably_no answers' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
['no', 'partial', 'probably_no'].each do |answer|
|
||||||
|
expect {
|
||||||
|
post '/gekanator/question_suggestions', params: {
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
question_text: "answer #{answer} question?",
|
||||||
|
answer: answer
|
||||||
|
}
|
||||||
|
}.to change { GekanatorQuestion.count }.by(1)
|
||||||
|
.and change { GekanatorQuestionExample.count }.by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(GekanatorQuestion.last.condition['answer']).to eq(answer)
|
||||||
|
expect(GekanatorQuestionExample.last.answer).to eq(answer)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not promote unknown answers' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/gekanator/question_suggestions', params: {
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
question_text: 'よく分からない質問?',
|
||||||
|
answer: 'unknown'
|
||||||
|
}
|
||||||
|
}.to change { GekanatorQuestionSuggestion.count }.by(1)
|
||||||
|
.and change { GekanatorQuestion.count }.by(0)
|
||||||
|
.and change { GekanatorQuestionExample.count }.by(0)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(GekanatorQuestionSuggestion.last.processed).to eq(false)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'limits suggestions to three per game' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
3.times do |i|
|
||||||
|
GekanatorQuestionSuggestion.create!(
|
||||||
|
gekanator_game: game,
|
||||||
|
user: admin,
|
||||||
|
question_text: "existing question #{i}",
|
||||||
|
answer: 'unknown'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post '/gekanator/question_suggestions', params: {
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
question_text: 'fourth question?',
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
}.not_to change { GekanatorQuestionSuggestion.count }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'returns not found for a non-admin user' do
|
||||||
|
sign_in_as member
|
||||||
|
|
||||||
|
post '/gekanator/question_suggestions', params: {
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
question_text: 'member question?',
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:not_found)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /gekanator/games/:id/extra_questions' do
|
||||||
|
it 'returns at most two accepted user_suggested post_similarity questions' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
low = create_post_similarity_question!(
|
||||||
|
text: 'low?',
|
||||||
|
priority_weight: 1.0
|
||||||
|
)
|
||||||
|
high = create_post_similarity_question!(
|
||||||
|
text: 'high?',
|
||||||
|
priority_weight: 3.0
|
||||||
|
)
|
||||||
|
middle = create_post_similarity_question!(
|
||||||
|
text: 'middle?',
|
||||||
|
priority_weight: 2.0
|
||||||
|
)
|
||||||
|
|
||||||
|
get "/gekanator/games/#{game.id}/extra_questions"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['questions'].length).to eq(2)
|
||||||
|
expect(json['questions'].map { _1['id'] }).to eq([high.id, middle.id])
|
||||||
|
expect(json['questions'].map { _1['id'] }).not_to include(low.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not return questions that already have an example for the correct post' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
existing = create_post_similarity_question!(text: 'already learned?')
|
||||||
|
fresh = create_post_similarity_question!(text: 'fresh?')
|
||||||
|
|
||||||
|
GekanatorQuestionExample.create!(
|
||||||
|
gekanator_question: existing,
|
||||||
|
post: correct_post,
|
||||||
|
user: admin,
|
||||||
|
gekanator_game: game,
|
||||||
|
answer: 'yes',
|
||||||
|
source: 'post_game_extra'
|
||||||
|
)
|
||||||
|
|
||||||
|
get "/gekanator/games/#{game.id}/extra_questions"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['questions'].map { _1['id'] }).to include(fresh.id)
|
||||||
|
expect(json['questions'].map { _1['id'] }).not_to include(existing.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not return questions already asked in the game using snake_case question_id' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
asked = create_post_similarity_question!(text: 'already asked?')
|
||||||
|
fresh = create_post_similarity_question!(text: 'fresh?')
|
||||||
|
game.update!(
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
'question_id' => "post-similarity:#{asked.id}",
|
||||||
|
'answer' => 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
get "/gekanator/games/#{game.id}/extra_questions"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['questions'].map { _1['id'] }).to include(fresh.id)
|
||||||
|
expect(json['questions'].map { _1['id'] }).not_to include(asked.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not return questions already asked in the game using camelCase questionId' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
asked = create_post_similarity_question!(text: 'already asked?')
|
||||||
|
fresh = create_post_similarity_question!(text: 'fresh?')
|
||||||
|
game.update!(
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
'questionId' => "post-similarity:#{asked.id}",
|
||||||
|
'answer' => 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
get "/gekanator/games/#{game.id}/extra_questions"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['questions'].map { _1['id'] }).to include(fresh.id)
|
||||||
|
expect(json['questions'].map { _1['id'] }).not_to include(asked.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'does not return non-accepted, non-user_suggested, or non-post_similarity questions' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
accepted = create_post_similarity_question!(text: 'accepted?')
|
||||||
|
create_post_similarity_question!(text: 'disabled?', status: 'disabled')
|
||||||
|
create_post_similarity_question!(text: 'ai?', source: 'ai_generated')
|
||||||
|
GekanatorQuestion.create!(
|
||||||
|
text: 'tag?',
|
||||||
|
kind: 'tag',
|
||||||
|
source: 'user_suggested',
|
||||||
|
status: 'accepted',
|
||||||
|
priority_weight: 1.0,
|
||||||
|
condition: { type: 'tag', key: 'character:喜多郁代' }
|
||||||
|
)
|
||||||
|
|
||||||
|
get "/gekanator/games/#{game.id}/extra_questions"
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['questions'].map { _1['id'] }).to contain_exactly(accepted.id)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'POST /gekanator/games/:id/extra_question_answers' do
|
||||||
|
it 'creates examples for extra question answers' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
question = create_post_similarity_question!(text: 'extra?')
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: question.id.to_s,
|
||||||
|
answer: 'partial'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}.to change { GekanatorQuestionExample.count }.by(1)
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(json).to include('count' => 1)
|
||||||
|
|
||||||
|
example = GekanatorQuestionExample.last
|
||||||
|
expect(example).to have_attributes(
|
||||||
|
gekanator_question_id: question.id,
|
||||||
|
post_id: correct_post.id,
|
||||||
|
user_id: admin.id,
|
||||||
|
gekanator_game_id: game.id,
|
||||||
|
answer: 'partial',
|
||||||
|
source: 'post_game_extra',
|
||||||
|
weight: 1.0
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'updates an existing example for the same question, post, and user' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
question = create_post_similarity_question!(text: 'extra?')
|
||||||
|
existing = GekanatorQuestionExample.create!(
|
||||||
|
gekanator_question: question,
|
||||||
|
post: correct_post,
|
||||||
|
user: admin,
|
||||||
|
answer: 'no',
|
||||||
|
source: 'post_game_extra',
|
||||||
|
weight: 1.0
|
||||||
|
)
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: question.id,
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}.not_to change { GekanatorQuestionExample.count }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:created)
|
||||||
|
expect(existing.reload).to have_attributes(
|
||||||
|
answer: 'yes',
|
||||||
|
source: 'post_game_extra',
|
||||||
|
gekanator_game_id: game.id
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'rejects missing questions' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
expect {
|
||||||
|
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: 999_999_999,
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}.not_to change { GekanatorQuestionExample.count }
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'rejects non-accepted questions' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
question = create_post_similarity_question!(
|
||||||
|
text: 'disabled?',
|
||||||
|
status: 'disabled'
|
||||||
|
)
|
||||||
|
|
||||||
|
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: question.id,
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'rejects non-post_similarity questions' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
question = GekanatorQuestion.create!(
|
||||||
|
text: 'tag?',
|
||||||
|
kind: 'tag',
|
||||||
|
source: 'user_suggested',
|
||||||
|
status: 'accepted',
|
||||||
|
priority_weight: 1.0,
|
||||||
|
condition: { type: 'tag', key: 'character:喜多郁代' }
|
||||||
|
)
|
||||||
|
|
||||||
|
post "/gekanator/games/#{game.id}/extra_question_answers", params: {
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: question.id,
|
||||||
|
answer: 'yes'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:unprocessable_entity)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe 'GET /gekanator/questions' do
|
||||||
|
it 'returns accepted questions only and includes example_answers for post_similarity questions' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
accepted = create_post_similarity_question!(text: 'accepted?')
|
||||||
|
create_post_similarity_question!(
|
||||||
|
text: 'disabled?',
|
||||||
|
status: 'disabled'
|
||||||
|
)
|
||||||
|
|
||||||
|
GekanatorQuestionExample.create!(
|
||||||
|
gekanator_question: accepted,
|
||||||
|
post: correct_post,
|
||||||
|
user: admin,
|
||||||
|
answer: 'yes',
|
||||||
|
source: 'initial_suggestion',
|
||||||
|
weight: 1.0
|
||||||
|
)
|
||||||
|
|
||||||
|
get '/gekanator/questions'
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
expect(json['questions'].length).to eq(1)
|
||||||
|
|
||||||
|
question_json = json['questions'].first
|
||||||
|
expect(question_json).to include(
|
||||||
|
'id' => "post-similarity:#{accepted.id}",
|
||||||
|
'text' => 'accepted?',
|
||||||
|
'kind' => 'post_similarity',
|
||||||
|
'source' => 'user_suggested',
|
||||||
|
'priority_weight' => 1.2
|
||||||
|
)
|
||||||
|
expect(question_json['condition']).to include(
|
||||||
|
'type' => 'post-similarity',
|
||||||
|
'postId' => correct_post.id,
|
||||||
|
'answer' => 'yes',
|
||||||
|
'threshold' => 0.65
|
||||||
|
)
|
||||||
|
expect(question_json['example_answers']).to include(
|
||||||
|
correct_post.id.to_s => 'yes'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'aggregates example_answers by weight' do
|
||||||
|
sign_in_as admin
|
||||||
|
|
||||||
|
question = create_post_similarity_question!(text: 'weighted?')
|
||||||
|
|
||||||
|
GekanatorQuestionExample.create!(
|
||||||
|
gekanator_question: question,
|
||||||
|
post: other_post,
|
||||||
|
user: admin,
|
||||||
|
answer: 'yes',
|
||||||
|
source: 'post_game_extra',
|
||||||
|
weight: 1.0
|
||||||
|
)
|
||||||
|
GekanatorQuestionExample.create!(
|
||||||
|
gekanator_question: question,
|
||||||
|
post: other_post,
|
||||||
|
user: other_user,
|
||||||
|
answer: 'no',
|
||||||
|
source: 'post_game_extra',
|
||||||
|
weight: 2.0
|
||||||
|
)
|
||||||
|
|
||||||
|
get '/gekanator/questions'
|
||||||
|
|
||||||
|
expect(response).to have_http_status(:ok)
|
||||||
|
question_json = json['questions'].find { _1['id'] == "post-similarity:#{question.id}" }
|
||||||
|
expect(question_json['example_answers']).to include(
|
||||||
|
other_post.id.to_s => 'no'
|
||||||
|
)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -33,6 +33,10 @@ npm run lint
|
|||||||
|
|
||||||
If either command cannot be run or fails, report the exact command and failure.
|
If either command cannot be run or fails, report the exact command and failure.
|
||||||
|
|
||||||
|
Do not create, modify, or run tests unless the user explicitly asks for test
|
||||||
|
work. When the user asks for tests, keep working and rerun them until they
|
||||||
|
pass or the remaining failure is clearly blocked.
|
||||||
|
|
||||||
## TypeScript
|
## TypeScript
|
||||||
|
|
||||||
- TypeScript is strict. `tsconfig.app.json` enables `strict`,
|
- TypeScript is strict. `tsconfig.app.json` enables `strict`,
|
||||||
|
|||||||
+16
-1
@@ -18,6 +18,7 @@ import MaterialListPage from '@/pages/materials/MaterialListPage'
|
|||||||
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
|
import MaterialNewPage from '@/pages/materials/MaterialNewPage'
|
||||||
// import MaterialSearchPage from '@/pages/materials/MaterialSearchPage'
|
// import MaterialSearchPage from '@/pages/materials/MaterialSearchPage'
|
||||||
import MorePage from '@/pages/MorePage'
|
import MorePage from '@/pages/MorePage'
|
||||||
|
import GekanatorPage from '@/pages/GekanatorPage'
|
||||||
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
|
import NicoTagListPage from '@/pages/tags/NicoTagListPage'
|
||||||
import NotFound from '@/pages/NotFound'
|
import NotFound from '@/pages/NotFound'
|
||||||
import TOSPage from '@/pages/TOSPage.mdx'
|
import TOSPage from '@/pages/TOSPage.mdx'
|
||||||
@@ -39,7 +40,7 @@ import WikiHistoryPage from '@/pages/wiki/WikiHistoryPage'
|
|||||||
import WikiNewPage from '@/pages/wiki/WikiNewPage'
|
import WikiNewPage from '@/pages/wiki/WikiNewPage'
|
||||||
import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
|
import WikiSearchPage from '@/pages/wiki/WikiSearchPage'
|
||||||
|
|
||||||
import type { Dispatch, FC, SetStateAction } from 'react'
|
import type { Dispatch, FC, ReactNode, SetStateAction } from 'react'
|
||||||
|
|
||||||
import type { User } from '@/types'
|
import type { User } from '@/types'
|
||||||
|
|
||||||
@@ -80,6 +81,10 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
|||||||
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
|
<Route path="/users/settings" element={<SettingPage user={user} setUser={setUser}/>}/>
|
||||||
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
|
<Route path="/settings" element={<Navigate to="/users/settings" replace/>}/>
|
||||||
<Route path="/tos" element={<TOSPage/>}/>
|
<Route path="/tos" element={<TOSPage/>}/>
|
||||||
|
<Route path="/gekanator" element={
|
||||||
|
<AdminOnly user={user}>
|
||||||
|
<GekanatorPage/>
|
||||||
|
</AdminOnly>}/>
|
||||||
<Route path="/more" element={<MorePage/>}/>
|
<Route path="/more" element={<MorePage/>}/>
|
||||||
<Route path="*" element={<NotFound/>}/>
|
<Route path="*" element={<NotFound/>}/>
|
||||||
</Routes>
|
</Routes>
|
||||||
@@ -87,6 +92,16 @@ const RouteTransitionWrapper = ({ user, setUser }: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const AdminOnly = ({ user, children }: {
|
||||||
|
user: User | null
|
||||||
|
children: ReactNode }) => {
|
||||||
|
if (user?.role !== 'admin')
|
||||||
|
return <NotFound/>
|
||||||
|
|
||||||
|
return <>{children}</>
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const PostDetailRoute = ({ user }: { user: User | null }) => {
|
const PostDetailRoute = ({ user }: { user: User | null }) => {
|
||||||
const location = useLocation ()
|
const location = useLocation ()
|
||||||
const key = location.pathname
|
const key = location.pathname
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { apiPost } from '@/lib/api'
|
||||||
|
import {
|
||||||
|
expectedAnswerForQuestion,
|
||||||
|
restoreGekanatorQuestion,
|
||||||
|
saveGekanatorExtraQuestionAnswers,
|
||||||
|
saveGekanatorGame,
|
||||||
|
saveGekanatorQuestionSuggestion,
|
||||||
|
} from '@/lib/gekanator'
|
||||||
|
|
||||||
|
import type {
|
||||||
|
GekanatorAnswerLog,
|
||||||
|
StoredGekanatorQuestion,
|
||||||
|
} from '@/lib/gekanator'
|
||||||
|
import type { Post } from '@/types'
|
||||||
|
|
||||||
|
vi.mock('@/lib/api', () => ({
|
||||||
|
apiGet: vi.fn(),
|
||||||
|
apiPost: vi.fn(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
const mockedApiPost = vi.mocked(apiPost)
|
||||||
|
|
||||||
|
const post = (overrides: Partial<Post> = {}): Post => ({
|
||||||
|
id: 1,
|
||||||
|
url: 'https://example.com/posts/1',
|
||||||
|
title: 'post title',
|
||||||
|
thumbnail: null,
|
||||||
|
thumbnailBase: null,
|
||||||
|
tags: [],
|
||||||
|
viewed: false,
|
||||||
|
related: [],
|
||||||
|
originalCreatedFrom: null,
|
||||||
|
originalCreatedBefore: null,
|
||||||
|
createdAt: '2026-06-10T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-06-10T00:00:00.000Z',
|
||||||
|
uploadedUser: null,
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('expectedAnswerForQuestion', () => {
|
||||||
|
it('returns a direct example answer when present', () => {
|
||||||
|
const question: StoredGekanatorQuestion = {
|
||||||
|
id: 'post-similarity:10',
|
||||||
|
text: '喜多ちゃんが泣いてる?',
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: 'user_suggested',
|
||||||
|
priorityWeight: 1.2,
|
||||||
|
condition: {
|
||||||
|
type: 'post-similarity',
|
||||||
|
postId: 999,
|
||||||
|
answer: 'yes',
|
||||||
|
threshold: 0.65,
|
||||||
|
},
|
||||||
|
exampleAnswers: {
|
||||||
|
1: 'partial',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(expectedAnswerForQuestion(question, post({ id: 1 }))).toBe('partial')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns the condition answer for the original post_similarity post', () => {
|
||||||
|
const question: StoredGekanatorQuestion = {
|
||||||
|
id: 'post-similarity:10',
|
||||||
|
text: '喜多ちゃんが泣いてる?',
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: 'user_suggested',
|
||||||
|
priorityWeight: 1.2,
|
||||||
|
condition: {
|
||||||
|
type: 'post-similarity',
|
||||||
|
postId: 123,
|
||||||
|
answer: 'probably_no',
|
||||||
|
threshold: 0.65,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(expectedAnswerForQuestion(question, post({ id: 123 }))).toBe('probably_no')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns null for an unrelated post_similarity post without examples', () => {
|
||||||
|
const question: StoredGekanatorQuestion = {
|
||||||
|
id: 'post-similarity:10',
|
||||||
|
text: '喜多ちゃんが泣いてる?',
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: 'user_suggested',
|
||||||
|
priorityWeight: 1.2,
|
||||||
|
condition: {
|
||||||
|
type: 'post-similarity',
|
||||||
|
postId: 123,
|
||||||
|
answer: 'yes',
|
||||||
|
threshold: 0.65,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(expectedAnswerForQuestion(question, post({ id: 456 }))).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns yes for a matching tag question', () => {
|
||||||
|
const question: StoredGekanatorQuestion = {
|
||||||
|
id: 'tag:character:喜多郁代',
|
||||||
|
text: '喜多ちゃんが関係してる?',
|
||||||
|
kind: 'tag',
|
||||||
|
condition: {
|
||||||
|
type: 'tag',
|
||||||
|
key: 'character:喜多郁代',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(
|
||||||
|
expectedAnswerForQuestion(
|
||||||
|
question,
|
||||||
|
post({
|
||||||
|
tags: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
name: '喜多郁代',
|
||||||
|
category: 'character',
|
||||||
|
aliases: [],
|
||||||
|
parents: [],
|
||||||
|
postCount: 1,
|
||||||
|
createdAt: '2026-06-10T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-06-10T00:00:00.000Z',
|
||||||
|
hasWiki: false,
|
||||||
|
materialId: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toBe('yes')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns no for a non-matching tag question', () => {
|
||||||
|
const question: StoredGekanatorQuestion = {
|
||||||
|
id: 'tag:character:喜多郁代',
|
||||||
|
text: '喜多ちゃんが関係してる?',
|
||||||
|
kind: 'tag',
|
||||||
|
condition: {
|
||||||
|
type: 'tag',
|
||||||
|
key: 'character:喜多郁代',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(expectedAnswerForQuestion(question, post({ tags: [] }))).toBe('no')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('restoreGekanatorQuestion', () => {
|
||||||
|
it('uses default source and priority weight when omitted', () => {
|
||||||
|
const question = restoreGekanatorQuestion({
|
||||||
|
id: 'tag:character:喜多郁代',
|
||||||
|
text: '喜多ちゃんが関係してる?',
|
||||||
|
kind: 'tag',
|
||||||
|
condition: {
|
||||||
|
type: 'tag',
|
||||||
|
key: 'character:喜多郁代',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(question.source).toBe('default')
|
||||||
|
expect(question.priorityWeight).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('tests a post_similarity question using direct examples', () => {
|
||||||
|
const question = restoreGekanatorQuestion({
|
||||||
|
id: 'post-similarity:10',
|
||||||
|
text: '喜多ちゃんが泣いてる?',
|
||||||
|
kind: 'post_similarity',
|
||||||
|
source: 'user_suggested',
|
||||||
|
priorityWeight: 1.2,
|
||||||
|
condition: {
|
||||||
|
type: 'post-similarity',
|
||||||
|
postId: 999,
|
||||||
|
answer: 'yes',
|
||||||
|
threshold: 0.65,
|
||||||
|
},
|
||||||
|
exampleAnswers: {
|
||||||
|
1: 'yes',
|
||||||
|
2: 'no',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(question.test(post({ id: 1 }))).toBe(true)
|
||||||
|
expect(question.test(post({ id: 2 }))).toBe(false)
|
||||||
|
expect(question.test(post({ id: 3 }))).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('Gekanator API writers', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockedApiPost.mockReset()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sends game results using snake_case request keys', async () => {
|
||||||
|
mockedApiPost.mockResolvedValue({ id: 100 })
|
||||||
|
|
||||||
|
const answers: GekanatorAnswerLog[] = [
|
||||||
|
{
|
||||||
|
questionId: 'tag:character:喜多郁代',
|
||||||
|
questionText: '喜多ちゃんが関係してる?',
|
||||||
|
questionCondition: {
|
||||||
|
type: 'tag',
|
||||||
|
key: 'character:喜多郁代',
|
||||||
|
},
|
||||||
|
answer: 'yes',
|
||||||
|
originalAnswer: 'partial',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
saveGekanatorGame({
|
||||||
|
guessedPostId: 1,
|
||||||
|
correctPostId: 2,
|
||||||
|
answers,
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({ id: 100 })
|
||||||
|
|
||||||
|
expect(mockedApiPost).toHaveBeenCalledWith('/gekanator/games', {
|
||||||
|
guessed_post_id: 1,
|
||||||
|
correct_post_id: 2,
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: 'tag:character:喜多郁代',
|
||||||
|
question_text: '喜多ちゃんが関係してる?',
|
||||||
|
question_condition: {
|
||||||
|
type: 'tag',
|
||||||
|
key: 'character:喜多郁代',
|
||||||
|
},
|
||||||
|
answer: 'yes',
|
||||||
|
original_answer: 'partial',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sends question suggestions using snake_case request keys', async () => {
|
||||||
|
mockedApiPost.mockResolvedValue({
|
||||||
|
id: 10,
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
saveGekanatorQuestionSuggestion({
|
||||||
|
gekanatorGameId: 100,
|
||||||
|
questionText: '喜多ちゃんが泣いてる?',
|
||||||
|
answer: 'yes',
|
||||||
|
}),
|
||||||
|
).resolves.toEqual({
|
||||||
|
id: 10,
|
||||||
|
count: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(mockedApiPost).toHaveBeenCalledWith('/gekanator/question_suggestions', {
|
||||||
|
gekanator_game_id: 100,
|
||||||
|
question_text: '喜多ちゃんが泣いてる?',
|
||||||
|
answer: 'yes',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sends extra question answers using snake_case request keys', async () => {
|
||||||
|
mockedApiPost.mockResolvedValue({
|
||||||
|
count: 2,
|
||||||
|
})
|
||||||
|
|
||||||
|
await saveGekanatorExtraQuestionAnswers({
|
||||||
|
gameId: 100,
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
questionId: 10,
|
||||||
|
answer: 'yes',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
questionId: 11,
|
||||||
|
answer: 'probably_no',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(mockedApiPost).toHaveBeenCalledWith(
|
||||||
|
'/gekanator/games/100/extra_question_answers',
|
||||||
|
{
|
||||||
|
answers: [
|
||||||
|
{
|
||||||
|
question_id: 10,
|
||||||
|
answer: 'yes',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
question_id: 11,
|
||||||
|
answer: 'probably_no',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,483 @@
|
|||||||
|
import { apiGet, apiPost } from '@/lib/api'
|
||||||
|
|
||||||
|
import type { Post } from '@/types'
|
||||||
|
|
||||||
|
export type GekanatorAnswerValue =
|
||||||
|
| 'yes'
|
||||||
|
| 'no'
|
||||||
|
| 'partial'
|
||||||
|
| 'probably_no'
|
||||||
|
| 'unknown'
|
||||||
|
|
||||||
|
export type GekanatorAnswerLog = {
|
||||||
|
questionId: string
|
||||||
|
questionText: string
|
||||||
|
questionCondition?: GekanatorQuestionCondition
|
||||||
|
answer: GekanatorAnswerValue
|
||||||
|
originalAnswer: GekanatorAnswerValue }
|
||||||
|
|
||||||
|
export type GekanatorQuestionKind =
|
||||||
|
| 'tag'
|
||||||
|
| 'source'
|
||||||
|
| 'title'
|
||||||
|
| 'original_date'
|
||||||
|
| 'post_similarity'
|
||||||
|
|
||||||
|
export type GekanatorQuestionSource =
|
||||||
|
| 'default'
|
||||||
|
| 'user_suggested'
|
||||||
|
| 'ai_generated'
|
||||||
|
| 'admin_curated'
|
||||||
|
|
||||||
|
export type GekanatorQuestionCondition =
|
||||||
|
| { type: 'tag'; key: string }
|
||||||
|
| { type: 'source'; host: string }
|
||||||
|
| { type: 'original-year'; year: number }
|
||||||
|
| { type: 'original-month'; month: number }
|
||||||
|
| { type: 'original-month-day'; monthDay: string }
|
||||||
|
| { type: 'title-length-greater-than'; length: number }
|
||||||
|
| { type: 'title-has-ascii' }
|
||||||
|
| {
|
||||||
|
type: 'post-similarity'
|
||||||
|
postId: number
|
||||||
|
answer: GekanatorAnswerValue
|
||||||
|
threshold: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GekanatorExtraQuestion = {
|
||||||
|
id: number
|
||||||
|
text: string
|
||||||
|
source: GekanatorQuestionSource
|
||||||
|
priorityWeight: number }
|
||||||
|
|
||||||
|
export type StoredGekanatorQuestion = {
|
||||||
|
id: string
|
||||||
|
text: string
|
||||||
|
kind: GekanatorQuestionKind
|
||||||
|
condition: GekanatorQuestionCondition
|
||||||
|
source?: GekanatorQuestionSource
|
||||||
|
priorityWeight?: number
|
||||||
|
exampleAnswers?: Record<`${ number }`, GekanatorAnswerValue> }
|
||||||
|
|
||||||
|
export type GekanatorQuestion = {
|
||||||
|
id: string
|
||||||
|
text: string
|
||||||
|
kind: GekanatorQuestionKind
|
||||||
|
condition: GekanatorQuestionCondition
|
||||||
|
source: GekanatorQuestionSource
|
||||||
|
priorityWeight: number
|
||||||
|
exampleAnswers?: Record<`${ number }`, GekanatorAnswerValue>
|
||||||
|
test: (post: Post) => boolean }
|
||||||
|
|
||||||
|
|
||||||
|
const directExampleAnswerFor = (
|
||||||
|
question: StoredGekanatorQuestion,
|
||||||
|
post: Post,
|
||||||
|
): GekanatorAnswerValue | null => {
|
||||||
|
const direct = question.exampleAnswers?.[String (post.id) as `${ number }`]
|
||||||
|
if (direct)
|
||||||
|
return direct
|
||||||
|
|
||||||
|
if (question.condition.type === 'post-similarity' && question.condition.postId === post.id)
|
||||||
|
return question.condition.answer
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const countBy = <T extends string | number> (values: T[]): Map<T, number> => {
|
||||||
|
const counts = new Map<T, number> ()
|
||||||
|
values.forEach (value => counts.set (value, (counts.get (value) ?? 0) + 1))
|
||||||
|
return counts
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const median = (values: number[]): number => {
|
||||||
|
const sorted = [...values].sort ((a, b) => a - b)
|
||||||
|
return sorted[Math.floor (sorted.length / 2)] ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const hostOf = (post: Post): string | null => {
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new URL (post.url).hostname.replace (/^www\./, '')
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const originalYearOf = (post: Post): number | null => {
|
||||||
|
const value = post.originalCreatedFrom || post.originalCreatedBefore
|
||||||
|
if (!(value))
|
||||||
|
return null
|
||||||
|
|
||||||
|
const date = new Date (value)
|
||||||
|
if (Number.isNaN (date.getTime ()))
|
||||||
|
return null
|
||||||
|
|
||||||
|
return date.getFullYear ()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const originalDateOf = (post: Post): Date | null => {
|
||||||
|
const value = post.originalCreatedFrom || post.originalCreatedBefore
|
||||||
|
if (!(value))
|
||||||
|
return null
|
||||||
|
|
||||||
|
const date = new Date (value)
|
||||||
|
if (Number.isNaN (date.getTime ()))
|
||||||
|
return null
|
||||||
|
|
||||||
|
return date
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const originalMonthOf = (post: Post): number | null => {
|
||||||
|
const date = originalDateOf (post)
|
||||||
|
if (!(date))
|
||||||
|
return null
|
||||||
|
|
||||||
|
return date.getMonth () + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const originalMonthDayOf = (post: Post): string | null => {
|
||||||
|
const date = originalDateOf (post)
|
||||||
|
if (!(date))
|
||||||
|
return null
|
||||||
|
|
||||||
|
return `${ date.getMonth () + 1 }-${ date.getDate () }`
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const tagQuestionKey = ({ category, name }: { category: string; name: string }): string =>
|
||||||
|
`${ category }:${ name }`
|
||||||
|
|
||||||
|
|
||||||
|
const tagFromQuestionKey = (key: string): { category: string; name: string } => {
|
||||||
|
const [category, ...rest] = key.split (':')
|
||||||
|
return { category: category ?? '', name: rest.join (':') }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const nicoTagLabel = (name: string): string => name.replace (/^nico:/, '')
|
||||||
|
|
||||||
|
|
||||||
|
const tagQuestionText = (category: string, label: string): string => {
|
||||||
|
switch (category)
|
||||||
|
{
|
||||||
|
case 'deerjikist':
|
||||||
|
return `作者・ニジラーとして「${ label }」に関係してゐる?`
|
||||||
|
case 'meme':
|
||||||
|
return `元ネタ・ミームとして「${ label }」に関係しさう?`
|
||||||
|
case 'character':
|
||||||
|
return `「${ label }」といふキャラクターが関係してゐる?`
|
||||||
|
case 'material':
|
||||||
|
return `素材として「${ label }」に関係してゐる?`
|
||||||
|
case 'nico':
|
||||||
|
return `ニコニコに「${ label }」といふタグが付いてゐる?`
|
||||||
|
case 'general':
|
||||||
|
case 'meta':
|
||||||
|
default:
|
||||||
|
return `内容として「${ label }」に関係しさう?`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const questionableTag = (post: Post, key: string): boolean => {
|
||||||
|
const { category, name } = tagFromQuestionKey (key)
|
||||||
|
|
||||||
|
return (
|
||||||
|
post.tags.some (tag =>
|
||||||
|
tag.name === name
|
||||||
|
&& tag.category === category
|
||||||
|
&& !(tag.category === 'meta')
|
||||||
|
&& !(tag.name.includes ('タグ希望'))
|
||||||
|
&& !(tag.name.includes ('bot操作'))))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const questionMatches = (
|
||||||
|
post: Post,
|
||||||
|
question: StoredGekanatorQuestion,
|
||||||
|
): boolean => {
|
||||||
|
const directAnswer = directExampleAnswerFor (question, post)
|
||||||
|
if (directAnswer)
|
||||||
|
return question.condition.type === 'post-similarity'
|
||||||
|
? directAnswer === question.condition.answer
|
||||||
|
: directAnswer === 'yes'
|
||||||
|
|
||||||
|
switch (question.condition.type)
|
||||||
|
{
|
||||||
|
case 'tag':
|
||||||
|
return questionableTag (post, question.condition.key)
|
||||||
|
case 'source':
|
||||||
|
return hostOf (post) === question.condition.host
|
||||||
|
case 'original-year':
|
||||||
|
return originalYearOf (post) === question.condition.year
|
||||||
|
case 'original-month':
|
||||||
|
return originalMonthOf (post) === question.condition.month
|
||||||
|
case 'original-month-day':
|
||||||
|
return originalMonthDayOf (post) === question.condition.monthDay
|
||||||
|
case 'title-length-greater-than':
|
||||||
|
return (post.title?.length ?? 0) > question.condition.length
|
||||||
|
case 'title-has-ascii':
|
||||||
|
return /[A-Za-z0-9]/.test (post.title ?? '')
|
||||||
|
case 'post-similarity':
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const expectedAnswerForQuestion = (
|
||||||
|
question: StoredGekanatorQuestion | GekanatorQuestion | undefined,
|
||||||
|
post: Post | null,
|
||||||
|
): GekanatorAnswerValue | null => {
|
||||||
|
if (!(question) || !(post))
|
||||||
|
return null
|
||||||
|
|
||||||
|
const directAnswer = directExampleAnswerFor (question, post)
|
||||||
|
if (directAnswer)
|
||||||
|
return directAnswer
|
||||||
|
|
||||||
|
switch (question.condition.type)
|
||||||
|
{
|
||||||
|
case 'tag':
|
||||||
|
case 'source':
|
||||||
|
case 'original-year':
|
||||||
|
case 'original-month':
|
||||||
|
case 'original-month-day':
|
||||||
|
case 'title-length-greater-than':
|
||||||
|
case 'title-has-ascii':
|
||||||
|
return questionMatches (post, question) ? 'yes' : 'no'
|
||||||
|
case 'post-similarity':
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const restoreGekanatorQuestion = (
|
||||||
|
question: StoredGekanatorQuestion,
|
||||||
|
): GekanatorQuestion => ({
|
||||||
|
...question,
|
||||||
|
source: question.source ?? 'default',
|
||||||
|
priorityWeight: question.priorityWeight ?? 1,
|
||||||
|
test: (post: Post) => questionMatches (post, question) })
|
||||||
|
|
||||||
|
|
||||||
|
export const storeGekanatorQuestion = (
|
||||||
|
question: GekanatorQuestion,
|
||||||
|
): StoredGekanatorQuestion => ({
|
||||||
|
id: question.id,
|
||||||
|
text: question.text,
|
||||||
|
kind: question.kind,
|
||||||
|
condition: question.condition,
|
||||||
|
source: question.source,
|
||||||
|
priorityWeight: question.priorityWeight,
|
||||||
|
exampleAnswers: question.exampleAnswers })
|
||||||
|
|
||||||
|
|
||||||
|
export const fetchGekanatorPosts = async (): Promise<Post[]> => {
|
||||||
|
const data = await apiGet<{ posts: Post[] }> ('/gekanator/posts')
|
||||||
|
return data.posts
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const fetchGekanatorQuestions = async (): Promise<StoredGekanatorQuestion[]> => {
|
||||||
|
const data = await apiGet<{ questions: StoredGekanatorQuestion[] }> ('/gekanator/questions')
|
||||||
|
return data.questions
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const fetchGekanatorExtraQuestions = async (
|
||||||
|
gameId: number,
|
||||||
|
): Promise<GekanatorExtraQuestion[]> => {
|
||||||
|
const data = await apiGet<{ questions: GekanatorExtraQuestion[] }> (
|
||||||
|
`/gekanator/games/${ gameId }/extra_questions`)
|
||||||
|
return data.questions
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const buildGekanatorQuestions = (posts: Post[]): GekanatorQuestion[] => {
|
||||||
|
const tagCounts = countBy (posts.flatMap (post =>
|
||||||
|
post.tags
|
||||||
|
.filter (tag =>
|
||||||
|
!(tag.category === 'meta')
|
||||||
|
&& !(tag.name.includes ('タグ希望'))
|
||||||
|
&& !(tag.name.includes ('bot操作')))
|
||||||
|
.map (tag => tagQuestionKey (tag))))
|
||||||
|
const hosts = countBy (posts.map (hostOf).filter ((host): host is string => Boolean (host)))
|
||||||
|
const originalYears = countBy (
|
||||||
|
posts
|
||||||
|
.map (originalYearOf)
|
||||||
|
.filter ((year): year is number => year !== null))
|
||||||
|
const originalMonths = countBy (
|
||||||
|
posts
|
||||||
|
.map (originalMonthOf)
|
||||||
|
.filter ((month): month is number => month !== null))
|
||||||
|
const originalMonthDays = countBy (
|
||||||
|
posts
|
||||||
|
.map (originalMonthDayOf)
|
||||||
|
.filter ((monthDay): monthDay is string => monthDay !== null))
|
||||||
|
const titleLengthMedian = median (posts.map (post => post.title?.length ?? 0))
|
||||||
|
|
||||||
|
const usefulEntries = <T extends string | number> (counts: Map<T, number>) =>
|
||||||
|
[...counts.entries ()]
|
||||||
|
.filter (([, count]) => count > 0 && count < posts.length)
|
||||||
|
.sort ((a, b) => Math.abs (posts.length / 2 - a[1])
|
||||||
|
- Math.abs (posts.length / 2 - b[1]))
|
||||||
|
.slice (0, 80)
|
||||||
|
|
||||||
|
const tagQuestions = usefulEntries (tagCounts)
|
||||||
|
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||||
|
.slice (0, 80)
|
||||||
|
.map (([key]) => {
|
||||||
|
const { category, name } = tagFromQuestionKey (String (key))
|
||||||
|
const label = category === 'nico' ? nicoTagLabel (name) : name
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: `tag:${ key }`,
|
||||||
|
text: tagQuestionText (category, label),
|
||||||
|
kind: 'tag' as const,
|
||||||
|
condition: { type: 'tag' as const, key: String (key) },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => questionableTag (post, String (key)) }
|
||||||
|
})
|
||||||
|
|
||||||
|
const sourceQuestions = usefulEntries (hosts)
|
||||||
|
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||||
|
.slice (0, 20)
|
||||||
|
.map (([host]) => ({
|
||||||
|
id: `source:${ host }`,
|
||||||
|
text: `${ host } の投稿を思ひ浮かべてゐる?`,
|
||||||
|
kind: 'source' as const,
|
||||||
|
condition: { type: 'source' as const, host },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => hostOf (post) === host }))
|
||||||
|
|
||||||
|
const originalYearQuestions = usefulEntries (originalYears)
|
||||||
|
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||||
|
.slice (0, 20)
|
||||||
|
.map (([year]) => ({
|
||||||
|
id: `original-year:${ year }`,
|
||||||
|
text: `オリジナルの投稿年は ${ year } 年?`,
|
||||||
|
kind: 'original_date' as const,
|
||||||
|
condition: { type: 'original-year' as const, year },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => originalYearOf (post) === year }))
|
||||||
|
|
||||||
|
const originalMonthQuestions = usefulEntries (originalMonths)
|
||||||
|
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||||
|
.slice (0, 20)
|
||||||
|
.map (([month]) => ({
|
||||||
|
id: `original-month:${ month }`,
|
||||||
|
text: `オリジナルの投稿月は ${ month } 月?`,
|
||||||
|
kind: 'original_date' as const,
|
||||||
|
condition: { type: 'original-month' as const, month },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => originalMonthOf (post) === month }))
|
||||||
|
|
||||||
|
const originalMonthDayQuestions = usefulEntries (originalMonthDays)
|
||||||
|
.filter (([, count]) => count >= 2 && count <= Math.max (2, posts.length * .7))
|
||||||
|
.slice (0, 20)
|
||||||
|
.map (([monthDay]) => {
|
||||||
|
const [month, day] = String (monthDay).split ('-')
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: `original-month-day:${ monthDay }`,
|
||||||
|
text: `オリジナルの投稿日は ${ month } 月 ${ day } 日?`,
|
||||||
|
kind: 'original_date' as const,
|
||||||
|
condition: { type: 'original-month-day' as const, monthDay: String (monthDay) },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => originalMonthDayOf (post) === monthDay }
|
||||||
|
})
|
||||||
|
|
||||||
|
const titleQuestions = [
|
||||||
|
{
|
||||||
|
id: 'title:long',
|
||||||
|
text: '題名が長めの投稿?',
|
||||||
|
kind: 'title' as const,
|
||||||
|
condition: {
|
||||||
|
type: 'title-length-greater-than' as const,
|
||||||
|
length: titleLengthMedian },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => (post.title?.length ?? 0) > titleLengthMedian },
|
||||||
|
{
|
||||||
|
id: 'title:ascii',
|
||||||
|
text: '題名に英数字が混じってゐる?',
|
||||||
|
kind: 'title' as const,
|
||||||
|
condition: { type: 'title-has-ascii' as const },
|
||||||
|
source: 'default' as const,
|
||||||
|
priorityWeight: 1,
|
||||||
|
test: (post: Post) => /[A-Za-z0-9]/.test (post.title ?? '') }]
|
||||||
|
.filter (question => {
|
||||||
|
const yes = posts.filter (post => question.test (post)).length
|
||||||
|
const no = posts.length - yes
|
||||||
|
return yes >= 2 && no >= 2 && yes <= posts.length * .7 && no <= posts.length * .7
|
||||||
|
})
|
||||||
|
|
||||||
|
return [
|
||||||
|
...sourceQuestions,
|
||||||
|
...originalYearQuestions,
|
||||||
|
...originalMonthQuestions,
|
||||||
|
...originalMonthDayQuestions,
|
||||||
|
...titleQuestions,
|
||||||
|
...tagQuestions]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const saveGekanatorGame = async ({
|
||||||
|
guessedPostId,
|
||||||
|
correctPostId,
|
||||||
|
answers,
|
||||||
|
}: {
|
||||||
|
guessedPostId: number
|
||||||
|
correctPostId: number
|
||||||
|
answers: GekanatorAnswerLog[]
|
||||||
|
}): Promise<{ id: number }> =>
|
||||||
|
await apiPost ('/gekanator/games', {
|
||||||
|
guessed_post_id: guessedPostId,
|
||||||
|
correct_post_id: correctPostId,
|
||||||
|
answers: answers.map (answer => ({
|
||||||
|
question_id: answer.questionId,
|
||||||
|
question_text: answer.questionText,
|
||||||
|
question_condition: answer.questionCondition ?? null,
|
||||||
|
answer: answer.answer,
|
||||||
|
original_answer: answer.originalAnswer })) })
|
||||||
|
|
||||||
|
|
||||||
|
export const saveGekanatorQuestionSuggestion = async ({
|
||||||
|
gekanatorGameId,
|
||||||
|
questionText,
|
||||||
|
answer,
|
||||||
|
}: {
|
||||||
|
gekanatorGameId: number
|
||||||
|
questionText: string
|
||||||
|
answer: GekanatorAnswerValue
|
||||||
|
}): Promise<{ id: number; count: number }> =>
|
||||||
|
await apiPost ('/gekanator/question_suggestions', {
|
||||||
|
gekanator_game_id: gekanatorGameId,
|
||||||
|
question_text: questionText,
|
||||||
|
answer })
|
||||||
|
|
||||||
|
|
||||||
|
export const saveGekanatorExtraQuestionAnswers = async ({
|
||||||
|
gameId,
|
||||||
|
answers,
|
||||||
|
}: {
|
||||||
|
gameId: number
|
||||||
|
answers: { questionId: number; answer: GekanatorAnswerValue }[]
|
||||||
|
}) =>
|
||||||
|
await apiPost (`/gekanator/games/${ gameId }/extra_question_answers`, {
|
||||||
|
answers: answers.map (item => ({
|
||||||
|
question_id: item.questionId,
|
||||||
|
answer: item.answer })) })
|
||||||
@@ -8,6 +8,13 @@ export const postsKeys = {
|
|||||||
changes: (p: { post?: string; tag?: string; page: number; limit: number }) =>
|
changes: (p: { post?: string; tag?: string; page: number; limit: number }) =>
|
||||||
['posts', 'changes', p] as const }
|
['posts', 'changes', p] as const }
|
||||||
|
|
||||||
|
export const gekanatorKeys = {
|
||||||
|
root: ['gekanator'] as const,
|
||||||
|
posts: () => ['gekanator', 'posts'] as const,
|
||||||
|
questions: () => ['gekanator', 'questions'] as const,
|
||||||
|
extraQuestions: (gameId: number) =>
|
||||||
|
['gekanator', 'games', gameId, 'extra-questions'] as const }
|
||||||
|
|
||||||
export const tagsKeys = {
|
export const tagsKeys = {
|
||||||
root: ['tags'] as const,
|
root: ['tags'] as const,
|
||||||
index: (p: FetchTagsParams) => ['tags', 'index', p] as const,
|
index: (p: FetchTagsParams) => ['tags', 'index', p] as const,
|
||||||
|
|||||||
ファイル差分が大きすぎるため省略します
差分を読込み
新しい課題から参照
ユーザをブロックする