repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/import_request.rb | app/models/import_request.rb | class ImportRequest < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: ImportRequestTransition,
initial_state: ImportRequestStateMachine.initial_state
]
default_scope { order("import_requests.id DESC") }
belongs_to :manifestation, optional: true
belongs_to :user
validates :isbn, presence: true
validate :check_isbn
# validate :check_imported, on: :create
# validates_uniqueness_of :isbn, if: Proc.new{|request| ImportRequest.where("created_at > ?", 1.day.ago).collect(&:isbn).include?(request.isbn)}
has_many :import_request_transitions, autosave: false, dependent: :destroy
def state_machine
ImportRequestStateMachine.new(self, transition_class: ImportRequestTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def check_isbn
return if isbn.blank?
errors.add(:isbn) unless StdNum::ISBN.valid?(isbn)
end
def check_imported
if isbn.present?
lisbn = Lisbn.new(isbn)
if IsbnRecord.find_by(body: lisbn.isbn13)&.manifestations
errors.add(:isbn, I18n.t("import_request.isbn_taken"))
end
end
end
def import!
exceptions = [ ActiveRecord::RecordInvalid, NameError, URI::InvalidURIError ]
not_found_exceptions = []
not_found_exceptions << EnjuNdl::RecordNotFound if defined? EnjuNdl
not_found_exceptions << EnjuNii::RecordNotFound if defined? EnjuNii
not_found_exceptions << EnjuLoc::RecordNotFound if defined? EnjuLoc
begin
return nil unless Manifestation.respond_to?(:import_isbn)
unless manifestation
manifestation = Manifestation.import_isbn(isbn)
if manifestation
self.manifestation = manifestation
transition_to!(:completed)
manifestation.index
Sunspot.commit
else
transition_to!(:failed)
end
end
save
rescue *not_found_exceptions => e
transition_to!(:failed)
"record_not_found"
rescue *exceptions => e
transition_to!(:failed)
:error
end
end
end
# == Schema Information
#
# Table name: import_requests
#
# id :bigint not null, primary key
# isbn :string
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint
# user_id :bigint not null
#
# Indexes
#
# index_import_requests_on_isbn (isbn)
# index_import_requests_on_manifestation_id (manifestation_id)
# index_import_requests_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/item.rb | app/models/item.rb | class Item < ApplicationRecord
scope :available, -> { includes(:circulation_status).where.not("circulation_statuses.name" => "Removed") }
scope :removed, -> { includes(:circulation_status).where("circulation_statuses.name" => "Removed") }
scope :on_shelf, -> { available.includes(:shelf).references(:shelf).where.not(shelves: { name: "web" }) }
scope :on_web, -> { available.includes(:shelf).references(:shelf).where("shelves.name = ?", "web") }
scope :available_for, ->(user) {
unless user.try(:has_role?, "Librarian")
on_shelf
end
}
include EnjuLibrary::EnjuItem
include EnjuCirculation::EnjuItem
include EnjuInventory::EnjuItem
delegate :display_name, to: :shelf, prefix: true
has_many :owns, dependent: :destroy
has_many :agents, through: :owns
has_many :donates, dependent: :destroy
has_many :donors, through: :donates, source: :agent
has_one :resource_import_result
belongs_to :manifestation, touch: true
belongs_to :bookstore, optional: true
belongs_to :required_role, class_name: "Role"
belongs_to :budget_type, optional: true
has_one :accept, dependent: :destroy
has_one :withdraw, dependent: :destroy
has_many :item_custom_values, -> { joins(:item_custom_property).order(:position) }, inverse_of: :item, dependent: :destroy
belongs_to :shelf, counter_cache: true
accepts_nested_attributes_for :item_custom_values, reject_if: :all_blank
scope :accepted_between, lambda { |from, to| includes(:accept).where("items.created_at BETWEEN ? AND ?", Time.zone.parse(from).beginning_of_day, Time.zone.parse(to).end_of_day) }
validates :item_identifier, allow_blank: true, uniqueness: true,
format: { with: /\A[0-9A-Za-z_]+\Z/ }
validates :binding_item_identifier, allow_blank: true,
format: { with: /\A[0-9A-Za-z_]+\Z/ }
validates :url, url: true, allow_blank: true, length: { maximum: 255 }
validates :acquired_at, date: true, allow_blank: true
strip_attributes only: [ :item_identifier, :binding_item_identifier,
:call_number, :binding_call_number, :url ]
searchable do
text :item_identifier, :note, :title, :creator, :contributor, :publisher,
:binding_item_identifier
string :item_identifier, multiple: true do
[ item_identifier, binding_item_identifier ]
end
integer :required_role_id
integer :manifestation_id
integer :shelf_id
integer :agent_ids, multiple: true
time :created_at
time :updated_at
time :acquired_at
end
after_save do
manifestation.index
Sunspot.commit
end
after_destroy do
manifestation.index
Sunspot.commit
end
attr_accessor :library_id
paginates_per 10
def title
manifestation&.original_title
end
def creator
manifestation&.creator
end
def contributor
manifestation&.contributor
end
def publisher
manifestation&.publisher
end
def owned(agent)
owns.find_by(agent_id: agent.id)
end
def manifestation_url
Addressable::URI.parse("#{LibraryGroup.site_config.url}manifestations/#{manifestation.id}").normalize.to_s if manifestation
end
def removable?
if defined?(EnjuCirculation)
return false if circulation_status.name == "Removed"
return false if checkouts.exists?
true
else
true
end
end
def self.csv_header(role: "Guest")
Item.new.to_hash(role: role).keys
end
def to_hash(role: "Guest")
record = {
item_id: id,
item_identifier: item_identifier,
binding_item_identifier: binding_item_identifier,
call_number: call_number,
library: shelf&.library&.name,
shelf: shelf&.name,
item_note: note,
accepted_at: accept&.created_at,
acquired_at: acquired_at,
item_created_at: created_at,
item_updated_at: updated_at
}
if [ "Administrator", "Librarian" ].include?(role)
record.merge!({
bookstore: bookstore&.name,
budget_type: budget_type&.name,
item_required_role: required_role.name,
item_price: price,
memo: memo
})
ItemCustomProperty.order(:position).each do |custom_property|
custom_value = item_custom_values.find_by(item_custom_property: custom_property)
record[:"item:#{custom_property.name}"] = custom_value.try(:value)
end
if defined?(EnjuCirculation)
record.merge!({
use_restriction: use_restriction&.name,
circulation_status: circulation_status&.name,
checkout_type: checkout_type&.name,
total_checkouts: checkouts.count
})
end
end
record
end
end
# == Schema Information
#
# Table name: items
#
# id :bigint not null, primary key
# acquired_at :datetime
# binded_at :datetime
# binding_call_number :string
# binding_item_identifier :string
# call_number :string
# include_supplements :boolean default(FALSE), not null
# item_identifier :string
# lock_version :integer default(0), not null
# memo :text
# missing_since :date
# note :text
# price :integer
# required_score :integer default(0), not null
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# bookstore_id :bigint
# budget_type_id :bigint
# checkout_type_id :bigint default(1), not null
# circulation_status_id :bigint default(5), not null
# manifestation_id :bigint not null
# required_role_id :bigint default(1), not null
# shelf_id :bigint default(1), not null
#
# Indexes
#
# index_items_on_binding_item_identifier (binding_item_identifier)
# index_items_on_bookstore_id (bookstore_id)
# index_items_on_checkout_type_id (checkout_type_id)
# index_items_on_circulation_status_id (circulation_status_id)
# index_items_on_item_identifier (item_identifier) UNIQUE WHERE (((item_identifier)::text <> ''::text) AND (item_identifier IS NOT NULL))
# index_items_on_manifestation_id (manifestation_id)
# index_items_on_required_role_id (required_role_id)
# index_items_on_shelf_id (shelf_id)
#
# Foreign Keys
#
# fk_rails_... (manifestation_id => manifestations.id)
# fk_rails_... (required_role_id => roles.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/checkout_stat_has_user.rb | app/models/checkout_stat_has_user.rb | class CheckoutStatHasUser < ApplicationRecord
belongs_to :user_checkout_stat
belongs_to :user
validates :user_id, uniqueness: { scope: :user_checkout_stat_id }
paginates_per 10
end
# == Schema Information
#
# Table name: checkout_stat_has_users
#
# id :bigint not null, primary key
# checkouts_count :integer default(0), not null
# created_at :datetime not null
# updated_at :datetime not null
# user_checkout_stat_id :bigint not null
# user_id :bigint not null
#
# Indexes
#
# index_checkout_stat_has_users_on_user_checkout_stat_id (user_checkout_stat_id)
# index_checkout_stat_has_users_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_checkout_stat_id => user_checkout_stats.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/basket.rb | app/models/basket.rb | class Basket < ApplicationRecord
include EnjuCirculation::EnjuBasket
default_scope { order("baskets.id DESC") }
scope :will_expire, lambda { |date| where("created_at < ?", date) }
belongs_to :user, optional: true
has_many :accepts, dependent: :destroy
has_many :withdraws, dependent: :destroy
# 貸出完了後にかごのユーザidは破棄する
validates :user, presence: { on: :create }
validate :check_suspended
attr_accessor :user_number
def check_suspended
if user
errors.add(:base, I18n.t("basket.this_account_is_suspended")) if user.locked_at
else
errors.add(:base, I18n.t("user.not_found"))
end
end
def self.expire
Basket.will_expire(Time.zone.now.beginning_of_day).destroy_all
logger.info "#{Time.zone.now} baskets expired!"
end
end
# == Schema Information
#
# Table name: baskets
#
# id :bigint not null, primary key
# lock_version :integer default(0), not null
# note :text
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint
#
# Indexes
#
# index_baskets_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/circulation_status.rb | app/models/circulation_status.rb | class CirculationStatus < ApplicationRecord
include MasterModel
validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ }
default_scope { order("circulation_statuses.position") }
scope :available_for_checkout, -> { where(name: "Available On Shelf") }
has_many :items, dependent: :restrict_with_exception
private
def valid_name?
true
end
end
# == Schema Information
#
# Table name: circulation_statuses
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_circulation_statuses_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/produce.rb | app/models/produce.rb | class Produce < ApplicationRecord
belongs_to :agent
belongs_to :manifestation, touch: true
belongs_to :produce_type, optional: true
delegate :original_title, to: :manifestation, prefix: true
validates :manifestation_id, uniqueness: { scope: :agent_id }
after_destroy :reindex
after_save :reindex
acts_as_list scope: :manifestation
def reindex
agent.try(:index)
manifestation.try(:index)
end
end
# == Schema Information
#
# Table name: produces
#
# id :bigint not null, primary key
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# agent_id :bigint not null
# manifestation_id :bigint not null
# produce_type_id :bigint
#
# Indexes
#
# index_produces_on_agent_id (agent_id)
# index_produces_on_manifestation_id_and_agent_id (manifestation_id,agent_id) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/message_transition.rb | app/models/message_transition.rb | class MessageTransition < ApplicationRecord
belongs_to :message, inverse_of: :message_transitions
end
# == Schema Information
#
# Table name: message_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# message_id :bigint
#
# Indexes
#
# index_message_transitions_on_message_id (message_id)
# index_message_transitions_on_sort_key_and_message_id (sort_key,message_id) UNIQUE
# index_message_transitions_parent_most_recent (message_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/checkout.rb | app/models/checkout.rb | class Checkout < ApplicationRecord
scope :not_returned, -> { where(checkin_id: nil) }
scope :returned, -> { where.not(checkin_id: nil) }
scope :overdue, lambda { |date| where("checkin_id IS NULL AND due_date < ?", date) }
scope :due_date_on, lambda { |date| where(checkin_id: nil, due_date: date.beginning_of_day .. date.end_of_day) }
scope :completed, lambda { |start_date, end_date| where("checkouts.created_at >= ? AND checkouts.created_at < ?", start_date, end_date) }
scope :on, lambda { |date| where("created_at >= ? AND created_at < ?", date.beginning_of_day, date.tomorrow.beginning_of_day) }
belongs_to :user, optional: true
delegate :username, :user_number, to: :user, prefix: true
belongs_to :item, touch: true
belongs_to :checkin, optional: true
belongs_to :librarian, class_name: "User"
belongs_to :basket
belongs_to :shelf, optional: true
belongs_to :library, optional: true
# TODO: 貸出履歴を保存しない場合は、ユーザ名を削除する
# validates :user, :item, :basket, presence: true
validates :due_date, date: true, presence: true
validates :item_id, uniqueness: { scope: [ :basket_id, :user_id ] }
validate :is_not_checked?, on: :create
validate :renewable?, on: :update
before_update :set_new_due_date
searchable do
string :username do
user.try(:username)
end
string :user_number do
user.try(:profile).try(:user_number)
end
string :item_identifier do
item.try(:item_identifier)
end
time :due_date
time :created_at
time :checked_in_at do
checkin.try(:created_at)
end
boolean :reserved do
reserved?
end
end
attr_accessor :operator
paginates_per 10
def is_not_checked?
checkout = Checkout.not_returned.where(item_id: item_id)
unless checkout.empty?
errors.add(:base, I18n.t("activerecord.errors.messages.checkin.already_checked_out"))
end
end
def renewable?
return nil if checkin
messages = []
if !operator && overdue?
messages << I18n.t("checkout.you_have_overdue_item")
end
if !operator && reserved?
messages << I18n.t("checkout.this_item_is_reserved")
end
if !operator && over_checkout_renewal_limit?
messages << I18n.t("checkout.excessed_renewal_limit")
end
if messages.empty?
true
else
messages.each do |message|
errors.add(:base, message)
end
false
end
end
def reserved?
return true if item.try(:reserved?)
false
end
def over_checkout_renewal_limit?
return nil unless item.checkout_status(user)
true if item.checkout_status(user).checkout_renewal_limit < checkout_renewal_count
end
def overdue?
return false unless due_date
if Time.zone.now > due_date.tomorrow.beginning_of_day
true
else
false
end
end
def is_today_due_date?
if Time.zone.now.beginning_of_day == due_date.beginning_of_day
true
else
false
end
end
def set_new_due_date
self.due_date = due_date.try(:end_of_day)
end
def get_new_due_date
return nil unless user
if item
if checkout_renewal_count <= item.checkout_status(user).checkout_renewal_limit
new_due_date = Time.zone.now.advance(days: item.checkout_status(user).checkout_period).beginning_of_day
else
new_due_date = due_date
end
end
end
def send_due_date_notification
mailer = CheckoutMailer.due_date(self)
mailer.deliver_later
Message.create!(
subject: mailer.subject,
sender: User.find(1),
recipient: user.username,
body: mailer.body.to_s
)
end
def send_overdue_notification
mailer = CheckoutMailer.overdue(self)
mailer.deliver_later
Message.create!(
subject: mailer.subject,
sender: User.find(1),
recipient: user.username,
body: mailer.body.to_s
)
end
def self.manifestations_count(start_date, end_date, manifestation)
where(
arel_table[:created_at].gteq start_date
).where(
arel_table[:created_at].lt end_date
)
.where(
item_id: manifestation.items.pluck("items.id")
).count
end
def self.send_due_date_notification
count = 0
User.find_each do |user|
# 未来の日時を指定する
user.checkouts.due_date_on(user.profile.user_group.number_of_day_to_notify_due_date.days.from_now.beginning_of_day).each_with_index do |checkout, i|
checkout.send_due_date_notification
count += 1
end
end
count
end
def self.send_overdue_notification
count = 0
User.find_each do |user|
user.profile.user_group.number_of_time_to_notify_overdue.times do |i|
user.checkouts.due_date_on((user.profile.user_group.number_of_day_to_notify_overdue * (i + 1)).days.ago.beginning_of_day).each_with_index do |checkout, j|
checkout.send_overdue_notification
count += 1
end
end
end
count
end
def self.remove_all_history(user)
user.checkouts.returned.update_all(user_id: nil)
end
end
# == Schema Information
#
# Table name: checkouts
#
# id :bigint not null, primary key
# checkout_renewal_count :integer default(0), not null
# due_date :datetime
# lock_version :integer default(0), not null
# created_at :datetime not null
# updated_at :datetime not null
# basket_id :bigint
# checkin_id :bigint
# item_id :bigint not null
# librarian_id :bigint
# library_id :bigint
# shelf_id :bigint
# user_id :bigint
#
# Indexes
#
# index_checkouts_on_basket_id (basket_id)
# index_checkouts_on_checkin_id (checkin_id)
# index_checkouts_on_item_id (item_id)
# index_checkouts_on_item_id_and_basket_id_and_user_id (item_id,basket_id,user_id) UNIQUE
# index_checkouts_on_librarian_id (librarian_id)
# index_checkouts_on_library_id (library_id)
# index_checkouts_on_shelf_id (shelf_id)
# index_checkouts_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (checkin_id => checkins.id)
# fk_rails_... (item_id => items.id)
# fk_rails_... (library_id => libraries.id)
# fk_rails_... (shelf_id => shelves.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/demand.rb | app/models/demand.rb | class Demand < ApplicationRecord
belongs_to :user
belongs_to :item
belongs_to :message
end
# == Schema Information
#
# Table name: demands
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# item_id :bigint
# message_id :bigint
# user_id :bigint not null
#
# Indexes
#
# index_demands_on_item_id (item_id)
# index_demands_on_message_id (message_id)
# index_demands_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (item_id => items.id)
# fk_rails_... (message_id => messages.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/agent_import_file_state_machine.rb | app/models/agent_import_file_state_machine.rb | class AgentImportFileStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
state :failed
transition from: :pending, to: [ :started, :failed ]
transition from: :started, to: [ :completed, :failed ]
after_transition(from: :pending, to: :started) do |agent_import_file|
agent_import_file.update_column(:executed_at, Time.zone.now)
end
before_transition(from: :started, to: :completed) do |agent_import_file|
agent_import_file.error_message = nil
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/bookmark_stat_state_machine.rb | app/models/bookmark_stat_state_machine.rb | class BookmarkStatStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
transition from: :pending, to: :started
transition from: :started, to: :completed
after_transition(to: :started) do |bookmark_stat|
bookmark_stat.calculate_count!
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/participate.rb | app/models/participate.rb | class Participate < ApplicationRecord
belongs_to :agent
belongs_to :event
validates :agent_id, uniqueness: { scope: :event_id }
acts_as_list scope: :event_id
paginates_per 10
end
# == Schema Information
#
# Table name: participates
#
# id :bigint not null, primary key
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# agent_id :bigint not null
# event_id :bigint not null
#
# Indexes
#
# index_participates_on_agent_id (agent_id)
# index_participates_on_event_id (event_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation_relationship_type.rb | app/models/manifestation_relationship_type.rb | class ManifestationRelationshipType < ApplicationRecord
include MasterModel
default_scope { order("manifestation_relationship_types.position") }
has_many :manifestation_relationships, dependent: :destroy
end
# == Schema Information
#
# Table name: manifestation_relationship_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_manifestation_relationship_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/subject_type.rb | app/models/subject_type.rb | class SubjectType < ApplicationRecord
include MasterModel
has_many :subjects, dependent: :restrict_with_exception
validates :name, format: { with: /\A[0-9A-Za-z][0-9a-z_\-]*[0-9a-z]\Z/ }
end
# == Schema Information
#
# Table name: subject_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_subject_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/request_type.rb | app/models/request_type.rb | class RequestType < ApplicationRecord
include MasterModel
validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ }
private
def valid_name?
true
end
end
# == Schema Information
#
# Table name: request_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_request_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/use_restriction.rb | app/models/use_restriction.rb | class UseRestriction < ApplicationRecord
include MasterModel
validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ }
scope :available, -> { where(name: [ "Not For Loan", "Limited Circulation, Normal Loan Period" ]) }
has_many :item_has_use_restrictions, dependent: :destroy
has_many :items, through: :item_has_use_restrictions
private
def valid_name?
true
end
end
# == Schema Information
#
# Table name: use_restrictions
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_use_restrictions_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resource_import_file.rb | app/models/resource_import_file.rb | class ResourceImportFile < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: ResourceImportFileTransition,
initial_state: ResourceImportFileStateMachine.initial_state
]
include ImportFile
default_scope { order("resource_import_files.id DESC") }
scope :not_imported, -> { in_state(:pending) }
scope :stucked, -> { in_state(:pending).where("resource_import_files.created_at < ?", 1.hour.ago) }
has_one_attached :attachment
validates :default_shelf_id, presence: true, if: proc { |model| model.edit_mode == "create" }
belongs_to :user
belongs_to :default_shelf, class_name: "Shelf", optional: true
has_many :resource_import_results, dependent: :destroy
has_many :resource_import_file_transitions, autosave: false, dependent: :destroy
attr_accessor :mode, :library_id
def state_machine
ResourceImportFileStateMachine.new(self, transition_class: ResourceImportFileTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def import_start
case edit_mode
when "create"
import
when "update"
modify
when "destroy"
remove
when "update_relationship"
update_relationship
else
import
end
end
def import
transition_to!(:started)
num = {
manifestation_imported: 0,
item_imported: 0,
manifestation_found: 0,
item_found: 0,
failed: 0
}
rows = open_import_file(create_import_temp_file(attachment))
rows.shift
# if [field['manifestation_id'], field['manifestation_identifier'], field['isbn'], field['original_title']].reject{|f|
# f.to_s.strip == ''
# }.empty?
# raise "You should specify isbn or original_title in the first line"
# end
row_num = 1
ResourceImportResult.create!(resource_import_file_id: id, body: (%w[ imported_manifestation_id imported_item_id ] + rows.headers).join("\t"))
rows.each do |row|
row_num += 1
import_result = ResourceImportResult.new(resource_import_file_id: id)
if row["dummy"].to_s.strip.present?
import_result.error_message = "line #{row_num}: #{I18n.t('import.dummy')}"
import_result.body = ([ nil, nil ] + row.fields).join("\t")
import_result.save!
next
end
item_identifier = row["item_identifier"].to_s.strip
item = Item.find_by(item_identifier: item_identifier)
if item
import_result.item = item
import_result.manifestation = item.manifestation
import_result.error_message = "line #{row_num}: #{I18n.t('import.item_found')}"
import_result.body = ([ item.manifestation.id, item.id ] + row.fields).join("\t")
import_result.save!
num[:item_found] += 1
next
end
if row["manifestation_identifier"].present?
manifestation = Manifestation.find_by(manifestation_identifier: row["manifestation_identifier"].to_s.strip)
end
unless manifestation
if row["manifestation_id"].present?
manifestation = Manifestation.find_by(id: row["manifestation_id"].to_s.strip)
end
end
unless manifestation
if row["iss_itemno"].present?
iss_itemno = URI.parse(row["iss_itemno"]).path.gsub(/^\//, "")
manifestation = NdlBibIdRecord.find_by(body: iss_itemno).manifestation
end
end
unless manifestation
if row["doi"].present?
doi = URI.parse(row["doi"].downcase).path.gsub(/^\//, "")
manifestation = DoiRecord.find_by(body: doi)&.manifestation
end
end
unless manifestation
if row["jpno"].present?
jpno = row["jpno"].to_s.strip
manifestation = JpnoRecord.find_by(body: jpno)&.manifestation
end
end
unless manifestation
if row["ncid"].present?
ncid = row["ncid"].to_s.strip
manifestation = NcidRecord.find_by(body: ncid)&.manifestation
end
end
unless manifestation
if row["lccn"].present?
lccn = row["lccn"].to_s.strip
manifestation = LccnRecord.find_by(body: lccn).manifestation
end
end
unless manifestation
if row["isbn"].present?
row["isbn"].to_s.split("//").each do |isbn|
m = IsbnRecord.find_by(body: Lisbn.new(isbn).isbn13)&.manifestations&.first
if m
if m.series_statements.exists?
manifestation = m
end
else
import_result.error_message = "line #{row_num}: #{I18n.t('import.isbn_invalid')}"
end
end
end
end
if manifestation
import_result.error_message = "line #{row_num}: #{I18n.t('import.manifestation_found')}"
num[:manifestation_found] += 1
end
if row["original_title"].blank?
unless manifestation
begin
if row["jpno"].present?
manifestation = Manifestation.import_from_ndl_search(jpno: row["jpno"])
end
if row["ncid"].present?
manifestation = Manifestation.import_from_cinii_books(ncid: row["ncid"])
end
row["isbn"].to_s.split("//").each do |isbn|
lisbn = Lisbn.new(isbn)
manifestation = Manifestation.import_from_ndl_search(isbn: lisbn.isbn13) if lisbn.isbn13
end
if manifestation
num[:manifestation_imported] += 1
end
rescue EnjuNdl::InvalidIsbn
manifestation = nil
import_result.error_message = "line #{row_num}: #{I18n.t('import.isbn_invalid')}"
rescue EnjuNdl::RecordNotFound, EnjuNii::RecordNotFound
manifestation = nil
import_result.error_message = "line #{row_num}: #{I18n.t('import.isbn_record_not_found')}"
end
end
if manifestation.nil? && row["ndl_bib_id"]
manifestation = Manifestation.import_ndl_bib_id("R100000002-I#{row['ndl_bib_id']}")
if manifestation
num[:manifestation_imported] += 1
end
end
end
unless manifestation
manifestation = fetch(row)
num[:manifestation_imported] += 1 if manifestation
end
import_result.manifestation = manifestation
if manifestation
manifestation.reload
ResourceImportFile.import_manifestation_custom_value(row, manifestation).each do |value|
value.update!(manifestation: manifestation)
end
item = nil
if item_identifier.present? || row["shelf"].present? || row["call_number"].present?
item = create_item(row, manifestation)
else
if manifestation.fulltext_content?
item = create_item(row, manifestation)
item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf")
begin
item.acquired_at = Time.zone.parse(row["acquired_at"].to_s.strip)
rescue ArgumentError
end
end
num[:failed] += 1
end
if item
ResourceImportFile.import_item_custom_value(row, item).each do |value|
value.update!(item: item)
end
import_result.item = item
end
else
num[:failed] += 1
end
import_result.body = ([ manifestation.try(:id), item.try(:id) ] + row.fields).join("\t")
import_result.save!
num[:item_imported] += 1 if import_result.item
end
Sunspot.commit
rows.close
transition_to!(:completed)
mailer = ResourceImportMailer.completed(self)
send_message(mailer)
Rails.cache.write("manifestation_search_total", Manifestation.search.total)
num
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = ResourceImportMailer.failed(self)
send_message(mailer)
raise e
end
def self.import_work(title, agents, options = { edit_mode: "create" })
work = Manifestation.new(title)
work.save
work.creators = agents.uniq unless agents.empty?
work
end
def self.import_expression(work, agents, options = { edit_mode: "create" })
expression = work
expression.save
expression.contributors = agents.uniq unless agents.empty?
expression
end
def self.import_manifestation(expression, agents, options = {}, edit_options = { edit_mode: "create" })
manifestation = expression
manifestation.during_import = true
manifestation.reload
manifestation.update!(options)
manifestation.publishers = agents.uniq unless agents.empty?
manifestation.reload
manifestation
end
def import_marc(marc_type)
file = attachment.download
case marc_type
when "marcxml"
reader = MARC::XMLReader.new(file)
else
reader = MARC::Reader.new(file)
end
file.close
# when 'marc_xml_url'
# url = URI(params[:marc_xml_url])
# xml = open(url).read
# reader = MARC::XMLReader.new(StringIO.new(xml))
# end
# TODO
reader.each do |record|
manifestation = Manifestation.new(original_title: expression.original_title)
manifestation.carrier_type = CarrierType.find(1)
manifestation.frequency = Frequency.find(1)
manifestation.language = Language.find(1)
manifestation.save
full_name = record["700"]["a"]
publisher = Agent.find_by(full_name: record["700"]["a"])
unless publisher
publisher = Agent.new(full_name: full_name)
publisher.save
end
manifestation.publishers << publisher
end
end
def self.import
ResourceImportFile.not_imported.each do |file|
file.import_start
end
rescue StandardError
Rails.logger.info "#{Time.zone.now} importing resources failed!"
end
# def import_jpmarc
# marc = NKF::nkf('-wc', self.db_file.data)
# marc.split("\r\n").each do |record|
# end
# end
def modify
transition_to!(:started)
rows = open_import_file(create_import_temp_file(attachment))
rows.shift
row_num = 1
ResourceImportResult.create!(resource_import_file_id: id, body: rows.headers.join("\t"))
rows.each do |row|
row_num += 1
import_result = ResourceImportResult.create!(resource_import_file_id: id, body: row.fields.join("\t"))
item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) if row["item_identifier"].to_s.strip.present?
unless item
item = Item.find_by(id: row["item_id"].to_s.strip) if row["item_id"].to_s.strip.present?
end
if item
if item.manifestation
fetch(row, edit_mode: "update")
item = update_item(item, row)
end
ResourceImportFile.import_item_custom_value(row, item).each do |value|
value.update!(item: item)
end
ResourceImportFile.import_manifestation_custom_value(row, item.manifestation).each do |value|
value.update!(manifestation: item.manifestation)
end
item.manifestation.reload
item.save!
import_result.item = item
else
manifestation_identifier = row["manifestation_identifier"].to_s.strip
manifestation = Manifestation.find_by(manifestation_identifier: manifestation_identifier) if manifestation_identifier.present?
manifestation ||= Manifestation.find_by(id: row["manifestation_id"])
if manifestation
fetch(row, edit_mode: "update")
ResourceImportFile.import_manifestation_custom_value(row, manifestation).each do |value|
value.update!(manifestation: manifestation)
end
import_result.manifestation = manifestation
end
end
import_result.save!
end
transition_to!(:completed)
mailer = ResourceImportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = ResourceImportMailer.failed(self)
send_message(mailer)
raise e
end
def remove
transition_to!(:started)
rows = open_import_file(create_import_temp_file(attachment))
rows.shift
row_num = 1
rows.each do |row|
row_num += 1
item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) if row["item_identifier"].to_s.strip.present?
unless item
item = Item.find_by(id: row["item_id"].to_s.strip) if row["item_id"].to_s.strip.present?
end
if item
item.destroy if item.removable?
end
end
transition_to!(:completed)
mailer = ResourceImportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = ResourceImportMailer.failed(self)
send_message(mailer)
raise e
end
def update_relationship
transition_to!(:started)
rows = open_import_file(create_import_temp_file(attachment))
rows.shift
row_num = 1
rows.each do |row|
item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip) if row["item_identifier"].to_s.strip.present?
unless item
item = Item.find_by(id: row["item_id"].to_s.strip) if row["item_id"].to_s.strip.present?
end
manifestation_identifier = row["manifestation_identifier"].to_s.strip
manifestation = Manifestation.find_by(manifestation_identifier: manifestation_identifier)
manifestation ||= Manifestation.find_by(id: row["manifestation_id"].to_s.strip)
if item && manifestation
item.manifestation = manifestation
item.save!
end
import_result = ResourceImportResult.create!(resource_import_file_id: id, body: row.fields.join("\t"))
import_result.item = item
import_result.manifestation = manifestation
import_result.save!
row_num += 1
end
transition_to!(:completed)
mailer = ResourceImportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = ResourceImportMailer.failed(self)
send_message(mailer)
raise e
end
private
def open_import_file(tempfile)
file = CSV.open(tempfile, col_sep: "\t")
header_columns = %w[
original_title manifestation_identifier item_identifier shelf note
title_transcription title_alternative title_alternative_transcription
serial manifestation_id publication_place carrier_type
series_statement_identifier series_original_title series_creator_string
series_title_transcription series_volume_number_string
series_title_subseries series_title_subseries_transcription
creator creator_transcription publisher
publisher_transcription pub_date date_of_publication year_of_publication
creator creator_transcription
contributor contributor_transcription abstract description access_address
volume_number volume_number_string issue_number issue_number_string
edition edition_string serial_number isbn issn manifestation_price
width height depth number_of_pages jpno lccn budget_type bookstore
language fulltext_content manifestation_required_role doi content_type
frequency extent start_page end_page dimensions manifestation_memo
ncid
ndl_bib_id
statement_of_responsibility acquired_at call_number circulation_status
binding_item_identifier binding_call_number binded_at item_price
use_restriction include_supplements item_note item_url item_memo
item_required_role
dummy
]
header_columns += ManifestationCustomProperty.order(:position).pluck(:name).map { |c| "manifestation:#{c}" }
header_columns += ItemCustomProperty.order(:position).pluck(:name).map { |c| "item:#{c}" }
if defined?(EnjuSubject)
header_columns += ClassificationType.order(:position).pluck(:name).map { |c| "classification:#{c}" }
header_columns += SubjectHeadingType.order(:position).pluck(:name).map { |s| "subject:#{s}" }
end
header = file.first
ignored_columns = header - header_columns
unless ignored_columns.empty?
self.error_message = I18n.t("import.following_column_were_ignored", column: ignored_columns.join(", "))
save!
end
rows = CSV.open(tempfile, headers: header, col_sep: "\t")
# ResourceImportResult.create!(resource_import_file_id: id, body: header.join("\t"))
tempfile.close(true)
file.close
rows
end
def import_subject(row)
subjects = []
SubjectHeadingType.order(:position).pluck(:name).map { |s| "subject:#{s}" }.each do |column_name|
type = column_name.split(":").last
subject_list = row[column_name].to_s.split("//")
subject_list.map { |value|
subject_heading_type = SubjectHeadingType.find_by(name: type)
next unless subject_heading_type
subject = Subject.new(term: value)
subject.subject_heading_type = subject_heading_type
# TODO: Subject typeの設定
subject.subject_type = SubjectType.find_by(name: "concept")
subject.save!
subjects << subject
}
end
subjects
end
def import_classification(row)
classifications = []
ClassificationType.order(:position).pluck(:name).map { |c| "classification:#{c}" }.each do |column_name|
type = column_name.split(":").last
classification_list = row[column_name].to_s.split("//")
classification_list.map { |value|
classification_type = ClassificationType.find_by(name: type)
next unless classification_type
classification = Classification.new(category: value)
classification.classification_type = classification_type
classification.save!
classifications << classification
}
end
classifications
end
def create_item(row, manifestation)
shelf = Shelf.find_by(name: row["shelf"].to_s.strip)
shelf ||= default_shelf || Shelf.web
bookstore = Bookstore.find_by(name: row["bookstore"].to_s.strip)
budget_type = BudgetType.find_by(name: row["budget_type"].to_s.strip)
acquired_at = Time.zone.parse(row["acquired_at"]) rescue nil
binded_at = Time.zone.parse(row["binded_at"]) rescue nil
item = Item.new(
manifestation_id: manifestation.id,
item_identifier: row["item_identifier"],
price: row["item_price"],
call_number: row["call_number"].to_s.strip,
acquired_at: acquired_at,
binding_item_identifier: row["binding_item_identifier"],
binding_call_number: row["binding_call_number"],
binded_at: binded_at,
url: row["item_url"],
note: row["item_note"].try(:gsub, /\\n/, "\n"),
memo: row["item_memo"].try(:gsub, /\\n/, "\n")
)
manifestation.items << item
if defined?(EnjuCirculation)
circulation_status = CirculationStatus.find_by(name: row["circulation_status"].to_s.strip) || CirculationStatus.find_by(name: "In Process")
item.circulation_status = circulation_status
use_restriction = UseRestriction.find_by(name: row["use_restriction"].to_s.strip)
use_restriction ||= UseRestriction.find_by(name: "Not For Loan")
item.use_restriction = use_restriction
end
item.bookstore = bookstore
item.budget_type = budget_type
item.shelf = shelf
item.shelf = Shelf.web unless item.shelf
if %w[t true].include?(row["include_supplements"].to_s.downcase.strip)
item.include_supplements = true
end
item.save!
item
end
def update_item(item, row)
shelf = Shelf.find_by(name: row["shelf"].to_s.strip)
bookstore = Bookstore.find_by(name: row["bookstore"])
required_role = Role.find_by(name: row["item_required_role"])
item.shelf = shelf if shelf
item.bookstore = bookstore if bookstore
item.required_role = required_role if required_role
acquired_at = Time.zone.parse(row["acquired_at"]) rescue nil
binded_at = Time.zone.parse(row["binded_at"]) rescue nil
item.acquired_at = acquired_at if acquired_at
item.binded_at = binded_at if binded_at
if defined?(EnjuCirculation)
circulation_status = CirculationStatus.find_by(name: row["circulation_status"])
checkout_type = CheckoutType.find_by(name: row["checkout_type"])
use_restriction = UseRestriction.find_by(name: row["use_restriction"].to_s.strip)
item.circulation_status = circulation_status if circulation_status
item.checkout_type = checkout_type if checkout_type
item.use_restriction = use_restriction if use_restriction
end
item_columns = %w[
call_number
binding_item_identifier binding_call_number binded_at
]
item_columns.each do |column|
if row[column].present?
item.assign_attributes(:"#{column}" => row[column])
end
end
item.price = row["item_price"] if row["item_price"].present?
item.note = row["item_note"].try(:gsub, /\\n/, "\n") if row["item_note"].present?
item.memo = row["item_memo"].try(:gsub, /\\n/, "\n") if row["item_memo"].present?
item.url = row["item_url"] if row["item_url"].present?
if row["include_supplements"]
if %w[t true].include?(row["include_supplements"].downcase.strip)
item.include_supplements = true
elsif item.include_supplements
item.include_supplements = false
end
end
item
end
def fetch(row, options = { edit_mode: "create" })
manifestation = nil
item = nil
if options[:edit_mode] == "update"
if row["item_identifier"].to_s.strip.present?
item = Item.find_by(item_identifier: row["item_identifier"].to_s.strip)
end
if row["item_id"].to_s.strip.present?
item = Item.find_by(id: row["item_id"].to_s.strip)
end
manifestation = item.manifestation if item
unless manifestation
manifestation_identifier = row["manifestation_identifier"].to_s.strip
manifestation = Manifestation.find_by(manifestation_identifier: manifestation_identifier) if manifestation_identifier
manifestation ||= Manifestation.find_by(id: row["manifestation_id"])
end
end
title = {}
title[:original_title] = row["original_title"].to_s.strip
title[:title_transcription] = row["title_transcription"].to_s.strip
title[:title_alternative] = row["title_alternative"].to_s.strip
title[:title_alternative_transcription] = row["title_alternative_transcription"].to_s.strip
if options[:edit_mode] == "update"
title[:original_title] = manifestation.original_title if row["original_title"].to_s.strip.blank?
title[:title_transcription] = manifestation.title_transcription if row["title_transcription"].to_s.strip.blank?
title[:title_alternative] = manifestation.title_alternative if row["title_alternative"].to_s.strip.blank?
title[:title_alternative_transcription] = manifestation.title_alternative_transcription if row["title_alternative_transcription"].to_s.strip.blank?
end
# title[:title_transcription_alternative] = row['title_transcription_alternative']
if title[:original_title].blank? && options[:edit_mode] == "create"
return nil
end
# TODO: 小数点以下の表現
language = Language.find_by(name: row["language"].to_s.strip.camelize) || Language.find_by(iso_639_2: row["language"].to_s.strip.downcase) || Language.find_by(iso_639_1: row["language"].to_s.strip.downcase)
carrier_type = CarrierType.find_by(name: row["carrier_type"].to_s.strip)
content_type = ContentType.find_by(name: row["content_type"].to_s.strip)
frequency = Frequency.find_by(name: row["frequency"].to_s.strip)
fulltext_content = serial = nil
if %w[t true].include?(row["fulltext_content"].to_s.downcase.strip)
fulltext_content = true
end
if %w[t true].include?(row["serial"].to_s.downcase.strip)
serial = true
end
creators = row["creator"].to_s.split("//")
creator_transcriptions = row["creator_transcription"].to_s.split("//")
creators_list = creators.zip(creator_transcriptions).map { |f, t| { full_name: f.to_s.strip, full_name_transcription: t.to_s.strip } }
contributors = row["contributor"].to_s.split("//")
contributor_transcriptions = row["contributor_transcription"].to_s.split("//")
contributors_list = contributors.zip(contributor_transcriptions).map { |f, t| { full_name: f.to_s.strip, full_name_transcription: t.to_s.strip } }
publishers = row["publisher"].to_s.split("//")
publisher_transcriptions = row["publisher_transcription"].to_s.split("//")
publishers_list = publishers.zip(publisher_transcriptions).map { |f, t| { full_name: f.to_s.strip, full_name_transcription: t.to_s.strip } }
ResourceImportFile.transaction do
creator_agents = Agent.import_agents(creators_list)
contributor_agents = Agent.import_agents(contributors_list)
publisher_agents = Agent.import_agents(publishers_list)
subjects = import_subject(row) if defined?(EnjuSubject)
case options[:edit_mode]
when "create"
work = self.class.import_work(title, creator_agents, options)
if defined?(EnjuSubject)
work.subjects = subjects.uniq unless subjects.empty?
end
expression = self.class.import_expression(work, contributor_agents)
when "update"
expression = manifestation
work = expression
work.creators = creator_agents.uniq unless creator_agents.empty?
expression.contributors = contributor_agents.uniq unless contributor_agents.empty?
if defined?(EnjuSubject)
work.subjects = subjects.uniq unless subjects.empty?
end
end
attributes = {
original_title: title[:original_title],
title_transcription: title[:title_transcription],
title_alternative: title[:title_alternative],
title_alternative_transcription: title[:title_alternative_transcription],
pub_date: row["pub_date"],
date_of_publication: row["date_of_publication"],
year_of_publication: row["year_of_publication"],
volume_number: row["volume_number"],
volume_number_string: row["volume_number_string"],
issue_number: row["issue_number"],
issue_number_string: row["issue_number_string"],
serial_number: row["serial_number"],
edition: row["edition"],
edition_string: row["edition_string"],
width: row["width"],
depth: row["depth"],
height: row["height"],
price: row["manifestation_price"],
abstract: row["abstract"].try(:gsub, /\\n/, "\n"),
description: row["description"].try(:gsub, /\\n/, "\n"),
# :description_transcription => row['description_transcription'],
note: row["note"].try(:gsub, /\\n/, "\n"),
memo: row["manifestation_memo"].try(:gsub, /\\n/, "\n"),
statement_of_responsibility: row["statement_of_responsibility"],
access_address: row["access_address"],
manifestation_identifier: row["manifestation_identifier"],
publication_place: row["publication_place"],
extent: row["extent"],
dimensions: row["dimensions"],
start_page: row["start_page"],
end_page: row["end_page"],
}.delete_if { |_key, value| value.nil? }
manifestation = self.class.import_manifestation(expression, publisher_agents, attributes,
{
edit_mode: options[:edit_mode]
})
required_role = Role.find_by(name: row["manifestation_required_role"].to_s.strip.camelize)
if required_role && row["manifestation_required_role"].present?
manifestation.required_role = required_role
else
manifestation.required_role = Role.find_by(name: "Guest") unless manifestation.required_role
end
if language && row["language"].present?
manifestation.language = language
else
manifestation.language = Language.find_by(name: "unknown") unless manifestation.language
end
manifestation.carrier_type = carrier_type if carrier_type
manifestation.manifestation_content_type = content_type if content_type
manifestation.frequency = frequency if frequency
# manifestation.start_page = row[:start_page].to_i if row[:start_page]
# manifestation.end_page = row[:end_page].to_i if row[:end_page]
manifestation.serial = serial if row["serial"]
manifestation.fulltext_content = fulltext_content if row["fulltext_content"]
if row["series_original_title"].to_s.strip.present?
Manifestation.transaction do
if manifestation.series_statements.exists?
manifestation.series_statements.delete_all
end
if row["series_original_title"]
series_statement = SeriesStatement.new(
original_title: row["series_original_title"],
title_transcription: row["series_title_transcription"],
title_subseries: row["series_title_subseries"],
title_subseries_transcription: row["series_title_subseries_transcription"],
volume_number_string: row["series_volume_number_string"],
creator_string: row["series_creator_string"]
)
series_statement.manifestation = manifestation
series_statement.save!
end
end
end
manifestation.doi_record = set_doi(row)
manifestation.create_jpno_record(body: row["jpno"]) if row["jpno"].present?
manifestation.create_ncid_record(body: row["ncid"]) if row["ncid"].present?
if row["isbn"].present?
row["isbn"].to_s.split("//").each do |isbn|
lisbn = Lisbn.new(isbn)
manifestation.isbn_records.find_or_create_by(body: lisbn.isbn13) if lisbn.isbn13
end
end
if row["issn"].present?
row["issn"].to_s.split("//").each do |issn|
manifestation.issn_records.find_or_create_by(body: issn) if issn.present?
end
end
identifiers = set_identifier(row)
if manifestation.save
Manifestation.transaction do
if options[:edit_mode] == "update"
unless identifiers.empty?
identifiers.each do |v|
v.manifestation = manifestation
v.save
end
end
else
manifestation.identifiers << identifiers
end
end
if defined?(EnjuSubject)
classifications = import_classification(row)
if classifications.present?
manifestation.classifications = classifications
end
end
end
manifestation.save!
if options[:edit_mode] == "create"
manifestation.set_agent_role_type(creators_list)
manifestation.set_agent_role_type(contributors_list, scope: :contributor)
manifestation.set_agent_role_type(publishers_list, scope: :publisher)
end
end
manifestation
end
def set_identifier(row)
identifiers = []
%w[isbn issn jpno ncid lccn iss_itemno].each do |id_type|
next unless row[id_type.to_s].present?
row[id_type].split(/\/\//).each do |identifier_s|
import_id = Identifier.new(body: identifier_s)
identifier_type = IdentifierType.find_or_create_by!(name: id_type)
import_id.identifier_type = identifier_type
identifiers << import_id if import_id.valid?
end
end
identifiers
end
def set_doi(row)
return if row["doi"].blank?
doi = URI.parse(row["doi"].downcase).path.gsub(/^\//, "")
doi_record = DoiRecord.new(body: doi)
doi_record
end
def self.import_manifestation_custom_value(row, manifestation)
values = []
ManifestationCustomProperty.order(:position).pluck(:name).map { |c| "manifestation:#{c}" }.each do |column_name|
value = nil
property = column_name.split(":").last
next if row[column_name].blank?
if manifestation
value = manifestation.manifestation_custom_values.find_by(manifestation_custom_property: property)
end
if value
value.value = row[column_name]
else
value = ManifestationCustomValue.new(
manifestation_custom_property: ManifestationCustomProperty.find_by(name: property),
value: row[column_name]
)
end
values << value
end
values
end
def self.import_item_custom_value(row, item)
values = []
ItemCustomProperty.order(:position).pluck(:name).map { |c| "item:#{c}" }.each do |column_name|
value = nil
property = column_name.split(":").last
next if row[column_name].blank?
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | true |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/classification.rb | app/models/classification.rb | class Classification < ApplicationRecord
belongs_to :classification_type
belongs_to :manifestation, touch: true, optional: true
validates :category, presence: true
searchable do
text :category, :note
integer :classification_type_id
end
strip_attributes only: [ :category, :url ]
paginates_per 10
end
# == Schema Information
#
# Table name: classifications
#
# id :bigint not null, primary key
# category :string not null
# label :string
# lft :integer
# note :text
# rgt :integer
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# classification_type_id :bigint not null
# manifestation_id :bigint
# parent_id :bigint
#
# Indexes
#
# index_classifications_on_category (category)
# index_classifications_on_classification_type_id (classification_type_id)
# index_classifications_on_manifestation_id (manifestation_id)
# index_classifications_on_parent_id (parent_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/form_of_work.rb | app/models/form_of_work.rb | class FormOfWork < ApplicationRecord
include MasterModel
has_many :works, class_name: "Manifestation" # , dependent: :restrict_with_exception
end
# == Schema Information
#
# Table name: form_of_works
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_form_of_works_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resource_export_file_transition.rb | app/models/resource_export_file_transition.rb | class ResourceExportFileTransition < ApplicationRecord
belongs_to :resource_export_file, inverse_of: :resource_export_file_transitions
end
# == Schema Information
#
# Table name: resource_export_file_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# resource_export_file_id :bigint
#
# Indexes
#
# index_resource_export_file_transitions_on_file_id (resource_export_file_id)
# index_resource_export_file_transitions_on_sort_key_and_file_id (sort_key,resource_export_file_id) UNIQUE
# index_resource_export_file_transitions_parent_most_recent (resource_export_file_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/ndl_bib_id_record.rb | app/models/ndl_bib_id_record.rb | class NdlBibIdRecord < ApplicationRecord
belongs_to :manifestation
validates :body, presence: true, uniqueness: true
end
# == Schema Information
#
# Table name: ndl_bib_id_records
#
# id :bigint not null, primary key
# body :string not null
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_ndl_bib_id_records_on_body (body) UNIQUE
# index_ndl_bib_id_records_on_manifestation_id (manifestation_id)
#
# Foreign Keys
#
# fk_rails_... (manifestation_id => manifestations.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/request_status_type.rb | app/models/request_status_type.rb | class RequestStatusType < ApplicationRecord
include MasterModel
validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ }
has_many :reserves, dependent: :restrict_with_exception
private
def valid_name?
true
end
end
# == Schema Information
#
# Table name: request_status_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_request_status_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/agent_relationship_type.rb | app/models/agent_relationship_type.rb | class AgentRelationshipType < ApplicationRecord
include MasterModel
default_scope { order("agent_relationship_types.position") }
has_many :agent_relationships, dependent: :destroy
end
# == Schema Information
#
# Table name: agent_relationship_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_agent_relationship_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_reserve_stat.rb | app/models/user_reserve_stat.rb | class UserReserveStat < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: UserReserveStatTransition,
initial_state: UserReserveStatStateMachine.initial_state
]
include CalculateStat
default_scope { order("user_reserve_stats.id DESC") }
scope :not_calculated, -> { in_state(:pending) }
has_many :reserve_stat_has_users, dependent: :destroy
has_many :users, through: :reserve_stat_has_users
belongs_to :user
paginates_per 10
attr_accessor :mode
has_many :user_reserve_stat_transitions, autosave: false, dependent: :destroy
def state_machine
UserReserveStatStateMachine.new(self, transition_class: UserReserveStatTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def calculate_count!
self.started_at = Time.zone.now
User.find_each do |user|
daily_count = user.reserves.created(start_date.beginning_of_day, end_date.tomorrow.beginning_of_day).size
if daily_count.positive?
users << user
sql = [ "UPDATE reserve_stat_has_users SET reserves_count = ? WHERE user_reserve_stat_id = ? AND user_id = ?", daily_count, id, user.id ]
UserReserveStat.connection.execute(
self.class.send(:sanitize_sql_array, sql)
)
end
end
self.completed_at = Time.zone.now
transition_to!(:completed)
mailer = UserReserveStatMailer.completed(self)
mailer.deliver_later
send_message(mailer)
end
end
# == Schema Information
#
# Table name: user_reserve_stats
#
# id :bigint not null, primary key
# completed_at :datetime
# end_date :datetime
# note :text
# start_date :datetime
# started_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_user_reserve_stats_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/isbn_record_and_manifestation.rb | app/models/isbn_record_and_manifestation.rb | class IsbnRecordAndManifestation < ApplicationRecord
belongs_to :isbn_record
belongs_to :manifestation
validates :isbn_record_id, uniqueness: { scope: :manifestation_id }
end
# == Schema Information
#
# Table name: isbn_record_and_manifestations(書誌とISBNの関係)
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# isbn_record_id :bigint not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_isbn_record_and_manifestations_on_isbn_record_id (isbn_record_id)
# index_isbn_record_and_manifestations_on_manifestation_id (manifestation_id,isbn_record_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (isbn_record_id => isbn_records.id)
# fk_rails_... (manifestation_id => manifestations.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/checkout_stat_has_manifestation.rb | app/models/checkout_stat_has_manifestation.rb | class CheckoutStatHasManifestation < ApplicationRecord
belongs_to :manifestation_checkout_stat
belongs_to :manifestation
validates :manifestation_id, uniqueness: { scope: :manifestation_checkout_stat_id }
paginates_per 10
end
# == Schema Information
#
# Table name: checkout_stat_has_manifestations
#
# id :bigint not null, primary key
# checkouts_count :integer
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_checkout_stat_id :bigint not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_checkout_stat_has_manifestations_on_checkout_stat_id (manifestation_checkout_stat_id)
# index_checkout_stat_has_manifestations_on_manifestation_id (manifestation_id)
#
# Foreign Keys
#
# fk_rails_... (manifestation_id => manifestations.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation.rb | app/models/manifestation.rb | class Manifestation < ApplicationRecord
include EnjuCirculation::EnjuManifestation
include EnjuSubject::EnjuManifestation
include EnjuNdl::EnjuManifestation
include EnjuNii::EnjuManifestation
include EnjuLoc::EnjuManifestation
include EnjuManifestationViewer::EnjuManifestation
include EnjuBookmark::EnjuManifestation
include EnjuOai::OaiModel
has_many :creates, -> { order("creates.position") }, dependent: :destroy, foreign_key: "work_id", inverse_of: :work
has_many :creators, through: :creates, source: :agent
has_many :realizes, -> { order("realizes.position") }, dependent: :destroy, foreign_key: "expression_id", inverse_of: :expression
has_many :contributors, through: :realizes, source: :agent
has_many :produces, -> { order("produces.position") }, dependent: :destroy, foreign_key: "manifestation_id", inverse_of: :manifestation
has_many :publishers, through: :produces, source: :agent
has_many :items, dependent: :destroy
has_many :children, foreign_key: "parent_id", class_name: "ManifestationRelationship", dependent: :destroy, inverse_of: :parent
has_many :parents, foreign_key: "child_id", class_name: "ManifestationRelationship", dependent: :destroy, inverse_of: :child
has_many :derived_manifestations, through: :children, source: :child
has_many :original_manifestations, through: :parents, source: :parent
has_many :picture_files, as: :picture_attachable, dependent: :destroy
belongs_to :language
belongs_to :carrier_type
belongs_to :manifestation_content_type, class_name: "ContentType", foreign_key: "content_type_id", inverse_of: :manifestations
has_many :series_statements, dependent: :destroy
belongs_to :frequency
belongs_to :required_role, class_name: "Role"
has_one :resource_import_result
has_many :identifiers, dependent: :destroy
has_many :manifestation_custom_values, -> { joins(:manifestation_custom_property).order(:position) }, inverse_of: :manifestation, dependent: :destroy
has_one :periodical_record, class_name: "Periodical", dependent: :destroy
has_one :periodical_and_manifestation, dependent: :destroy
has_one :periodical, through: :periodical_and_manifestation, dependent: :destroy
has_many :isbn_record_and_manifestations, dependent: :destroy
has_many :isbn_records, through: :isbn_record_and_manifestations
has_many :issn_record_and_manifestations, dependent: :destroy
has_many :issn_records, through: :issn_record_and_manifestations
has_one :doi_record, dependent: :destroy
has_one :jpno_record, dependent: :destroy
has_one :ncid_record, dependent: :destroy
has_one :lccn_record, dependent: :destroy
has_one :ndl_bib_id_record, dependent: :destroy
accepts_nested_attributes_for :creators, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :contributors, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :publishers, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :series_statements, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :identifiers, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :manifestation_custom_values, reject_if: :all_blank
accepts_nested_attributes_for :doi_record, reject_if: :all_blank
accepts_nested_attributes_for :jpno_record, reject_if: :all_blank
accepts_nested_attributes_for :ncid_record, reject_if: :all_blank
accepts_nested_attributes_for :lccn_record, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :isbn_records, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :issn_records, allow_destroy: true, reject_if: :all_blank
searchable do
text :title, default_boost: 2 do
titles
end
[ :fulltext, :note, :creator, :contributor, :publisher, :abstract, :description, :statement_of_responsibility ].each do |field|
text field do
if series_master?
derived_manifestations.map { |c| c.send(field) }.flatten.compact
else
self.send(field)
end
end
end
text :item_identifier do
if series_master?
root_series_statement.root_manifestation.items.pluck(:item_identifier, :binding_item_identifier).flatten.compact
else
items.pluck(:item_identifier, :binding_item_identifier).flatten.compact
end
end
string :call_number, multiple: true do
items.pluck(:call_number)
end
string :title, multiple: true
# text フィールドだと区切りのない文字列の index が上手く作成
# できなかったので。 downcase することにした。
# 他の string 項目も同様の問題があるので、必要な項目は同様の処置が必要。
string :connect_title do
title.join("").gsub(/\s/, "").downcase
end
string :connect_creator do
creator.join("").gsub(/\s/, "").downcase
end
string :connect_publisher do
publisher.join("").gsub(/\s/, "").downcase
end
string :isbn, multiple: true do
isbn_characters
end
string :issn, multiple: true do
if series_statements.exists?
[ issn_records.pluck(:body), (series_statements.map { |s| s.manifestation.issn_records.pluck(:body) }) ].flatten.uniq.compact
else
issn_records.pluck(:body)
end
end
string :lccn do
lccn_record&.body
end
string :jpno, multiple: true do
jpno_record&.body
end
string :carrier_type do
carrier_type.name
end
string :library, multiple: true do
if series_master?
root_series_statement.root_manifestation.items.map { |i| i.shelf.library.name }.flatten.uniq
else
items.map { |i| i.shelf.library.name }
end
end
string :language do
language&.name
end
string :item_identifier, multiple: true do
if series_master?
root_series_statement.root_manifestation.items.pluck(:item_identifier, :binding_item_identifier).flatten.compact
else
items.pluck(:item_identifier, :binding_item_identifier).flatten.compact
end
end
string :shelf, multiple: true do
items.collect { |i| "#{i.shelf.library.name}_#{i.shelf.name}" }
end
time :created_at
time :updated_at
time :pub_date, multiple: true do
if series_master?
root_series_statement.root_manifestation.pub_dates
else
pub_dates
end
end
time :date_of_publication
integer :pub_year do
date_of_publication&.year
end
integer :creator_ids, multiple: true
integer :contributor_ids, multiple: true
integer :publisher_ids, multiple: true
integer :item_ids, multiple: true
integer :original_manifestation_ids, multiple: true
integer :parent_ids, multiple: true do
original_manifestations.pluck(:id)
end
integer :required_role_id
integer :height
integer :width
integer :depth
integer :volume_number
integer :issue_number
integer :serial_number
integer :start_page
integer :end_page
integer :number_of_pages
float :price
integer :series_statement_ids, multiple: true
boolean :repository_content
# for OpenURL
text :aulast do
creators.pluck(:last_name)
end
text :aufirst do
creators.pluck(:first_name)
end
# OTC start
string :creator, multiple: true do
creator.map { |au| au.gsub(" ", "") }
end
text :au do
creator
end
text :atitle do
if serial? && root_series_statement.nil?
titles
end
end
text :btitle do
title unless serial?
end
text :jtitle do
if serial?
if root_series_statement
root_series_statement.titles
else
titles
end
end
end
text :isbn do # 前方一致検索のためtext指定を追加
isbn_characters
end
text :issn do # 前方一致検索のためtext指定を追加
if series_statements.exists?
[ issn_records.pluck(:body), (series_statements.map { |s| s.manifestation.issn_records.pluck(:body) }) ].flatten.uniq.compact
else
issn_records.pluck(:body)
end
end
text :identifier do
identifiers.pluck(:body)
end
string :sort_title
string :doi do
doi_record&.body
end
boolean :serial do
serial?
end
boolean :series_master do
series_master?
end
boolean :resource_master do
if serial?
if series_master?
true
else
false
end
else
true
end
end
time :acquired_at
string :agent_id, multiple: true do
creators.map { |a| a.id }
end
end
has_one_attached :attachment
validates :original_title, presence: true
validates :start_page, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :end_page, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :height, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :width, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :depth, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :manifestation_identifier, uniqueness: true, allow_blank: true
validates :pub_date, format: { with: /\A\[{0,1}\d+([\/-]\d{0,2}){0,2}\]{0,1}\z/ }, allow_blank: true
validates :access_address, url: true, allow_blank: true, length: { maximum: 255 }
validates :issue_number, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :volume_number, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :serial_number, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
validates :edition, numericality: { greater_than_or_equal_to: 0 }, allow_blank: true
before_save :set_date_of_publication, :set_number
before_save do
attachment.purge if delete_attachment == "1"
end
after_create :clear_cached_numdocs
after_destroy :index_series_statement
after_save :index_series_statement
after_touch do |manifestation|
manifestation.index
manifestation.index_series_statement
Sunspot.commit
end
strip_attributes only: [ :manifestation_identifier, :pub_date, :original_title ]
paginates_per 10
attr_accessor :during_import, :parent_id, :delete_attachment
def set_date_of_publication
return if pub_date.blank?
year = Time.utc(pub_date.rjust(4, "0").to_i).year rescue nil
begin
date = Time.zone.parse(pub_date.rjust(4, "0"))
if date.year != year
raise ArgumentError
end
rescue ArgumentError, TZInfo::AmbiguousTime
date = nil
end
pub_date_string = pub_date.rjust(4, "0").split(";").first.gsub(/[\[\]]/, "")
if pub_date_string.length == 4
date = Time.zone.parse(Time.utc(pub_date_string).to_s).beginning_of_day
else
while date.nil?
pub_date_string += "-01"
break if pub_date_string =~ /-01-01-01$/
begin
date = Time.zone.parse(pub_date_string)
if date.year != year
raise ArgumentError
end
rescue ArgumentError
date = nil
rescue TZInfo::AmbiguousTime
date = nil
self.year_of_publication = pub_date_string.to_i if pub_date_string =~ /^\d+$/
break
end
end
end
if date
self.year_of_publication = date.year
self.month_of_publication = date.month
if date.year.positive?
self.date_of_publication = date
end
end
end
def self.cached_numdocs
Rails.cache.fetch("manifestation_search_total") { Manifestation.search.total }
end
def clear_cached_numdocs
Rails.cache.delete("manifestation_search_total")
end
def parent_of_series
original_manifestations
end
def number_of_pages
if start_page && end_page
end_page.to_i - start_page.to_i + 1
end
end
def titles
title = []
title << original_title.to_s.strip
title << title_transcription.to_s.strip
title << title_alternative.to_s.strip
title << volume_number_string
title << issue_number_string
title << serial_number.to_s
title << edition_string
title << series_statements.map { |s| s.titles }
# title << original_title.wakati
# title << title_transcription.wakati rescue nil
# title << title_alternative.wakati rescue nil
title.flatten
end
def url
# access_address
"#{LibraryGroup.site_config.url}#{self.class.to_s.tableize}/#{id}"
end
def creator
creators.collect(&:name).flatten
end
def contributor
contributors.collect(&:name).flatten
end
def publisher
publishers.collect(&:name).flatten
end
def title
titles
end
# TODO: よりよい推薦方法
def self.pickup(keyword = nil, current_user = nil)
return nil if self.cached_numdocs < 5
if current_user&.role
current_role_id = current_user.role.id
else
current_role_id = 1
end
# TODO: ヒット件数が0件のキーワードがあるときに指摘する
response = Manifestation.search do
fulltext keyword if keyword
with(:required_role_id).less_than_or_equal_to current_role_id
order_by(:random)
paginate page: 1, per_page: 1
end
response.results.first
end
def extract_text
return unless attachment.attached?
return unless ENV["ENJU_LEAF_EXTRACT_TEXT"] == "true"
if ENV["ENJU_LEAF_EXTRACT_FILESIZE_LIMIT"].present?
filesize_limit = ENV["ENJU_LEAF_EXTRACT_FILESIZE_LIMIT"].to_i
else
filesize_limit = 2097152
end
if attachment.byte_size > filesize_limit
Rails.logger.error("#{attachment.filename} (size: #{attachment.byte_size} byte(s)) exceeds filesize limit #{ENV['ENJU_LEAF_EXTRACT_FILESIZE_LIMIT']} bytes")
return ""
end
client = Faraday.new(url: ENV["TIKA_URL"] || "http://tika:9998") do |conn|
conn.adapter :net_http
end
response = client.put("/tika/text") do |req|
req.headers["Content-Type"] = attachment.content_type
req.headers["Content-Length"] = attachment.byte_size.to_s
req.body = Faraday::FilePart.new(StringIO.new(attachment.download), attachment.content_type)
end
payload = JSON.parse(response.body)["X-TIKA:content"].strip.tr("\t", " ").gsub(/\r?\n/, "")
payload
end
def created(agent)
creates.find_by(agent_id: agent.id)
end
def realized(agent)
realizes.find_by(agent_id: agent.id)
end
def produced(agent)
produces.find_by(agent_id: agent.id)
end
def sort_title
if series_master?
if root_series_statement.title_transcription?
NKF.nkf("-w --katakana", root_series_statement.title_transcription)
else
root_series_statement.original_title
end
elsif title_transcription?
NKF.nkf("-w --katakana", title_transcription)
else
original_title
end
end
# ISBNで検索する
# @param isbn [Strinng]
# @return [Manifestation]
def self.find_by_isbn(isbn)
IsbnRecord.find_by(body: isbn)&.manifestations
isbn_record = IsbnRecord.find_by(body: isbn)
return unless isbn_record
isbn_record.manifestations.order(:created_at).first
end
def index_series_statement
series_statements.map { |s| s.index
s.root_manifestation&.index}
end
def acquired_at
items.order(:acquired_at).first.try(:acquired_at)
end
def series_master?
return true if root_series_statement
false
end
def web_item
items.find_by(shelf_id: Shelf.web.id)
end
def set_agent_role_type(agent_lists, options = { scope: :creator })
agent_lists.each do |agent_list|
name_and_role = agent_list[:full_name].split("||")
if agent_list[:agent_identifier].present?
agent = Agent.find_by(agent_identifier: agent_list[:agent_identifier])
end
agent ||= Agent.find_by(full_name: name_and_role[0])
next unless agent
type = name_and_role[1].to_s.strip
case options[:scope]
when :creator
type = "author" if type.blank?
role_type = CreateType.find_by(name: type)
create = Create.find_by(work_id: id, agent_id: agent.id)
if create
create.create_type = role_type
create.save(validate: false)
end
when :publisher
type = "publisher" if role_type.blank?
produce = Produce.find_by(manifestation_id: id, agent_id: agent.id)
if produce
produce.produce_type = ProduceType.find_by(name: type)
produce.save(validate: false)
end
else
raise "#{options[:scope]} is not supported!"
end
end
end
def set_number
self.volume_number = volume_number_string.scan(/\d*/).map { |s| s.to_i if s =~ /\d/ }.compact.first if volume_number_string && !volume_number?
self.issue_number = issue_number_string.scan(/\d*/).map { |s| s.to_i if s =~ /\d/ }.compact.first if issue_number_string && !issue_number?
self.edition = edition_string.scan(/\d*/).map { |s| s.to_i if s =~ /\d/ }.compact.first if edition_string && !edition?
end
def pub_dates
return [] unless pub_date
pub_date_array = pub_date.split(";")
pub_date_array.map { |pub_date_string|
date = nil
while date.nil? do
pub_date_string += "-01"
break if pub_date_string =~ /-01-01-01$/
begin
date = Time.zone.parse(pub_date_string)
rescue ArgumentError
rescue TZInfo::AmbiguousTime
end
end
date
}.compact
end
def latest_issue
if series_master?
derived_manifestations.where.not(date_of_publication: nil).order("date_of_publication DESC").first
end
end
def first_issue
if series_master?
derived_manifestations.where.not(date_of_publication: nil).order("date_of_publication DESC").first
end
end
def identifier_contents(name)
identifiers.id_type(name).order(:position).pluck(:body)
end
# CSVのヘッダ
# @param [String] role 権限
def self.csv_header(role: "Guest")
Manifestation.new.to_hash(role: role).keys
end
# CSV出力用のハッシュ
# @param [String] role 権限
def to_hash(role: "Guest")
record = {
manifestation_id: id,
original_title: original_title,
title_alternative: title_alternative,
title_transcription: title_transcription,
statement_of_responsibility: statement_of_responsibility,
serial: serial,
manifestation_identifier: manifestation_identifier,
creator: creates.map { |create|
if create.create_type
"#{create.agent.full_name}||#{create.create_type.name}"
else
"#{create.agent.full_name}"
end
}.join("//"),
contributor: realizes.map { |realize|
if realize.realize_type
"#{realize.agent.full_name}||#{realize.realize_type.name}"
else
"#{realize.agent.full_name}"
end
}.join("//"),
publisher: produces.map { |produce|
if produce.produce_type
"#{produce.agent.full_name}||#{produce.produce_type.name}"
else
"#{produce.agent.full_name}"
end
}.join("//"),
pub_date: pub_date,
date_of_publication: date_of_publication,
year_of_publication: year_of_publication,
publication_place: publication_place,
manifestation_created_at: created_at,
manifestation_updated_at: updated_at,
carrier_type: carrier_type.name,
content_type: manifestation_content_type.name,
frequency: frequency.name,
language: language.name,
isbn: isbn_records.pluck(:body).join("//"),
issn: issn_records.pluck(:body).join("//"),
volume_number: volume_number,
volume_number_string: volume_number_string,
edition: edition,
edition_string: edition_string,
issue_number: issue_number,
issue_number_string: issue_number_string,
serial_number: serial_number,
extent: extent,
start_page: start_page,
end_page: end_page,
dimensions: dimensions,
height: height,
width: width,
depth: depth,
manifestation_price: price,
access_address: access_address,
manifestation_required_role: required_role.name,
abstract: abstract,
description: description,
note: note
}
IdentifierType.find_each do |type|
next if [ "isbn", "issn", "jpno", "ncid", "lccn", "doi" ].include?(type.name.downcase.strip)
record[:"identifier:#{type.name.to_sym}"] = identifiers.where(identifier_type: type).pluck(:body).join("//")
end
series = series_statements.order(:position)
record.merge!(
series_statement_id: series.pluck(:id).join("//"),
series_statement_original_title: series.pluck(:original_title).join(".//"),
series_statement_title_subseries: series.pluck(:title_subseries).join("//"),
series_statement_title_subseries_transcription: series.pluck(:title_subseries_transcription).join("//"),
series_statement_title_transcription: series.pluck(:title_transcription).join("//"),
series_statement_creator: series.pluck(:creator_string).join("//"),
series_statement_volume_number: series.pluck(:volume_number_string).join("//"),
series_statement_series_master: series.pluck(:series_master).join("//"),
series_statement_root_manifestation_id: series.pluck(:root_manifestation_id).join("//"),
series_statement_manifestation_id: series.pluck(:manifestation_id).join("//"),
series_statement_position: series.pluck(:position).join("//"),
series_statement_note: series.pluck(:note).join("//"),
series_statement_created_at: series.pluck(:created_at).join("//"),
series_statement_updated_at: series.pluck(:updated_at).join("//")
)
if [ "Administrator", "Librarian" ].include?(role)
record.merge!({
memo: memo
})
ManifestationCustomProperty.order(:position).each do |custom_property|
custom_value = manifestation_custom_values.find_by(manifestation_custom_property: custom_property)
record[:"manifestation:#{custom_property.name}"] = custom_value&.value
end
end
if defined?(EnjuSubject)
SubjectHeadingType.find_each do |type|
record[:"subject:#{type.name}"] = subjects.where(subject_heading_type: type).pluck(:term).join("//")
end
ClassificationType.find_each do |type|
record[:"classification:#{type.name}"] = classifications.where(classification_type: type).pluck(:category).map(&:to_s).join("//")
end
end
record["doi"] = doi_record&.body
record["jpno"] = jpno_record&.body
record["ncid"] = ncid_record&.body
record["lccn"] = lccn_record&.body
record["iss_itemno"] = ndl_bib_id_record&.body
record
end
# TSVでのエクスポート
# @param [String] role 権限
# @param [String] col_sep 区切り文字
def self.export(role: "Guest", col_sep: "\t")
file = Tempfile.create("manifestation_export") do |f|
f.write (Manifestation.csv_header(role: role) + Item.csv_header(role: role)).to_csv(col_sep: col_sep)
Manifestation.find_each do |manifestation|
if manifestation.items.exists?
manifestation.items.each do |item|
f.write (manifestation.to_hash(role: role).values + item.to_hash(role: role).values).to_csv(col_sep: col_sep)
end
else
f.write manifestation.to_hash(role: role).values.to_csv(col_sep: col_sep)
end
end
f.rewind
f.read
end
file
end
def root_series_statement
series_statements.find_by(root_manifestation_id: id)
end
def isbn_characters
isbn_records.pluck(:body).map { |i|
isbn10 = isbn13 = isbn10_dash = isbn13_dash = nil
isbn10 = Lisbn.new(i).isbn10
isbn13 = Lisbn.new(i).isbn13
isbn10_dash = Lisbn.new(isbn10).isbn_with_dash if isbn10
isbn13_dash = Lisbn.new(isbn13).isbn_with_dash if isbn13
[
isbn10, isbn13, isbn10_dash, isbn13_dash
]
}.flatten
end
def set_custom_property(row)
ManifestationCustomProperty.find_each do |property|
if row[property]
custom_value = ManifestationCustomValue.new(
manifestation: self,
manifestation_custom_property: property,
value: row[property]
)
end
end
end
end
# == Schema Information
#
# Table name: manifestations
#
# id :bigint not null, primary key
# abstract :text
# access_address :string
# available_at :datetime
# classification_number :string
# date_accepted :datetime
# date_captured :datetime
# date_copyrighted :datetime
# date_of_publication :datetime
# date_submitted :datetime
# depth :integer
# description :text
# dimensions :text
# edition :integer
# edition_string :string
# end_page :integer
# extent :text
# fulltext :text
# fulltext_content :boolean
# height :integer
# issue_number :integer
# issue_number_string :string
# lock_version :integer default(0), not null
# manifestation_identifier :string
# memo :text
# month_of_publication :integer
# note :text
# original_title :text not null
# price :integer
# pub_date :string
# publication_place :text
# repository_content :boolean default(FALSE), not null
# required_score :integer default(0), not null
# serial :boolean
# serial_number :integer
# serial_number_string :string
# start_page :integer
# statement_of_responsibility :text
# subscription_master :boolean default(FALSE), not null
# title_alternative :text
# title_alternative_transcription :text
# title_transcription :text
# valid_until :datetime
# volume_number :integer
# volume_number_string :string
# width :integer
# year_of_publication :integer
# created_at :datetime not null
# updated_at :datetime not null
# carrier_type_id :bigint default(1), not null
# content_type_id :bigint default(1)
# frequency_id :bigint default(1), not null
# language_id :bigint default(1), not null
# nii_type_id :bigint
# required_role_id :bigint default(1), not null
#
# Indexes
#
# index_manifestations_on_access_address (access_address)
# index_manifestations_on_date_of_publication (date_of_publication)
# index_manifestations_on_manifestation_identifier (manifestation_identifier)
# index_manifestations_on_nii_type_id (nii_type_id)
# index_manifestations_on_updated_at (updated_at)
#
# Foreign Keys
#
# fk_rails_... (required_role_id => roles.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/country.rb | app/models/country.rb | class Country < ApplicationRecord
include MasterModel
default_scope { order("countries.position") }
has_many :agents, dependent: :destroy
has_many :libraries, dependent: :destroy
has_one :library_group
# If you wish to change the field names for brevity, feel free to enable/modify these.
# alias_attribute :iso, :alpha_2
# alias_attribute :iso3, :alpha_3
# alias_attribute :numeric, :numeric_3
# Validations
validates :alpha_2, :alpha_3, :numeric_3, presence: true
validates :name, presence: true, format: { with: /\A[0-9A-Za-z][0-9A-Za-z_\-\s,]*[0-9a-z]\Z/ }
after_destroy :clear_all_cache
after_save :clear_all_cache
def self.all_cache
Rails.cache.fetch("country_all") { Country.all.to_a }
end
def clear_all_cache
Rails.cache.delete("country_all")
end
private
def valid_name?
true
end
end
# == Schema Information
#
# Table name: countries
#
# id :bigint not null, primary key
# alpha_2 :string
# alpha_3 :string
# display_name :text
# name :string not null
# note :text
# numeric_3 :string
# position :integer
#
# Indexes
#
# index_countries_on_alpha_2 (alpha_2)
# index_countries_on_alpha_3 (alpha_3)
# index_countries_on_lower_name (lower((name)::text)) UNIQUE
# index_countries_on_numeric_3 (numeric_3)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/message_state_machine.rb | app/models/message_state_machine.rb | class MessageStateMachine
include Statesman::Machine
state :pending, initial: true
state :unread
state :read
transition from: :pending, to: :unread
transition from: :pending, to: :read
transition from: :unread, to: :read
transition from: :read, to: :unread
before_transition(from: :pending, to: :read) do |message|
message.read_at = Time.zone.now unless message.read_at
end
before_transition(from: :unread, to: :read) do |message|
message.read_at = Time.zone.now unless message.read_at
end
before_transition(from: :read, to: :unread) do |message|
message.read_at = nil
end
after_transition(from: :pending, to: :read) do |message|
message.index
Sunspot.commit
end
after_transition(from: :unread, to: :read) do |message|
message.index
Sunspot.commit
end
after_transition(from: :read, to: :unread) do |message|
message.index
Sunspot.commit
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/realize.rb | app/models/realize.rb | class Realize < ApplicationRecord
belongs_to :agent
belongs_to :expression, class_name: "Manifestation", touch: true
belongs_to :realize_type, optional: true
validates :expression_id, uniqueness: { scope: :agent_id }
after_destroy :reindex
after_save :reindex
acts_as_list scope: :expression
def reindex
agent.try(:index)
expression.try(:index)
end
end
# == Schema Information
#
# Table name: realizes
#
# id :bigint not null, primary key
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# agent_id :bigint not null
# expression_id :bigint not null
# realize_type_id :bigint
#
# Indexes
#
# index_realizes_on_agent_id (agent_id)
# index_realizes_on_expression_id_and_agent_id (expression_id,agent_id) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/picture_file.rb | app/models/picture_file.rb | class PictureFile < ApplicationRecord
scope :attached, -> { where.not(picture_attachable_id: nil) }
belongs_to :picture_attachable, polymorphic: true
has_one_attached :attachment
validates :picture_attachable_type, presence: true, inclusion: { in: [ "Event", "Manifestation", "Agent", "Shelf" ] }
validates_associated :picture_attachable
default_scope { order("picture_files.position") }
# http://railsforum.com/viewtopic.php?id=11615
acts_as_list scope: :picture_attachable
strip_attributes only: :picture_attachable_type
paginates_per 10
end
# == Schema Information
#
# Table name: picture_files
#
# id :bigint not null, primary key
# picture_attachable_type :string
# picture_fingerprint :string
# picture_width :integer
# position :integer
# title :text
# created_at :datetime not null
# updated_at :datetime not null
# picture_attachable_id :bigint
#
# Indexes
#
# index_picture_files_on_picture_attachable_id_and_type (picture_attachable_id,picture_attachable_type)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_reserve_stat_state_machine.rb | app/models/user_reserve_stat_state_machine.rb | class UserReserveStatStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
transition from: :pending, to: :started
transition from: :started, to: :completed
after_transition(to: :started) do |user_reserve_stat|
user_reserve_stat.update_column(:started_at, Time.zone.now)
user_reserve_stat.calculate_count!
end
after_transition(to: :completed) do |user_reserve_stat|
user_reserve_stat.update_column(:completed_at, Time.zone.now)
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/agent_import_file_transition.rb | app/models/agent_import_file_transition.rb | class AgentImportFileTransition < ApplicationRecord
belongs_to :agent_import_file, inverse_of: :agent_import_file_transitions
end
# == Schema Information
#
# Table name: agent_import_file_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# agent_import_file_id :bigint
#
# Indexes
#
# index_agent_import_file_transitions_on_agent_import_file_id (agent_import_file_id)
# index_agent_import_file_transitions_on_sort_key_and_file_id (sort_key,agent_import_file_id) UNIQUE
# index_agent_import_file_transitions_parent_most_recent (agent_import_file_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/carrier_type_has_checkout_type.rb | app/models/carrier_type_has_checkout_type.rb | class CarrierTypeHasCheckoutType < ApplicationRecord
scope :available_for_carrier_type, lambda { |carrier_type| includes(:carrier_type).where("carrier_types.name = ?", carrier_type.name) }
scope :available_for_user_group, lambda { |user_group| includes(checkout_type: :user_groups).where("user_groups.name = ?", user_group.name) }
belongs_to :carrier_type
belongs_to :checkout_type
validates :checkout_type_id, uniqueness: { scope: :carrier_type_id }
acts_as_list scope: :carrier_type_id
end
# == Schema Information
#
# Table name: carrier_type_has_checkout_types
#
# id :bigint not null, primary key
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# carrier_type_id :bigint not null
# checkout_type_id :bigint not null
#
# Indexes
#
# index_carrier_type_has_checkout_types_on_carrier_type_id (carrier_type_id,checkout_type_id) UNIQUE
# index_carrier_type_has_checkout_types_on_checkout_type_id (checkout_type_id)
#
# Foreign Keys
#
# fk_rails_... (carrier_type_id => carrier_types.id)
# fk_rails_... (checkout_type_id => checkout_types.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_import_result.rb | app/models/user_import_result.rb | class UserImportResult < ApplicationRecord
scope :file_id, proc { |file_id| where(user_import_file_id: file_id) }
scope :failed, -> { where(user_id: nil) }
belongs_to :user_import_file
belongs_to :user, optional: true
end
# == Schema Information
#
# Table name: user_import_results
#
# id :bigint not null, primary key
# body :text
# error_message :text
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint
# user_import_file_id :bigint
#
# Indexes
#
# index_user_import_results_on_user_id (user_id)
# index_user_import_results_on_user_import_file_id (user_import_file_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_import_file.rb | app/models/user_import_file.rb | class UserImportFile < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: UserImportFileTransition,
initial_state: UserImportFileStateMachine.initial_state
]
include ImportFile
default_scope { order("user_import_files.id DESC") }
scope :not_imported, -> { in_state(:pending) }
scope :stucked, -> { in_state(:pending).where("user_import_files.created_at < ?", 1.hour.ago) }
has_one_attached :attachment
belongs_to :user
belongs_to :default_user_group, class_name: "UserGroup"
belongs_to :default_library, class_name: "Library"
has_many :user_import_results, dependent: :destroy
has_many :user_import_file_transitions, autosave: false, dependent: :destroy
attr_accessor :mode
def state_machine
UserImportFileStateMachine.new(self, transition_class: UserImportFileTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
# 利用者情報をTSVファイルを用いて作成します。
def import
transition_to!(:started)
num = { user_imported: 0, user_found: 0, failed: 0, error: 0 }
rows = open_import_file(create_import_temp_file(attachment))
row_num = 1
field = rows.first
if [ field["username"] ].reject { |f| f.to_s.strip == "" }.empty?
raise "username column is not found"
end
rows.each do |row|
row_num += 1
import_result = UserImportResult.create!(
user_import_file_id: id, body: row.fields.join("\t")
)
next if row["dummy"].to_s.strip.present?
username = row["username"]
new_user = User.find_by(username: username)
if new_user
import_result.user = new_user
import_result.save
num[:user_found] += 1
else
new_user = User.new(
username: username,
role: Role.find_by(name: row["role"])
)
if new_user.role
unless user.has_role?(new_user.role.name)
num[:failed] += 1
next
end
else
new_user.role = Role.find(2) # User
end
new_user.assign_attributes(set_user_params(row))
if row["password"].to_s.strip.present?
new_user.password = row["password"]
else
new_user.password = Devise.friendly_token[0..7]
end
profile = Profile.new
profile.assign_attributes(set_profile_params(row))
new_user.profile = profile
Profile.transaction do
if new_user.valid? && profile.valid?
import_result.user = new_user
import_result.save!
num[:user_imported] += 1
else
error_message = "line #{row_num}: "
error_message += new_user.errors.map(&:full_message).join(" ")
error_message += profile.errors.map(&:full_message).join(" ")
import_result.error_message = error_message
import_result.save
num[:error] += 1
end
end
end
end
Sunspot.commit
rows.close
error_messages = user_import_results.order(:id).pluck(:error_message).compact
unless error_messages.empty?
self.error_message = "" if error_message.nil?
self.error_message += "\n"
self.error_message += error_messages.join("\n")
end
save
if num[:error] >= 1
transition_to!(:failed)
else
transition_to!(:completed)
end
mailer = UserImportMailer.completed(self)
send_message(mailer)
num
rescue StandardError => e
transition_to!(:failed)
mailer = UserImportMailer.failed(self)
send_message(mailer)
raise e
end
# 利用者情報をTSVファイルを用いて更新します。
def modify
transition_to!(:started)
num = { user_updated: 0, user_not_found: 0, failed: 0 }
rows = open_import_file(create_import_temp_file(attachment))
row_num = 1
field = rows.first
if [ field["username"] ].reject { |f| f.to_s.strip == "" }.empty?
raise "username column is not found"
end
rows.each do |row|
row_num += 1
next if row["dummy"].to_s.strip.present?
import_result = UserImportResult.create!(
user_import_file_id: id, body: row.fields.join("\t")
)
username = row["username"]
new_user = User.find_by(username: username)
if new_user.try(:profile)
new_user.assign_attributes(set_user_params(row))
new_user.password = row["password"] if row["password"].to_s.strip.present?
new_user.profile.assign_attributes(set_profile_params(row))
Profile.transaction do
if new_user.save && new_user.profile.save
num[:user_updated] += 1
import_result.user = new_user
import_result.save!
else
num[:failed] += 1
end
end
else
num[:user_not_found] += 1
end
end
rows.close
Sunspot.commit
transition_to!(:completed)
mailer = UserImportMailer.completed(self)
send_message(mailer)
num
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = UserImportMailer.failed(self)
send_message(mailer)
raise e
end
# 利用者情報をTSVファイルを用いて削除します。
def remove
transition_to!(:started)
row_num = 1
rows = open_import_file(create_import_temp_file(attachment))
field = rows.first
if [ field["username"] ].reject { |f| f.to_s.strip == "" }.empty?
raise "username column is not found"
end
rows.each do |row|
row_num += 1
username = row["username"].to_s.strip
remove_user = User.find_by(username: username)
next unless remove_user.try(:deletable_by?, user)
UserImportFile.transaction do
remove_user.destroy
remove_user.profile.destroy
end
end
transition_to!(:completed)
mailer = UserImportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = UserImportMailer.failed(self)
send_message(mailer)
raise e
end
private
# インポート作業用のファイルを読み込みます。
# @param [File] tempfile 作業用のファイル
def open_import_file(tempfile)
file = CSV.open(tempfile.path, "r:utf-8", col_sep: "\t")
header_columns = %w[
username role email password user_group user_number expired_at
full_name full_name_transcription required_role locked
keyword_list note locale library dummy
]
if defined?(EnjuCirculation)
header_columns += %w[checkout_icalendar_token save_checkout_history]
end
if defined?(EnjuSearchLog)
header_columns += %w[save_search_history]
end
if defined?(EnjuBookmark)
header_columns += %w[share_bookmarks]
end
header = file.first
ignored_columns = header - header_columns
unless ignored_columns.empty?
self.error_message = I18n.t("import.following_column_were_ignored", column: ignored_columns.join(", "))
save!
end
rows = CSV.open(tempfile.path, "r:utf-8", headers: header, col_sep: "\t")
UserImportResult.create!(user_import_file_id: id, body: header.join("\t"))
tempfile.close(true)
file.close
rows
end
# 未処理のインポート作業用のファイルを一括で処理します。
def self.import
UserImportFile.not_imported.each do |file|
file.import_start
end
rescue StandardError
Rails.logger.info "#{Time.zone.now} importing resources failed!"
end
private
# ユーザ情報のパラメータを設定します。
# @param [Hash] row 利用者情報のハッシュ
def set_user_params(row)
params = {}
params[:email] = row["email"] if row["email"].present?
if %w[t true].include?(row["locked"].to_s.downcase.strip)
params[:locked] = "1"
end
params
end
# 利用者情報のパラメータを設定します。
# @param [Hash] row 利用者情報のハッシュ
def set_profile_params(row)
params = {}
user_group = UserGroup.find_by(name: row["user_group"]) || default_user_group
params[:user_group_id] = user_group.id if user_group
required_role = Role.find_by(name: row["required_role"]) || Role.find_by(name: "Librarian")
params[:required_role_id] = required_role.id if required_role
params[:user_number] = row["user_number"] if row["user_number"]
params[:full_name] = row["full_name"] if row["full_name"]
params[:full_name_transcription] = row["full_name_transcription"] if row["full_name_transcription"]
if row["expired_at"].present?
params[:expired_at] = Time.zone.parse(row["expired_at"]).end_of_day
end
if row["keyword_list"].present?
params[:keyword_list] = row["keyword_list"].split("//").join("\n")
end
params[:note] = row["note"] if row["note"]
if I18n.available_locales.include?(row["locale"].to_s.to_sym)
params[:locale] = row["locale"]
end
library = Library.find_by(name: row["library"].to_s.strip) || default_library || Library.web
params[:library_id] = library.id if library
if defined?(EnjuCirculation)
params[:checkout_icalendar_token] = row["checkout_icalendar_token"] if row["checkout_icalendar_token"].present?
params[:save_checkout_history] = row["save_checkout_history"] if row["save_checkout_history"].present?
end
if defined?(EnjuSearchLog)
params[:save_search_history] = row["save_search_history"] if row["save_search_history"].present?
end
if defined?(EnjuBookmark)
params[:share_bookmarks] = row["share_bookmarks"] if row["share_bookmarks"].present?
end
params
end
end
# == Schema Information
#
# Table name: user_import_files
#
# id :bigint not null, primary key
# edit_mode :string
# error_message :text
# executed_at :datetime
# note :text
# user_encoding :string
# user_import_fingerprint :string
# created_at :datetime not null
# updated_at :datetime not null
# default_library_id :bigint
# default_user_group_id :bigint
# user_id :bigint not null
#
# Indexes
#
# index_user_import_files_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/ndl_book.rb | app/models/ndl_book.rb | class NdlBook
def initialize(node)
@node = node
end
def jpno
@node.at('./dc:identifier[@xsi:type="dcndl:JPNO"]').try(:content).to_s
end
def permalink
@node.at("./link").try(:content).to_s
end
def itemno
URI.parse(permalink).path.split("/").last
end
def title
@node.at("./title").try(:content).to_s
end
def volume
@node.at("./dcndl:volume").try(:content).to_s
end
def series_title
@node.at("./dcndl:seriesTitle").try(:content).to_s
end
def creator
@node.xpath("./dc:creator").map(&:content).join(" ")
end
def publisher
@node.xpath("./dc:publisher").map(&:content).join(" ")
end
def issued
@node.at('./dcterms:issued[@xsi:type="dcterms:W3CDTF"]').try(:content).to_s
end
def isbn
@node.at('./dc:identifier[@xsi:type="dcndl:ISBN"]').try(:content).to_s
end
def self.per_page
10
end
def self.search(query, page = 1, _per_page = per_page)
if query
cnt = per_page
page = 1 if page.to_i < 1
idx = (page.to_i - 1) * cnt + 1
doc = Nokogiri::XML(Manifestation.search_ndl(query, cnt: cnt, page: page, idx: idx, raw: true, mediatype: "books periodicals video audio scores").to_s)
items = doc.xpath("//channel/item").map { |node| new node }
total_entries = doc.at("//channel/openSearch:totalResults").content.to_i
{ items: items, total_entries: total_entries }
else
{ items: [], total_entries: 0 }
end
end
def self.import_from_sru_response(itemno)
identifier = NdlBibIdRecord.find_by(body: itemno)
return if identifier
url = "https://ndlsearch.ndl.go.jp/api/sru?operation=searchRetrieve&recordSchema=dcndl&maximumRecords=1&query=%28itemno=#{itemno}%29&onlyBib=true"
xml = Faraday.get(url).body
response = Nokogiri::XML(xml).at("//xmlns:recordData")
return unless response.try(:content)
Manifestation.import_record(Nokogiri::XML(response.content))
end
def subjects
@node.xpath("//dcterms:subject/rdf:Description").map { |a|
{
id: a.attributes["about"].content,
value: a.at("./rdf:value").content
}
}
end
def authors
@node.xpath("//dcterms:creator/foaf:Agent").map { |a| { id: a.attributes["about"].content, name: a.at("./foaf:name").content, transcription: a.at("./dcndl:transcription").try(:content) } }
end
attr_accessor :url
class AlreadyImported < StandardError
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/subject_heading_type.rb | app/models/subject_heading_type.rb | class SubjectHeadingType < ApplicationRecord
include MasterModel
has_many :subjects, dependent: :destroy
validates :name, format: { with: /\A[0-9a-z][0-9a-z_\-]*[0-9a-z]\Z/ }
end
# == Schema Information
#
# Table name: subject_heading_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_subject_heading_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/own.rb | app/models/own.rb | class Own < ApplicationRecord
belongs_to :agent
belongs_to :item
validates :item_id, uniqueness: { scope: :agent_id }
after_destroy :reindex
after_save :reindex
acts_as_list scope: :item
attr_accessor :item_identifier
def reindex
agent.try(:index)
item.try(:index)
end
end
# == Schema Information
#
# Table name: owns
#
# id :bigint not null, primary key
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# agent_id :bigint not null
# item_id :bigint not null
#
# Indexes
#
# index_owns_on_agent_id (agent_id)
# index_owns_on_item_id_and_agent_id (item_id,agent_id) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/series_statement_merge_list.rb | app/models/series_statement_merge_list.rb | class SeriesStatementMergeList < ApplicationRecord
has_many :series_statement_merges, dependent: :destroy
has_many :series_statements, through: :series_statement_merges
validates :title, presence: true
paginates_per 10
end
# == Schema Information
#
# Table name: series_statement_merge_lists
#
# id :bigint not null, primary key
# title :string
# created_at :datetime not null
# updated_at :datetime not null
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/news_post.rb | app/models/news_post.rb | class NewsPost < ApplicationRecord
scope :published, -> { where(draft: false) }
scope :current, -> { where("start_date <= ? AND end_date >= ?", Time.zone.now, Time.zone.now) }
default_scope { order("news_posts.start_date DESC") }
belongs_to :user
belongs_to :required_role, class_name: "Role"
validates :title, :body, presence: true
validate :check_date
acts_as_list
searchable do
text :title, :body
time :start_date, :end_date
end
def self.per_page
10
end
def check_date
if start_date && end_date
self.end_date = end_date.end_of_day
if start_date >= end_date
errors.add(:start_date)
errors.add(:end_date)
end
end
end
end
# == Schema Information
#
# Table name: news_posts
#
# id :bigint not null, primary key
# body :text
# draft :boolean default(FALSE), not null
# end_date :datetime
# note :text
# position :integer
# start_date :datetime
# title :text
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# required_role_id :bigint default(1), not null
# user_id :bigint not null
#
# Indexes
#
# index_news_posts_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (required_role_id => roles.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/ndla_record.rb | app/models/ndla_record.rb | class NdlaRecord < ApplicationRecord
belongs_to :agent
validates :body, presence: true, uniqueness: true
end
# == Schema Information
#
# Table name: ndla_records
#
# id :bigint not null, primary key
# body :string not null
# created_at :datetime not null
# updated_at :datetime not null
# agent_id :bigint
#
# Indexes
#
# index_ndla_records_on_agent_id (agent_id)
# index_ndla_records_on_body (body) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (agent_id => agents.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/bookmark_stat.rb | app/models/bookmark_stat.rb | class BookmarkStat < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: UserCheckoutStatTransition,
initial_state: UserCheckoutStatStateMachine.initial_state
]
include CalculateStat
default_scope { order("bookmark_stats.id DESC") }
scope :not_calculated, -> { in_state(:pending) }
has_many :bookmark_stat_has_manifestations, dependent: :destroy
has_many :manifestations, through: :bookmark_stat_has_manifestations
paginates_per 10
has_many :bookmark_stat_transitions, autosave: false, dependent: :destroy
def state_machine
BookmarkStatStateMachine.new(self, transition_class: BookmarkStatTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def calculate_count!
self.started_at = Time.zone.now
Manifestation.find_each do |manifestation|
daily_count = Bookmark.manifestations_count(start_date, end_date, manifestation)
# manifestation.update_attributes({:daily_bookmarks_count => daily_count, :total_count => manifestation.total_count + daily_count})
if daily_count > 0
self.manifestations << manifestation
sql = [ "UPDATE bookmark_stat_has_manifestations SET bookmarks_count = ? WHERE bookmark_stat_id = ? AND manifestation_id = ?", daily_count, self.id, manifestation.id ]
ActiveRecord::Base.connection.execute(
self.class.send(:sanitize_sql_array, sql)
)
end
end
self.completed_at = Time.zone.now
transition_to!(:completed)
end
private
def self.transition_class
BookmarkStatTransition
end
def self.initial_state
:pending
end
end
# == Schema Information
#
# Table name: bookmark_stats
#
# id :bigint not null, primary key
# start_date :datetime
# end_date :datetime
# started_at :datetime
# completed_at :datetime
# note :text
# created_at :datetime not null
# updated_at :datetime not null
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/loc_search.rb | app/models/loc_search.rb | class LocSearch
def initialize(node)
@node = node
end
class ModsRecord < LocSearch
MODS_NS = { "mods" => "http://www.loc.gov/mods/v3" }
def title
title = @node.xpath(".//mods:titleInfo/mods:title", MODS_NS).first.content
subtitle = @node.xpath(".//mods:titleInfo/mods:subTitle", MODS_NS).first
title += " : #{subtitle.content}" if subtitle
title
end
def lccn
@node.xpath('.//mods:mods/mods:identifier[@type="lccn"]', MODS_NS).first.try(:content)
end
def isbn
@node.xpath('.//mods:mods/mods:identifier[@type="isbn"]', MODS_NS).first.try(:content)
end
def creator
statement_of_responsibility = @node.at('.//mods:note[@type="statement of responsibility"]', MODS_NS).try(:content)
if statement_of_responsibility
statement_of_responsibility
else
names = @node.xpath(".//mods:name", MODS_NS)
creator = names.map do |name|
name.xpath(".//mods:namePart", MODS_NS).map do |part|
if part.content
part.content
else
nil
end
end.compact.join(", ")
end.join(" ; ")
creator
end
end
def publisher
@node.xpath(".//mods:publisher", MODS_NS).map do |e|
e.content
end.join(", ")
end
def pubyear
@node.xpath(".//mods:dateIssued", MODS_NS).first.try(:content)
end
end
class DCRecord < LocSearch
DC_NS = { "dc" => "http://purl.org/dc/elements/1.1/" }
def title
@node.xpath(".//dc:title", DC_NS).first.content
end
def lccn
@node.xpath('.//dc:identifier[@type="lccn"]', DC_NS).first.content
end
def creator
end
end
# http://www.loc.gov/z3950/lcserver.html
LOC_SRU_BASEURL = "http://lx2.loc.gov:210/LCDB".freeze
def self.make_sru_request_uri(query, options = {})
if options[:page]
page = options[:page].to_i
options[:startRecord] = (page - 1) * 10 + 1
options.delete :page
end
options = { maximumRecords: 10, recordSchema: :mods }.merge(options)
options = options.merge({ query: query, version: "1.1", operation: "searchRetrieve" })
params = options.map do |k, v|
"#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}"
end.join("&")
"#{LOC_SRU_BASEURL}?#{params}"
end
def self.search(query, options = {})
if query.present?
url = make_sru_request_uri(query, options)
doc = Nokogiri::XML(Faraday.get(url).body)
items = doc.search("//zs:record").map { |e| ModsRecord.new e }
@results = { items: items,
total_entries: doc.xpath("//zs:numberOfRecords").first.try(:content).to_i }
else
{ items: [], total_entries: 0 }
end
end
def self.import_from_sru_response(lccn)
lccn_record = LccnRecord.find_by(body: lccn)
return if lccn_record
url = make_sru_request_uri("bath.lccn=\"^#{lccn}\"")
response = Nokogiri::XML(Faraday.get(url).body)
record = response.at("//zs:recordData", { "zs" => "http://www.loc.gov/zing/srw/" })
return unless record.try(:content)
doc = Nokogiri::XML::Document.new
doc << record.at("//mods:mods", { "mods" => "http://www.loc.gov/mods/v3" })
Manifestation.import_record_from_loc(doc)
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/agent_import_result.rb | app/models/agent_import_result.rb | class AgentImportResult < ApplicationRecord
default_scope { order("agent_import_results.id") }
scope :file_id, proc { |file_id| where(agent_import_file_id: file_id) }
scope :failed, -> { where(agent_id: nil) }
belongs_to :agent_import_file
belongs_to :agent, optional: true
end
# == Schema Information
#
# Table name: agent_import_results
#
# id :bigint not null, primary key
# agent_import_file_id :bigint
# agent_id :bigint
# body :text
# created_at :datetime not null
# updated_at :datetime not null
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/realize_type.rb | app/models/realize_type.rb | class RealizeType < ApplicationRecord
include MasterModel
default_scope { order("realize_types.position") }
end
# == Schema Information
#
# Table name: realize_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_realize_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resourcesync.rb | app/models/resourcesync.rb | class Resourcesync
def initialize
@base_url = if ENV["ENJU_LEAF_RESOURCESYNC_BASE_URL"].present?
URI.parse(ENV["ENJU_LEAF_RESOURCESYNC_BASE_URL"]).to_s
else
URI.parse(ENV["ENJU_LEAF_BASE_URL"]).to_s
end
end
def generate_capabilitylist
capabilitylist = Resync::CapabilityList.new(
links: [ Resync::Link.new(rel: "up", uri: @base_url) ],
resources: [
Resync::Resource.new(uri: "#{@base_url}/resourcelist.xml", metadata: Resync::Metadata.new(capability: "resourcelist")),
Resync::Resource.new(uri: "#{@base_url}/changelist.xml", metadata: Resync::Metadata.new(capability: "changelist"))
]
)
capabilitylist.save_to_xml
end
def generate_resourcelist_index(manifestations)
last_updated = manifestations.order(:updated_at).first&.updated_at
resourcelist_index = Resync::ResourceListIndex.new(
links: [ Resync::Link.new(rel: "up", uri: "#{@base_url}/capabilitylist.xml") ],
metadata: Resync::Metadata.new(
capability: "resourcelist",
from_time: manifestations.order(:updated_at).pick(:updated_at)
),
resources: ((manifestations.count / 50000) + 1).times.map do |i|
Resync::Resource.new(
uri: URI.parse("#{@base_url}/resourcelist_#{i}.xml").to_s,
modified_time: Time.zone.now
)
end
)
resourcelist_index.save_to_xml
end
def generate_resourcelist(manifestations)
xml_lists = []
last_updated = manifestations.order(:updated_at).first&.updated_at
manifestations.find_in_batches(batch_size: 50000).with_index do |works, i|
resourcelist = Resync::ResourceList.new(
links: [ Resync::Link.new(rel: "up", uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s) ],
metadata: Resync::Metadata.new(
capability: "resourcelist",
from_time: last_updated
),
resources: works.map { |m|
Resync::Resource.new(
uri: "#{@base_url}/manifestations/#{m.id}",
modified_time: m.updated_at
)
}
)
xml_lists << resourcelist.save_to_xml
end
xml_lists
end
def generate_changelist_index(manifestations)
last_updated = manifestations.order(:updated_at).first&.updated_at
changelist_index = Resync::ChangeListIndex.new(
links: [ Resync::Link.new(rel: "up", uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s) ],
metadata: Resync::Metadata.new(
capability: "changelist",
from_time: manifestations.order(:updated_at).pick(:updated_at)
),
resources: ((manifestations.count / 50000) + 1).times.map do |i|
Resync::Resource.new(
uri: URI.parse("#{@base_url}/changelist_#{i}.xml").to_s,
modified_time: Time.zone.now
)
end
)
changelist_index.save_to_xml
end
def generate_changelist(manifestations)
xml_lists = []
last_updated = manifestations.order(:updated_at).first&.updated_at
manifestations.find_in_batches(batch_size: 50000).with_index do |works, i|
changelist = Resync::ChangeList.new(
links: [ Resync::Link.new(rel: "up", uri: URI.parse("#{@base_url}/capabilitylist.xml").to_s) ],
metadata: Resync::Metadata.new(
capability: "changelist",
from_time: last_updated
),
resources: works.map { |m|
Resync::Resource.new(
uri: "#{@base_url}/manifestations/#{m.id}",
modified_time: m.updated_at,
metadata: Resync::Metadata.new(
change: Resync::Types::Change::UPDATED,
# datetime: m.updated_at
)
)
}
)
xml_lists << changelist.save_to_xml
end
xml_lists
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_import_file_transition.rb | app/models/user_import_file_transition.rb | class UserImportFileTransition < ApplicationRecord
belongs_to :user_import_file, inverse_of: :user_import_file_transitions
end
# == Schema Information
#
# Table name: user_import_file_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# user_import_file_id :bigint
#
# Indexes
#
# index_user_import_file_transitions_on_sort_key_and_file_id (sort_key,user_import_file_id) UNIQUE
# index_user_import_file_transitions_on_user_import_file_id (user_import_file_id)
# index_user_import_file_transitions_parent_most_recent (user_import_file_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/color.rb | app/models/color.rb | class Color < ApplicationRecord
belongs_to :library_group
validates :code, presence: true, format: /\A[A-Fa-f0-9]{6}\Z/
validates :property, presence: true, uniqueness: true, format: /\A[a-z][0-9a-z_]*[0-9a-z]\Z/
acts_as_list
end
# == Schema Information
#
# Table name: colors
#
# id :bigint not null, primary key
# code :string
# position :integer
# property :string
# created_at :datetime not null
# updated_at :datetime not null
# library_group_id :bigint
#
# Indexes
#
# index_colors_on_library_group_id (library_group_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/event_export_file_state_machine.rb | app/models/event_export_file_state_machine.rb | class EventExportFileStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
state :failed
transition from: :pending, to: :started
transition from: :started, to: [ :completed, :failed ]
after_transition(from: :pending, to: :started) do |event_export_file|
event_export_file.update_column(:executed_at, Time.zone.now)
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/checked_item.rb | app/models/checked_item.rb | class CheckedItem < ApplicationRecord
belongs_to :item, optional: true
belongs_to :basket
belongs_to :librarian, class_name: "User", optional: true
validates_associated :item, :basket, on: :update
validates :item, :basket, :due_date, presence: { on: :update }
validates :item_id, uniqueness: { scope: :basket_id }
validate :available_for_checkout?, on: :create
validates :due_date_string, format: { with: /\A\[{0,1}\d+([\/-]\d{0,2}){0,2}\]{0,1}\z/ }, allow_blank: true
validate :check_due_date
before_validation :set_item
before_validation :set_due_date, on: :create
strip_attributes only: :item_identifier
# attr_protected :user_id
attr_accessor :item_identifier, :ignore_restriction, :due_date_string
def available_for_checkout?
if item.blank?
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.item_not_found"))
return false
end
if item.rent?
unless item.circulation_status.name == "Missing"
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.already_checked_out"))
end
end
unless item.available_for_checkout?
if item.circulation_status.name == "Missing"
item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf")
item.save
set_due_date
else
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.not_available_for_checkout"))
return false
end
end
if item_checkout_type.blank?
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.this_group_cannot_checkout"))
return false
end
# ここまでは絶対に貸出ができない場合
return true if ignore_restriction == "1"
if item.not_for_loan?
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.not_available_for_checkout"))
end
if item.reserved?
unless item.manifestation.next_reservation.user == basket.user
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.reserved_item_included"))
end
end
checkout_count = basket.user.checked_item_count
checkout_type = item_checkout_type.checkout_type
if checkout_count[:"#{checkout_type.name}"] >= item_checkout_type.checkout_limit
errors.add(:base, I18n.t("activerecord.errors.messages.checked_item.excessed_checkout_limit"))
end
if errors[:base].empty?
true
else
false
end
end
def item_checkout_type
if item && basket
basket.user.profile.user_group.user_group_has_checkout_types.available_for_item(item).first
end
end
def set_due_date
return nil unless item_checkout_type
if due_date_string.present?
date = Time.zone.parse(due_date_string).try(:end_of_day)
else
# 返却期限日が閉館日の場合
if item.shelf.library.closed?(item_checkout_type.checkout_period.days.from_now)
if item_checkout_type.set_due_date_before_closing_day
date = (item_checkout_type.checkout_period - 1).days.from_now.end_of_day
else
date = (item_checkout_type.checkout_period + 1).days.from_now.end_of_day
end
else
date = (item_checkout_type.checkout_period + 1).days.from_now.end_of_day
end
end
self.due_date = date
due_date
end
def set_item
identifier = item_identifier.to_s.strip
if identifier.present?
item = Item.find_by(item_identifier: identifier)
self.item = item
end
end
private
def check_due_date
return nil unless due_date
if due_date <= Time.zone.now
errors.add(:due_date)
end
end
end
# == Schema Information
#
# Table name: checked_items
#
# id :bigint not null, primary key
# due_date :datetime not null
# created_at :datetime not null
# updated_at :datetime not null
# basket_id :bigint not null
# item_id :bigint not null
# librarian_id :bigint
# user_id :bigint
#
# Indexes
#
# index_checked_items_on_basket_id (basket_id)
# index_checked_items_on_item_id_and_basket_id (item_id,basket_id) UNIQUE
# index_checked_items_on_librarian_id (librarian_id)
# index_checked_items_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (basket_id => baskets.id)
# fk_rails_... (item_id => items.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/carrier_type.rb | app/models/carrier_type.rb | class CarrierType < ApplicationRecord
include MasterModel
include EnjuCirculation::EnjuCarrierType
has_many :manifestations, dependent: :restrict_with_exception
has_one_attached :attachment
before_save do
attachment.purge if delete_attachment == "1"
end
attr_accessor :delete_attachment
def mods_type
case name
when "volume"
"text"
else
# TODO: その他のタイプ
"software, multimedia"
end
end
end
# == Schema Information
#
# Table name: carrier_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_carrier_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation_relationship.rb | app/models/manifestation_relationship.rb | class ManifestationRelationship < ApplicationRecord
belongs_to :parent, class_name: "Manifestation"
belongs_to :child, class_name: "Manifestation"
belongs_to :manifestation_relationship_type, optional: true
validate :check_parent
acts_as_list scope: :parent_id
def check_parent
if parent_id == child_id
errors.add(:parent)
errors.add(:child)
end
end
end
# == Schema Information
#
# Table name: manifestation_relationships
#
# id :bigint not null, primary key
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# child_id :bigint
# manifestation_relationship_type_id :bigint
# parent_id :bigint
#
# Indexes
#
# index_manifestation_relationships_on_child_id (child_id)
# index_manifestation_relationships_on_parent_id (parent_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/bookmark_stat_transition.rb | app/models/bookmark_stat_transition.rb | class BookmarkStatTransition < ApplicationRecord
belongs_to :bookmark_stat, inverse_of: :bookmark_stat_transitions
end
# == Schema Information
#
# Table name: bookmark_stat_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# bookmark_stat_id :bigint
#
# Indexes
#
# index_bookmark_stat_transitions_on_bookmark_stat_id (bookmark_stat_id)
# index_bookmark_stat_transitions_on_sort_key_and_stat_id (sort_key,bookmark_stat_id) UNIQUE
# index_bookmark_stat_transitions_parent_most_recent (bookmark_stat_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/message.rb | app/models/message.rb | class Message < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: MessageTransition,
initial_state: MessageStateMachine.initial_state
]
scope :unread, -> { in_state("unread") }
belongs_to :sender, class_name: "User"
belongs_to :receiver, class_name: "User"
validates :subject, :body, presence: true # , :sender
validates :receiver, presence: { message: :invalid }
before_validation :set_receiver
after_create :send_notification
after_create :set_default_state
after_destroy :remove_from_index
after_save :index!
acts_as_nested_set
attr_accessor :recipient
validates :recipient, presence: true, on: :create
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
searchable do
text :body, :subject
string :subject
integer :receiver_id
integer :sender_id
time :created_at
boolean :is_read do
read?
end
end
paginates_per 10
has_many :message_transitions, autosave: false, dependent: :destroy
def state_machine
@state_machine ||= MessageStateMachine.new(self, transition_class: MessageTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def set_receiver
if recipient
self.receiver = User.find_by(username: recipient)
end
end
def send_notification
Notifier.message_notification(id).deliver_later if receiver.try(:email).present?
end
def read
transition_to!(:read)
end
def read?
return true if current_state == "read"
false
end
private
def set_default_state
transition_to!(:unread)
end
end
# == Schema Information
#
# Table name: messages
#
# id :bigint not null, primary key
# body :text
# depth :integer
# lft :integer
# read_at :datetime
# rgt :integer
# subject :string not null
# created_at :datetime not null
# updated_at :datetime not null
# message_request_id :bigint
# parent_id :bigint
# receiver_id :bigint
# sender_id :bigint
#
# Indexes
#
# index_messages_on_message_request_id (message_request_id)
# index_messages_on_parent_id (parent_id)
# index_messages_on_receiver_id (receiver_id)
# index_messages_on_sender_id (sender_id)
#
# Foreign Keys
#
# fk_rails_... (parent_id => messages.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_checkout_stat_state_machine.rb | app/models/user_checkout_stat_state_machine.rb | class UserCheckoutStatStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
transition from: :pending, to: :started
transition from: :started, to: :completed
after_transition(to: :started) do |user_checkout_stat|
user_checkout_stat.update_column(:started_at, Time.zone.now)
user_checkout_stat.calculate_count!
end
after_transition(to: :completed) do |user_checkout_stat|
user_checkout_stat.update_column(:completed_at, Time.zone.now)
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/reserve_state_machine.rb | app/models/reserve_state_machine.rb | class ReserveStateMachine
include Statesman::Machine
state :pending, initial: true
state :postponed
state :requested
state :retained
state :canceled
state :expired
state :completed
transition from: :pending, to: [ :requested ]
transition from: :postponed, to: [ :requested, :retained, :canceled, :expired ]
transition from: :retained, to: [ :postponed, :canceled, :expired, :completed ]
transition from: :requested, to: [ :retained, :canceled, :expired, :completed ]
after_transition(to: :requested) do |reserve|
reserve.update(request_status_type: RequestStatusType.find_by(name: "In Process"), item_id: nil, retained_at: nil)
end
after_transition(to: :retained) do |reserve|
# TODO: 「取り置き中」の状態を正しく表す
reserve.update(request_status_type: RequestStatusType.find_by(name: "In Process"), retained_at: Time.zone.now)
Reserve.transaction do
if reserve.item
other_reserves = reserve.item.reserves.waiting
other_reserves.each { |r|
next unless r != reserve
r.transition_to!(:postponed)
r.update!(item: nil)
}
end
end
end
after_transition(to: :canceled) do |reserve|
Reserve.transaction do
reserve.update(request_status_type: RequestStatusType.find_by(name: "Cannot Fulfill Request"), canceled_at: Time.zone.now)
next_reserve = reserve.next_reservation
if next_reserve
next_reserve.item = reserve.item
reserve.update!(item: nil)
next_reserve.transition_to!(:retained)
end
end
end
after_transition(to: :expired) do |reserve|
Reserve.transaction do
reserve.manifestation.reload
reserve.update(request_status_type: RequestStatusType.find_by(name: "Expired"), canceled_at: Time.zone.now)
next_reserve = reserve.next_reservation
if next_reserve
next_reserve.item = reserve.item
next_reserve.transition_to!(:retained)
reserve.update!(item: nil)
end
end
Rails.logger.info "#{Time.zone.now} reserve_id #{reserve.id} expired!"
end
after_transition(to: :postponed) do |reserve|
reserve.update(item_id: nil, retained_at: nil, postponed_at: Time.zone.now, force_retaining: "1")
end
after_transition(to: :completed) do |reserve|
reserve.update(
request_status_type: RequestStatusType.find_by(name: "Available For Pickup"),
checked_out_at: Time.zone.now
)
end
after_transition(to: :requested) do |reserve|
reserve.send_message
end
after_transition(to: :expired) do |reserve|
reserve.send_message
end
after_transition(to: :postponed) do |reserve|
reserve.send_message
end
after_transition(to: :canceled) do |reserve|
reserve.send_message
end
after_transition(to: :retained) do |reserve|
reserve.send_message
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resource_import_file_state_machine.rb | app/models/resource_import_file_state_machine.rb | class ResourceImportFileStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
state :failed
transition from: :pending, to: [ :started, :failed ]
transition from: :started, to: [ :completed, :failed ]
after_transition(from: :pending, to: :started) do |resource_import_file|
resource_import_file.update_column(:executed_at, Time.zone.now)
end
before_transition(from: :started, to: :completed) do |resource_import_file|
# resource_import_file.error_message = nil
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/event_import_file.rb | app/models/event_import_file.rb | class EventImportFile < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: EventImportFileTransition,
initial_state: EventImportFileStateMachine.initial_state
]
include ImportFile
scope :not_imported, -> { in_state(:pending) }
scope :stucked, -> { in_state(:pending).where("event_import_files.created_at < ?", 1.hour.ago) }
has_one_attached :attachment
belongs_to :user
belongs_to :default_library, class_name: "Library", optional: true
belongs_to :default_event_category, class_name: "EventCategory", optional: true
has_many :event_import_results, dependent: :destroy
has_many :event_import_file_transitions, autosave: false, dependent: :destroy
attr_accessor :mode
def state_machine
EventImportFileStateMachine.new(self, transition_class: EventImportFileTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def import
transition_to!(:started)
num = { imported: 0, failed: 0 }
rows = open_import_file(create_import_temp_file(attachment))
check_field(rows.first)
row_num = 1
rows.each do |row|
row_num += 1
next if row["dummy"].to_s.strip.present?
event_import_result = EventImportResult.new(event_import_file_id: id, body: row.fields.join("\t"))
event = Event.new
event.name = row["name"].to_s.strip
event.display_name = row["display_name"]
event.note = row["note"]
event.start_at = Time.zone.parse(row["start_at"]) if row["start_at"].present?
event.end_at = Time.zone.parse(row["end_at"]) if row["end_at"].present?
category = row["event_category"].to_s.strip
if %w[t true TRUE].include?(row["all_day"].to_s.strip)
event.all_day = true
else
event.all_day = false
end
library = Library.find_by(name: row["library"])
library = default_library || Library.web if library.blank?
event.library = library
event_category = EventCategory.find_by(name: row["event_category"])
event_category = default_event_category if event_category.blank?
event.event_category = event_category
if event.save
event_import_result.event = event
num[:imported] += 1
else
num[:failed] += 1
end
event_import_result.save!
end
Sunspot.commit
rows.close
transition_to!(:completed)
mailer = EventImportMailer.completed(self)
send_message(mailer)
num
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = EventImportMailer.failed(self)
send_message(mailer)
raise e
end
def modify
transition_to!(:started)
rows = open_import_file(create_import_temp_file(attachment))
check_field(rows.first)
row_num = 1
rows.each do |row|
row_num += 1
next if row["dummy"].to_s.strip.present?
event = Event.find(row["id"].to_s.strip)
event_category = EventCategory.find_by(name: row["event_category"].to_s.strip)
event.event_category = event_category if event_category
library = Library.find_by(name: row["library"].to_s.strip)
event.library = library if library
event.name = row["name"] if row["name"].to_s.strip.present?
event.start_at = Time.zone.parse(row["start_at"]) if row["start_at"].present?
event.end_at = Time.zone.parse(row["end_at"]) if row["end_at"].present?
event.note = row["note"] if row["note"].to_s.strip.present?
if %w[t true TRUE].include?(row["all_day"].to_s.strip)
event.all_day = true
else
event.all_day = false
end
event.save!
end
transition_to!(:completed)
mailer = EventImportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = EventImportMailer.failed(self)
send_message(mailer)
raise e
end
def remove
transition_to!(:started)
rows = open_import_file(create_import_temp_file(attachment))
rows.shift
row_num = 1
rows.each do |row|
row_num += 1
next if row["dummy"].to_s.strip.present?
event = Event.find(row["id"].to_s.strip)
event.picture_files.destroy_all # workaround
event.reload
event.destroy
end
transition_to!(:completed)
mailer = EventImportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
self.error_message = "line #{row_num}: #{e.message}"
save
transition_to!(:failed)
mailer = EventImportMailer.failed(self)
send_message(mailer)
raise e
end
def self.import
EventImportFile.not_imported.each do |file|
file.import_start
end
rescue StandardError
Rails.logger.info "#{Time.zone.now} importing events failed!"
end
private
def open_import_file(tempfile)
file = CSV.open(tempfile, col_sep: "\t")
header_columns = EventImportResult.header
header = file.first
ignored_columns = header - header_columns
unless ignored_columns.empty?
self.error_message = I18n.t("import.following_column_were_ignored", column: ignored_columns.join(", "))
save!
end
rows = CSV.open(tempfile, headers: header, col_sep: "\t")
event_import_result = EventImportResult.new
event_import_result.assign_attributes({ event_import_file_id: id, body: header.join("\t") })
event_import_result.save!
tempfile.close(true)
file.close
rows
end
def check_field(field)
if [ field["name"] ].reject { |f| f.to_s.strip == "" }.empty?
raise "You should specify a name in the first line"
end
if [ field["start_at"], field["end_at"] ].reject { |f| f.to_s.strip == "" }.empty?
raise "You should specify dates in the first line"
end
end
end
# == Schema Information
#
# Table name: event_import_files
#
# id :bigint not null, primary key
# edit_mode :string
# error_message :text
# event_import_fingerprint :string
# executed_at :datetime
# note :text
# user_encoding :string
# created_at :datetime not null
# updated_at :datetime not null
# default_event_category_id :bigint
# default_library_id :bigint
# parent_id :bigint
# user_id :bigint not null
#
# Indexes
#
# index_event_import_files_on_parent_id (parent_id)
# index_event_import_files_on_user_id (user_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/lccn_record.rb | app/models/lccn_record.rb | class LccnRecord < ApplicationRecord
belongs_to :manifestation
validates :body, presence: true, uniqueness: true
end
# == Schema Information
#
# Table name: lccn_records
#
# id :bigint not null, primary key
# body :string not null
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_lccn_records_on_body (body) UNIQUE
# index_lccn_records_on_manifestation_id (manifestation_id)
#
# Foreign Keys
#
# fk_rails_... (manifestation_id => manifestations.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_import_file_state_machine.rb | app/models/user_import_file_state_machine.rb | class UserImportFileStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
state :failed
transition from: :pending, to: [ :started, :failed ]
transition from: :started, to: [ :completed, :failed ]
after_transition(from: :pending, to: :started) do |user_import_file|
user_import_file.update_column(:executed_at, Time.zone.now)
end
before_transition(from: :started, to: :completed) do |user_import_file|
user_import_file.error_message = nil
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/classification_type.rb | app/models/classification_type.rb | class ClassificationType < ApplicationRecord
include MasterModel
has_many :classifications, dependent: :restrict_with_exception
validates :name, format: { with: /\A[0-9a-z][0-9a-z_\-]*[0-9a-z]\Z/ }
end
# == Schema Information
#
# Table name: classification_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_classification_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/application_record.rb | app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/bookmark_stat_has_manifestation.rb | app/models/bookmark_stat_has_manifestation.rb | class BookmarkStatHasManifestation < ApplicationRecord
belongs_to :bookmark_stat
belongs_to :manifestation
validates_uniqueness_of :manifestation_id, scope: :bookmark_stat_id
paginates_per 10
end
# == Schema Information
#
# Table name: bookmark_stat_has_manifestations
#
# id :bigint not null, primary key
# bookmarks_count :integer
# created_at :datetime not null
# updated_at :datetime not null
# bookmark_stat_id :bigint not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_bookmark_stat_has_manifestations_on_bookmark_stat_id (bookmark_stat_id)
# index_bookmark_stat_has_manifestations_on_manifestation_id (manifestation_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/create.rb | app/models/create.rb | class Create < ApplicationRecord
belongs_to :agent
belongs_to :work, class_name: "Manifestation", touch: true
belongs_to :create_type, optional: true
validates :work_id, uniqueness: { scope: :agent_id }
after_destroy :reindex
after_save :reindex
acts_as_list scope: :work
def reindex
agent.try(:index)
work.try(:index)
end
end
# == Schema Information
#
# Table name: creates
#
# id :bigint not null, primary key
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
# agent_id :bigint not null
# create_type_id :bigint
# work_id :bigint not null
#
# Indexes
#
# index_creates_on_agent_id (agent_id)
# index_creates_on_work_id_and_agent_id (work_id,agent_id) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/search_engine.rb | app/models/search_engine.rb | class SearchEngine < ApplicationRecord
acts_as_list
validates :name, presence: true
validates :query_param, presence: true
validates :http_method, presence: true, inclusion: %w[get post]
validates :url, presence: true, url: true, length: { maximum: 255 }
validates :base_url, presence: true, url: true, length: { maximum: 255 }
paginates_per 10
def search_params(query)
params = {}
if additional_param
additional_param.gsub("{query}", query).to_s.split.each do |param|
p = param.split("=")
params[p[0].to_sym] = p[1]
end
params
end
end
end
# == Schema Information
#
# Table name: search_engines
#
# id :bigint not null, primary key
# name :string not null
# display_name :text
# url :string not null
# base_url :text not null
# http_method :text not null
# query_param :text not null
# additional_param :text
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation_checkout_stat.rb | app/models/manifestation_checkout_stat.rb | class ManifestationCheckoutStat < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: ManifestationCheckoutStatTransition,
initial_state: ManifestationCheckoutStatStateMachine.initial_state
]
include CalculateStat
default_scope { order("manifestation_checkout_stats.id DESC") }
scope :not_calculated, -> { in_state(:pending) }
has_many :checkout_stat_has_manifestations, dependent: :destroy
has_many :manifestations, through: :checkout_stat_has_manifestations
belongs_to :user
paginates_per 10
attr_accessor :mode
has_many :manifestation_checkout_stat_transitions, autosave: false, dependent: :destroy
def state_machine
ManifestationCheckoutStatStateMachine.new(self, transition_class: ManifestationCheckoutStatTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def calculate_count!
self.started_at = Time.zone.now
Manifestation.find_each do |manifestation|
daily_count = Checkout.manifestations_count(start_date.beginning_of_day, end_date.tomorrow.beginning_of_day, manifestation)
# manifestation.update_attributes({daily_checkouts_count: daily_count, total_count: manifestation.total_count + daily_count})
if daily_count.positive?
manifestations << manifestation
sql = [ "UPDATE checkout_stat_has_manifestations SET checkouts_count = ? WHERE manifestation_checkout_stat_id = ? AND manifestation_id = ?", daily_count, id, manifestation.id ]
ManifestationCheckoutStat.connection.execute(
self.class.send(:sanitize_sql_array, sql)
)
end
end
self.completed_at = Time.zone.now
transition_to!(:completed)
mailer = ManifestationCheckoutStatMailer.completed(self)
mailer.deliver_later
send_message(mailer)
end
end
# == Schema Information
#
# Table name: manifestation_checkout_stats
#
# id :bigint not null, primary key
# completed_at :datetime
# end_date :datetime
# note :text
# start_date :datetime
# started_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_manifestation_checkout_stats_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/subscribe.rb | app/models/subscribe.rb | class Subscribe < ApplicationRecord
belongs_to :subscription, counter_cache: true
belongs_to :work, class_name: "Manifestation"
validates :start_at, :end_at, presence: true
validates :work_id, uniqueness: { scope: :subscription_id }
end
# == Schema Information
#
# Table name: subscribes
#
# id :bigint not null, primary key
# end_at :datetime not null
# start_at :datetime not null
# created_at :datetime not null
# updated_at :datetime not null
# subscription_id :bigint not null
# work_id :bigint not null
#
# Indexes
#
# index_subscribes_on_subscription_id (subscription_id)
# index_subscribes_on_work_id (work_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation_checkout_stat_transition.rb | app/models/manifestation_checkout_stat_transition.rb | class ManifestationCheckoutStatTransition < ApplicationRecord
belongs_to :manifestation_checkout_stat, inverse_of: :manifestation_checkout_stat_transitions
end
# == Schema Information
#
# Table name: manifestation_checkout_stat_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_checkout_stat_id :bigint
#
# Indexes
#
# index_manifestation_checkout_stat_transitions_on_stat_id (manifestation_checkout_stat_id)
# index_manifestation_checkout_stat_transitions_on_transition (sort_key,manifestation_checkout_stat_id) UNIQUE
# index_manifestation_checkout_stat_transitions_parent_most_rece (manifestation_checkout_stat_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/inventory_file.rb | app/models/inventory_file.rb | class InventoryFile < ApplicationRecord
has_many :inventories, dependent: :destroy
has_many :items, through: :inventories
belongs_to :user
belongs_to :shelf, optional: true
has_one_attached :attachment
attr_accessor :library_id
paginates_per 10
def import
reload
reader = attachment.download
reader.split.each do |row|
identifier = row.to_s.strip
item = Item.find_by(item_identifier: identifier)
next unless item
next if self.items.where(id: item.id).select("items.id").first
Inventory.create(
inventory_file: self,
item: item,
current_shelf_name: shelf.name,
item_identifier: identifier
)
end
true
end
def export(col_sep: "\t")
file = Tempfile.create("inventory_file") do |f|
inventories.each do |inventory|
f.write inventory.to_hash.values.to_csv(col_sep)
end
f.rewind
f.read
end
file
end
def missing_items
Item.where(Inventory.where("items.id = inventories.item_id AND inventories.inventory_file_id = ?", id).exists.not)
end
def found_items
items
end
end
# == Schema Information
#
# Table name: inventory_files
#
# id :bigint not null, primary key
# inventory_fingerprint :string
# note :text
# created_at :datetime not null
# updated_at :datetime not null
# shelf_id :bigint
# user_id :bigint not null
#
# Indexes
#
# index_inventory_files_on_shelf_id (shelf_id)
# index_inventory_files_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (shelf_id => shelves.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/series_statement_merge.rb | app/models/series_statement_merge.rb | class SeriesStatementMerge < ApplicationRecord
belongs_to :series_statement
belongs_to :series_statement_merge_list
paginates_per 10
end
# == Schema Information
#
# Table name: series_statement_merges
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# series_statement_id :bigint not null
# series_statement_merge_list_id :bigint not null
#
# Indexes
#
# index_series_statement_merges_on_list_id (series_statement_merge_list_id)
# index_series_statement_merges_on_series_statement_id (series_statement_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/event_import_file_transition.rb | app/models/event_import_file_transition.rb | class EventImportFileTransition < ApplicationRecord
belongs_to :event_import_file, inverse_of: :event_import_file_transitions
end
# == Schema Information
#
# Table name: event_import_file_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# event_import_file_id :bigint
#
# Indexes
#
# index_event_import_file_transitions_on_event_import_file_id (event_import_file_id)
# index_event_import_file_transitions_on_sort_key_and_file_id (sort_key,event_import_file_id) UNIQUE
# index_event_import_file_transitions_parent_most_recent (event_import_file_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_export_file_state_machine.rb | app/models/user_export_file_state_machine.rb | class UserExportFileStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
state :failed
transition from: :pending, to: [ :started, :failed ]
transition from: :started, to: [ :completed, :failed ]
after_transition(from: :pending, to: :started) do |user_export_file|
user_export_file.update_column(:executed_at, Time.zone.now)
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resource_import_file_transition.rb | app/models/resource_import_file_transition.rb | class ResourceImportFileTransition < ApplicationRecord
belongs_to :resource_import_file, inverse_of: :resource_import_file_transitions
end
# == Schema Information
#
# Table name: resource_import_file_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# resource_import_file_id :bigint
#
# Indexes
#
# index_resource_import_file_transitions_on_file_id (resource_import_file_id)
# index_resource_import_file_transitions_on_sort_key_and_file_id (sort_key,resource_import_file_id) UNIQUE
# index_resource_import_file_transitions_parent_most_recent (resource_import_file_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/event_export_file.rb | app/models/event_export_file.rb | class EventExportFile < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: EventExportFileTransition,
initial_state: EventExportFileStateMachine.initial_state
]
include ExportFile
has_one_attached :attachment
has_many :event_export_file_transitions, autosave: false
def state_machine
EventExportFileStateMachine.new(self, transition_class: EventExportFileTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def export!
role_name = user.try(:role).try(:name)
tsv = Event.export(role: role_name)
EventExportFile.transaction do
transition_to!(:started)
role_name = user.try(:role).try(:name)
attachment.attach(io: StringIO.new(tsv), filename: "event_export.txt")
save!
transition_to!(:completed)
end
mailer = EventExportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
transition_to!(:failed)
mailer = EventExportMailer.failed(self)
send_message(mailer)
raise e
end
end
# == Schema Information
#
# Table name: event_export_files
#
# id :bigint not null, primary key
# executed_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_event_export_files_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/profile.rb | app/models/profile.rb | class Profile < ApplicationRecord
include EnjuCirculation::EnjuProfile
scope :administrators, -> { joins(user: :role).where("roles.name = ?", "Administrator") }
scope :librarians, -> { joins(user: :role).where("roles.name = ? OR roles.name = ?", "Administrator", "Librarian") }
has_one :user, dependent: :destroy, inverse_of: :profile
belongs_to :library
belongs_to :user_group
belongs_to :required_role, class_name: "Role"
has_many :identities, dependent: :destroy
has_many :agents, dependent: :nullify
accepts_nested_attributes_for :identities, allow_destroy: true, reject_if: :all_blank
validates :locale, presence: true
validates :user_number, uniqueness: true, format: { with: /\A[0-9A-Za-z_]+\z/ }, allow_blank: true
validates :birth_date, format: { with: /\A\d{4}-\d{1,2}-\d{1,2}\z/ }, allow_blank: true
strip_attributes only: :user_number
attr_accessor :birth_date
searchable do
text :user_number, :full_name, :full_name_transcription, :note
string :user_number
text :username do
user.try(:username)
end
text :email do
user.try(:email)
end
string :username do
user.try(:username)
end
string :email do
user.try(:email)
end
time :created_at
time :updated_at
boolean :active do
user.try(:active_for_authentication?)
end
integer :required_role_id
end
before_validation :set_role_and_agent, on: :create
before_save :set_expired_at, :set_date_of_birth
accepts_nested_attributes_for :user
# 既定のユーザ権限を設定します。
# @return [void]
def set_role_and_agent
self.required_role = Role.find_by(name: "Librarian") unless required_role
self.locale = I18n.default_locale.to_s unless locale
end
# ユーザの有効期限を設定します。
# @return [Time]
def set_expired_at
if expired_at.blank?
if user_group.valid_period_for_new_user.positive?
self.expired_at = user_group.valid_period_for_new_user.days.from_now.end_of_day
end
end
end
# ユーザの誕生日を設定します。
# @return [Time]
def set_date_of_birth
self.date_of_birth = Time.zone.parse(birth_date) if birth_date
rescue ArgumentError
nil
end
end
# == Schema Information
#
# Table name: profiles
#
# id :bigint not null, primary key
# checkout_icalendar_token :string
# date_of_birth :datetime
# expired_at :datetime
# full_name :text
# full_name_transcription :text
# keyword_list :text
# locale :string
# note :text
# save_checkout_history :boolean default(FALSE), not null
# share_bookmarks :boolean
# user_number :string
# created_at :datetime not null
# updated_at :datetime not null
# library_id :bigint
# required_role_id :bigint
# user_group_id :bigint
#
# Indexes
#
# index_profiles_on_checkout_icalendar_token (checkout_icalendar_token) UNIQUE
# index_profiles_on_library_id (library_id)
# index_profiles_on_user_group_id (user_group_id)
# index_profiles_on_user_number (user_number) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (required_role_id => roles.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_group_has_checkout_type.rb | app/models/user_group_has_checkout_type.rb | class UserGroupHasCheckoutType < ApplicationRecord
scope :available_for_item, lambda { |item| where(checkout_type_id: item.checkout_type.id) }
scope :available_for_carrier_type, lambda { |carrier_type| includes(checkout_type: :carrier_types).where("carrier_types.id" => carrier_type.id) }
belongs_to :user_group
belongs_to :checkout_type
validates :checkout_type_id, uniqueness: { scope: :user_group_id }
validates :checkout_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :checkout_period, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :checkout_renewal_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :reservation_limit, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :reservation_expired_period, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
acts_as_list scope: :user_group_id
def self.update_current_checkout_count
sql = [
'SELECT count(checkouts.id) as current_checkout_count,
profiles.user_group_id,
items.checkout_type_id
FROM profiles, checkouts LEFT OUTER JOIN items
ON (checkouts.item_id = items.id)
LEFT OUTER JOIN users
ON (users.id = checkouts.user_id)
WHERE checkouts.checkin_id IS NULL
GROUP BY user_group_id, checkout_type_id;'
]
UserGroupHasCheckoutType.find_by_sql(sql).each do |result|
update_sql = [
'UPDATE user_group_has_checkout_types
SET current_checkout_count = ?
WHERE user_group_id = ? AND checkout_type_id = ?;',
result.current_checkout_count, result.user_group_id, result.checkout_type_id
]
ActiveRecord::Base.connection.execute(
send(:sanitize_sql_array, update_sql)
)
end
end
end
# == Schema Information
#
# Table name: user_group_has_checkout_types
#
# id :bigint not null, primary key
# checkout_limit :integer default(0), not null
# checkout_period :integer default(0), not null
# checkout_renewal_limit :integer default(0), not null
# current_checkout_count :integer
# fixed_due_date :datetime
# note :text
# position :integer
# reservation_expired_period :integer default(7), not null
# reservation_limit :integer default(0), not null
# set_due_date_before_closing_day :boolean default(FALSE), not null
# created_at :datetime not null
# updated_at :datetime not null
# checkout_type_id :bigint not null
# user_group_id :bigint not null
#
# Indexes
#
# index_user_group_has_checkout_types_on_checkout_type_id (checkout_type_id)
# index_user_group_has_checkout_types_on_user_group_id (user_group_id,checkout_type_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (checkout_type_id => checkout_types.id)
# fk_rails_... (user_group_id => user_groups.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/library_group.rb | app/models/library_group.rb | class LibraryGroup < ApplicationRecord
# include Singleton
include MasterModel
has_many :libraries, dependent: :destroy
has_many :colors, dependent: :destroy
belongs_to :country, optional: true
validates :url, presence: true, url: true
validates :short_name, presence: true
validates :max_number_of_results, numericality: {
greater_than_or_equal_to: 0
}
accepts_nested_attributes_for :colors, update_only: true
store_accessor :settings,
:book_jacket_unknown_resource
translates :login_banner, :footer_banner
globalize_accessors
has_one_attached :header_logo
attr_accessor :delete_header_logo
def self.site_config
LibraryGroup.order(:created_at).first
end
def self.system_name(locale = I18n.locale)
LibraryGroup.site_config.display_name.localize(locale)
end
def config?
true if self == LibraryGroup.site_config
end
def real_libraries
libraries.where.not(name: "web")
end
def network_access_allowed?(ip_address, options = {})
options = { network_type: :lan }.merge(options)
client_ip = IPAddr.new(ip_address)
case options[:network_type]
when :admin
allowed_networks = admin_networks.to_s.split
else
allowed_networks = my_networks.to_s.split
end
allowed_networks.each do |allowed_network|
network = IPAddr.new(allowed_network)
return true if network.include?(client_ip)
rescue ArgumentError
nil
end
false
end
end
# == Schema Information
#
# Table name: library_groups
#
# id :bigint not null, primary key
# admin_networks :text
# allow_bookmark_external_url :boolean default(FALSE), not null
# book_jacket_source :string
# csv_charset_conversion :boolean default(FALSE), not null
# display_name :text
# email :string
# family_name_first :boolean default(TRUE)
# footer_banner :text
# html_snippet :text
# login_banner :text
# max_number_of_results :integer default(1000)
# my_networks :text
# name :string not null
# note :text
# old_login_banner :text
# position :integer
# pub_year_facet_range_interval :integer default(10)
# screenshot_generator :string
# settings :jsonb not null
# short_name :string not null
# url :string default("http://localhost:3000/")
# created_at :datetime not null
# updated_at :datetime not null
# country_id :bigint
#
# Indexes
#
# index_library_groups_on_email (email)
# index_library_groups_on_lower_name (lower((name)::text)) UNIQUE
# index_library_groups_on_short_name (short_name)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/event_export_file_transition.rb | app/models/event_export_file_transition.rb | class EventExportFileTransition < ApplicationRecord
belongs_to :event_export_file, inverse_of: :event_export_file_transitions
end
# == Schema Information
#
# Table name: event_export_file_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# event_export_file_id :bigint
#
# Indexes
#
# index_event_export_file_transitions_on_file_id (event_export_file_id)
# index_event_export_file_transitions_on_sort_key_and_file_id (sort_key,event_export_file_id) UNIQUE
# index_event_export_file_transitions_parent_most_recent (event_export_file_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/withdraw.rb | app/models/withdraw.rb | class Withdraw < ApplicationRecord
include EnjuCirculation::EnjuWithdraw
belongs_to :basket
belongs_to :item, touch: true
belongs_to :librarian, class_name: "User"
validates :item_id,
uniqueness: true # { message: I18n.t('withdraw.already_withdrawn', locale: I18n.default_locale) }
attr_accessor :item_identifier
paginates_per 10
end
# == Schema Information
#
# Table name: withdraws
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# basket_id :bigint
# item_id :bigint
# librarian_id :bigint
#
# Indexes
#
# index_withdraws_on_basket_id (basket_id)
# index_withdraws_on_item_id (item_id) UNIQUE
# index_withdraws_on_librarian_id (librarian_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/order_list_transition.rb | app/models/order_list_transition.rb | class OrderListTransition < ApplicationRecord
belongs_to :order_list, inverse_of: :order_list_transitions
end
# == Schema Information
#
# Table name: order_list_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# order_list_id :integer
#
# Indexes
#
# index_order_list_transitions_on_order_list_id (order_list_id)
# index_order_list_transitions_on_sort_key_and_order_list_id (sort_key,order_list_id) UNIQUE
# index_order_list_transitions_parent_most_recent (order_list_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/reserve_transition.rb | app/models/reserve_transition.rb | class ReserveTransition < ApplicationRecord
belongs_to :reserve, inverse_of: :reserve_transitions
end
# == Schema Information
#
# Table name: reserve_transitions
#
# id :bigint not null, primary key
# metadata :jsonb not null
# most_recent :boolean not null
# sort_key :integer
# to_state :string
# created_at :datetime not null
# updated_at :datetime not null
# reserve_id :bigint
#
# Indexes
#
# index_reserve_transitions_on_reserve_id (reserve_id)
# index_reserve_transitions_on_sort_key_and_reserve_id (sort_key,reserve_id) UNIQUE
# index_reserve_transitions_parent_most_recent (reserve_id,most_recent) UNIQUE WHERE most_recent
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_has_role.rb | app/models/user_has_role.rb | class UserHasRole < ApplicationRecord
belongs_to :user
belongs_to :role
accepts_nested_attributes_for :role
end
# == Schema Information
#
# Table name: user_has_roles
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# role_id :bigint not null
# user_id :bigint not null
#
# Indexes
#
# index_user_has_roles_on_role_id (role_id)
# index_user_has_roles_on_user_id_and_role_id (user_id,role_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (role_id => roles.id)
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/role.rb | app/models/role.rb | class Role < ApplicationRecord
include MasterModel
validates :name, presence: true, format: { with: /\A[A-Za-z][a-z_,]*[a-z]\z/ }
has_many :user_has_roles, dependent: :destroy
has_many :users, through: :user_has_roles
extend FriendlyId
friendly_id :name
def localized_name
display_name.localize
end
def self.default
Role.find_by(name: "Guest")
end
private
def valid_name?
true
end
end
# == Schema Information
#
# Table name: roles
#
# id :bigint not null, primary key
# display_name :string
# name :string not null
# note :text
# position :integer
# score :integer default(0), not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_roles_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/issn_record.rb | app/models/issn_record.rb | class IssnRecord < ApplicationRecord
has_many :issn_record_and_manifestations, dependent: :destroy
has_many :manifestations, through: :issn_record_and_manifestations
validates :body, presence: true, uniqueness: true
before_save :normalize_issn
strip_attributes
def normalize_issn
if StdNum::ISSN.valid?(body)
self.body = StdNum::ISSN.normalize(body)
else
errors.add(:body)
end
end
def self.new_records(issn_records_params)
return [] unless issn_records_params
issn_records = []
IssnRecord.transaction do
issn_records_params.each do |k, v|
next if v["_destroy"] == "1"
if v["body"].present?
issn_record = IssnRecord.where(body: v["body"].gsub(/[^0-9x]/i, "")).first_or_create!
elsif v["id"].present?
issn_record = IssnRecord.find(v["id"])
else
v.delete("_destroy")
issn_record = IssnRecord.create(v)
end
issn_records << issn_record
end
end
issn_records
end
end
# == Schema Information
#
# Table name: issn_records(ISSN)
#
# id :bigint not null, primary key
# body(ISSN) :string not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_issn_records_on_body (body) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/doi_record.rb | app/models/doi_record.rb | class DoiRecord < ApplicationRecord
belongs_to :manifestation
validates :body, presence: true, uniqueness: true
end
# == Schema Information
#
# Table name: doi_records
#
# id :bigint not null, primary key
# body :string not null
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_doi_records_on_lower_body_manifestation_id (lower((body)::text), manifestation_id) UNIQUE
# index_doi_records_on_manifestation_id (manifestation_id)
#
# Foreign Keys
#
# fk_rails_... (manifestation_id => manifestations.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/user_export_file.rb | app/models/user_export_file.rb | class UserExportFile < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: UserExportFileTransition,
initial_state: UserExportFileStateMachine.initial_state
]
include ExportFile
has_one_attached :attachment
has_many :user_export_file_transitions, autosave: false, dependent: :destroy
def state_machine
UserExportFileStateMachine.new(self, transition_class: UserExportFileTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
# エクスポートの処理を実行します。
def export!
transition_to!(:started)
tempfile = Tempfile.new([ "user_export_file_", ".txt" ])
file = User.export(format: :text)
tempfile.puts(file)
tempfile.close
attachment.attach(io: File.new(tempfile.path, "r"), filename: "user_export.txt")
save!
transition_to!(:completed)
mailer = UserExportMailer.completed(self)
send_message(mailer)
rescue StandardError => e
transition_to!(:failed)
mailer = UserExportMailer.failed(self)
send_message(mailer)
rescue StandardError => e
raise e
end
end
# == Schema Information
#
# Table name: user_export_files
#
# id :bigint not null, primary key
# executed_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_user_export_files_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/item_custom_value.rb | app/models/item_custom_value.rb | class ItemCustomValue < ApplicationRecord
belongs_to :item_custom_property
belongs_to :item
validates :item_custom_property, uniqueness: { scope: :item_id }
end
# == Schema Information
#
# Table name: item_custom_values
#
# id :bigint not null, primary key
# value :text
# created_at :datetime not null
# updated_at :datetime not null
# item_custom_property_id :bigint not null
# item_id :bigint not null
#
# Indexes
#
# index_item_custom_values_on_custom_item_property_and_item_id (item_custom_property_id,item_id) UNIQUE
# index_item_custom_values_on_custom_property_id (item_custom_property_id)
# index_item_custom_values_on_item_id (item_id)
#
# Foreign Keys
#
# fk_rails_... (item_custom_property_id => item_custom_properties.id)
# fk_rails_... (item_id => items.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/item_has_use_restriction.rb | app/models/item_has_use_restriction.rb | class ItemHasUseRestriction < ApplicationRecord
belongs_to :item
belongs_to :use_restriction
accepts_nested_attributes_for :use_restriction
validates :item, presence: { on: :update }
paginates_per 10
end
# == Schema Information
#
# Table name: item_has_use_restrictions
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# item_id :bigint not null
# use_restriction_id :bigint not null
#
# Indexes
#
# index_item_has_use_restrictions_on_item_and_use_restriction (item_id,use_restriction_id) UNIQUE
# index_item_has_use_restrictions_on_use_restriction_id (use_restriction_id)
#
# Foreign Keys
#
# fk_rails_... (item_id => items.id)
# fk_rails_... (use_restriction_id => use_restrictions.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation_reserve_stat.rb | app/models/manifestation_reserve_stat.rb | class ManifestationReserveStat < ApplicationRecord
include Statesman::Adapters::ActiveRecordQueries[
transition_class: ManifestationReserveStatTransition,
initial_state: ManifestationReserveStatStateMachine.initial_state
]
include CalculateStat
default_scope { order("manifestation_reserve_stats.id DESC") }
scope :not_calculated, -> { in_state(:pending) }
has_many :reserve_stat_has_manifestations, dependent: :destroy
has_many :manifestations, through: :reserve_stat_has_manifestations
belongs_to :user
paginates_per 10
attr_accessor :mode
has_many :manifestation_reserve_stat_transitions, autosave: false, dependent: :destroy
def state_machine
ManifestationReserveStatStateMachine.new(self, transition_class: ManifestationReserveStatTransition)
end
delegate :can_transition_to?, :transition_to!, :transition_to, :current_state,
to: :state_machine
def calculate_count!
self.started_at = Time.zone.now
Manifestation.find_each do |manifestation|
daily_count = manifestation.reserves.created(start_date.beginning_of_day, end_date.tomorrow.beginning_of_day).size
# manifestation.update_attributes({daily_reserves_count: daily_count, total_count: manifestation.total_count + daily_count})
if daily_count.positive?
manifestations << manifestation
sql = [ "UPDATE reserve_stat_has_manifestations SET reserves_count = ? WHERE manifestation_reserve_stat_id = ? AND manifestation_id = ?", daily_count, id, manifestation.id ]
ManifestationReserveStat.connection.execute(
self.class.send(:sanitize_sql_array, sql)
)
end
end
self.completed_at = Time.zone.now
transition_to!(:completed)
mailer = ManifestationReserveStatMailer.completed(self)
mailer.deliver_later
send_message(mailer)
end
end
# == Schema Information
#
# Table name: manifestation_reserve_stats
#
# id :bigint not null, primary key
# completed_at :datetime
# end_date :datetime
# note :text
# start_date :datetime
# started_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_manifestation_reserve_stats_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/subject.rb | app/models/subject.rb | class Subject < ApplicationRecord
belongs_to :manifestation, touch: true, optional: true
belongs_to :subject_type
belongs_to :subject_heading_type
belongs_to :required_role, class_name: "Role"
validates :term, presence: true
searchable do
text :term
time :created_at
integer :required_role_id
end
strip_attributes only: :term
paginates_per 10
end
# == Schema Information
#
# Table name: subjects
#
# id :bigint not null, primary key
# lock_version :integer default(0), not null
# note :text
# scope_note :text
# term :string
# term_transcription :text
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint
# parent_id :bigint
# required_role_id :bigint default(1), not null
# subject_heading_type_id :bigint
# subject_type_id :bigint not null
# use_term_id :bigint
#
# Indexes
#
# index_subjects_on_manifestation_id (manifestation_id)
# index_subjects_on_parent_id (parent_id)
# index_subjects_on_required_role_id (required_role_id)
# index_subjects_on_subject_type_id (subject_type_id)
# index_subjects_on_term (term)
# index_subjects_on_use_term_id (use_term_id)
#
# Foreign Keys
#
# fk_rails_... (required_role_id => roles.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/inventory.rb | app/models/inventory.rb | class Inventory < ApplicationRecord
belongs_to :item, optional: true
belongs_to :inventory_file
validates :item_identifier, :current_shelf_name, presence: true
validates :item_id, :item_identifier, uniqueness: { scope: :inventory_file_id }
paginates_per 10
def to_hash
{
created_at: created_at,
identifier: item_identifier,
item_identifier: item.try(:item_identifier),
current_shelf: current_shelf_name,
shelf: item.try(:shelf),
call_number: item.try(:call_number),
circulation_status: item.try(:circulation_status).try(:name),
title: item.try(:manifestation).try(:original_title),
extent: item.try(:manifestation).try(:extent)
}
end
def lost
item.circulation_status = CirculationStatus.find_by(name: "Missing")
end
def found
if item.rended?
item.circulation_status = CirculationStatus.find_by(name: "On Loan")
else
item.circulation_status = CirculationStatus.find_by(name: "Available On Shelf")
end
end
end
# == Schema Information
#
# Table name: inventories
#
# id :bigint not null, primary key
# current_shelf_name :string
# item_identifier :string
# note :text
# created_at :datetime not null
# updated_at :datetime not null
# inventory_file_id :bigint
# item_id :bigint
#
# Indexes
#
# index_inventories_on_current_shelf_name (current_shelf_name)
# index_inventories_on_inventory_file_id (inventory_file_id)
# index_inventories_on_item_id (item_id)
# index_inventories_on_item_identifier (item_identifier)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/checkout_type.rb | app/models/checkout_type.rb | class CheckoutType < ApplicationRecord
include MasterModel
scope :available_for_carrier_type, lambda { |carrier_type| includes(:carrier_types).where("carrier_types.name = ?", carrier_type.name).order("carrier_types.position") }
scope :available_for_user_group, lambda { |user_group| includes(:user_groups).where("user_groups.name = ?", user_group.name).order("user_group.position") }
has_many :user_group_has_checkout_types, dependent: :destroy
has_many :user_groups, through: :user_group_has_checkout_types
has_many :carrier_type_has_checkout_types, dependent: :destroy
has_many :carrier_types, through: :carrier_type_has_checkout_types
# has_many :item_has_checkout_types, dependent: :destroy
# has_many :items, through: :item_has_checkout_types
has_many :items, dependent: :restrict_with_exception
paginates_per 10
end
# == Schema Information
#
# Table name: checkout_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_checkout_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/create_type.rb | app/models/create_type.rb | class CreateType < ApplicationRecord
include MasterModel
default_scope { order("create_types.position") }
end
# == Schema Information
#
# Table name: create_types
#
# id :bigint not null, primary key
# display_name :text
# name :string not null
# note :text
# position :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_create_types_on_lower_name (lower((name)::text)) UNIQUE
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/accept.rb | app/models/accept.rb | class Accept < ApplicationRecord
include EnjuCirculation::EnjuAccept
default_scope { order("accepts.id DESC") }
belongs_to :basket
belongs_to :item, touch: true
belongs_to :librarian, class_name: "User"
validates :item_id, uniqueness: true # , message: I18n.t('accept.already_accepted')
attr_accessor :item_identifier
paginates_per 10
end
# == Schema Information
#
# Table name: accepts
#
# id :bigint not null, primary key
# created_at :datetime not null
# updated_at :datetime not null
# basket_id :bigint
# item_id :bigint
# librarian_id :bigint
#
# Indexes
#
# index_accepts_on_basket_id (basket_id)
# index_accepts_on_item_id (item_id) UNIQUE
# index_accepts_on_librarian_id (librarian_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/manifestation_custom_value.rb | app/models/manifestation_custom_value.rb | class ManifestationCustomValue < ApplicationRecord
belongs_to :manifestation_custom_property
belongs_to :manifestation
validates :manifestation_custom_property, uniqueness: { scope: :manifestation_id }
end
# == Schema Information
#
# Table name: manifestation_custom_values
#
# id :bigint not null, primary key
# value :text
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_custom_property_id :bigint not null
# manifestation_id :bigint not null
#
# Indexes
#
# index_manifestation_custom_values_on_custom_property_id (manifestation_custom_property_id)
# index_manifestation_custom_values_on_manifestation_id (manifestation_id)
# index_manifestation_custom_values_on_property_manifestation (manifestation_custom_property_id,manifestation_id) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (manifestation_custom_property_id => manifestation_custom_properties.id)
# fk_rails_... (manifestation_id => manifestations.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/bookmark.rb | app/models/bookmark.rb | class Bookmark < ApplicationRecord
scope :bookmarked, lambda { |start_date, end_date| where("created_at >= ? AND created_at < ?", start_date, end_date) }
scope :user_bookmarks, lambda { |user| where(user_id: user.id) }
scope :shared, -> { where(shared: true) }
belongs_to :manifestation, touch: true, optional: true
belongs_to :user
validates :title, presence: :true
validates :url, presence: { on: :create }
validates :manifestation_id, presence: { on: :update }
validates :manifestation_id, uniqueness: { scope: :user_id }
validates :url, url: true, presence: true, length: { maximum: 255 }
validate :bookmarkable_url?
validate :already_bookmarked?, if: :url_changed?
before_save :create_manifestation, if: :url_changed?
before_save :replace_space_in_tags
acts_as_taggable_on :tags
strip_attributes only: :url
searchable do
text :title do
manifestation.title
end
string :url
string :tag, multiple: true do
tag_list
end
integer :user_id
integer :manifestation_id
time :created_at
time :updated_at
boolean :shared
end
paginates_per 10
def replace_space_in_tags
# タグに含まれている全角スペースを除去する
self.tag_list = tag_list.map { |tag| tag.gsub(" ", " ").gsub(" ", ", ") }
end
def save_tagger
taggings.each do |tagging|
tagging.tagger = user
tagging.save(validate: false)
end
end
def shelved?
true if manifestation.items.on_web.first
end
def self.get_title(string)
CGI.unescape(string).strip unless string.nil?
end
def get_title
return if url.blank?
if url.my_host?
my_host_resource.original_title
else
Bookmark.get_title_from_url(url)
end
end
def get_title_from_url(url)
return if url.blank?
return unless Addressable::URI.parse(url).host
if manifestation_id == url.bookmarkable_id
bookmark.manifestation = Manifestation.find(manifestation_id)
return manifestation.original_title
end
unless manifestation
normalized_url = Addressable::URI.parse(url).normalize.to_s
doc = Nokogiri::HTML(Faraday.get(normalized_url).body)
# TODO: 日本語以外
# charsets = ['iso-2022-jp', 'euc-jp', 'shift_jis', 'iso-8859-1']
# if charsets.include?(page.charset.downcase)
title = NKF.nkf("-w", CGI.unescapeHTML((doc.at("title").inner_text))).to_s.gsub(/\r\n|\r|\n/, "").gsub(/\s+/, " ").strip
if title.blank?
title = url
end
# else
# title = (doc/"title").inner_text
# end
title
end
rescue OpenURI::HTTPError
# TODO: 404などの場合の処理
raise "unable to access: #{url}"
# nil
end
def self.get_canonical_url(url)
doc = Nokogiri::HTML(Faraday.get(url).body)
canonical_url = doc.search("/html/head/link[@rel='canonical']").first["href"]
# TODO: URLを相対指定している時
Addressable::URI.parse(canonical_url).normalize.to_s
rescue
nil
end
def my_host_resource
if url.bookmarkable_id
manifestation = Manifestation.find(url.bookmarkable_id)
end
end
def bookmarkable_url?
if url.try(:my_host?)
unless url.try(:bookmarkable_id)
errors.add(:base, I18n.t("bookmark.not_our_holding"))
end
unless my_host_resource
errors.add(:base, I18n.t("bookmark.not_our_holding"))
end
end
end
def get_manifestation
# 自館のページをブックマークする場合
if url.try(:my_host?)
manifestation = self.my_host_resource
else
manifestation = Manifestation.where(access_address: url).first if url.present?
end
end
def already_bookmarked?
if manifestation
if manifestation.bookmarked?(user)
errors.add(:base, "already_bookmarked")
end
end
end
def create_manifestation
manifestation = get_manifestation
if manifestation
self.manifestation_id = manifestation.id
return
end
manifestation = Manifestation.new(access_address: url)
manifestation.carrier_type = CarrierType.find_by(name: "online_resource")
if title.present?
manifestation.original_title = title
else
manifestation.original_title = self.get_title
end
Manifestation.transaction do
manifestation.save
self.manifestation = manifestation
item = Item.new
item.shelf = Shelf.web
item.manifestation = manifestation
if defined?(EnjuCirculation)
item.circulation_status = CirculationStatus.where(name: "Not Available").first
end
item.save!
if defined?(EnjuCirculation)
item.use_restriction = UseRestriction.where(name: "Not For Loan").first
end
end
end
def self.manifestations_count(start_date, end_date, manifestation)
if manifestation
self.bookmarked(start_date, end_date).where(manifestation_id: manifestation.id).count
else
0
end
end
def tag_index!
manifestation.reload
manifestation.index
taggings.map { |tagging| Tag.find(tagging.tag_id).index }
Sunspot.commit
end
end
# == Schema Information
#
# Table name: bookmarks
#
# id :bigint not null, primary key
# note :text
# shared :boolean
# title :text
# url :string
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint
# user_id :bigint not null
#
# Indexes
#
# index_bookmarks_on_manifestation_id (manifestation_id)
# index_bookmarks_on_url (url)
# index_bookmarks_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resource_export_file_state_machine.rb | app/models/resource_export_file_state_machine.rb | class ResourceExportFileStateMachine
include Statesman::Machine
state :pending, initial: true
state :started
state :completed
state :failed
transition from: :pending, to: [ :started, :failed ]
transition from: :started, to: [ :completed, :failed ]
after_transition(from: :pending, to: :started) do |resource_export_file|
resource_export_file.update_column(:executed_at, Time.zone.now)
end
end
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/resource_import_result.rb | app/models/resource_import_result.rb | class ResourceImportResult < ApplicationRecord
default_scope { order("resource_import_results.id") }
scope :file_id, proc { |file_id| where(resource_import_file_id: file_id) }
scope :failed, -> { where(manifestation_id: nil) }
scope :skipped, -> { where.not(error_message: nil) }
belongs_to :resource_import_file
belongs_to :manifestation, optional: true
belongs_to :item, optional: true
end
# == Schema Information
#
# Table name: resource_import_results
#
# id :bigint not null, primary key
# body :text
# error_message :text
# created_at :datetime not null
# updated_at :datetime not null
# item_id :bigint
# manifestation_id :bigint
# resource_import_file_id :bigint
#
# Indexes
#
# index_resource_import_results_on_item_id (item_id)
# index_resource_import_results_on_manifestation_id (manifestation_id)
# index_resource_import_results_on_resource_import_file_id (resource_import_file_id)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
next-l/enju_leaf | https://github.com/next-l/enju_leaf/blob/cd3cff6dcc8e67909e1cd0a12c38700b45af6a42/app/models/series_statement.rb | app/models/series_statement.rb | class SeriesStatement < ApplicationRecord
has_many :series_statement_merges, dependent: :destroy
has_many :series_statement_merge_lists, through: :series_statement_merges
belongs_to :manifestation, touch: true, optional: true
belongs_to :root_manifestation, class_name: "Manifestation", touch: true, optional: true
validates :original_title, presence: true
validates :root_manifestation_id, uniqueness: true, allow_nil: true
before_save :create_root_series_statement
after_destroy :reindex
after_save :reindex
acts_as_list
searchable do
text :title do
titles
end
text :numbering, :title_subseries, :numbering_subseries
integer :manifestation_id
integer :position
integer :series_statement_merge_list_ids, multiple: true
end
attr_accessor :selected
strip_attributes only: :original_title
paginates_per 10
def reindex
manifestation.try(:index)
root_manifestation.try(:index)
end
def titles
[
original_title,
title_transcription
]
end
def create_root_series_statement
if series_master?
self.root_manifestation = manifestation
else
self.root_manifestation = nil
end
end
end
# == Schema Information
#
# Table name: series_statements
#
# id :bigint not null, primary key
# creator_string :text
# note :text
# numbering :text
# numbering_subseries :text
# original_title :text
# position :integer
# series_master :boolean
# series_statement_identifier :string
# title_alternative :text
# title_subseries :text
# title_subseries_transcription :text
# title_transcription :text
# volume_number_string :text
# volume_number_transcription_string :text
# created_at :datetime not null
# updated_at :datetime not null
# manifestation_id :bigint
# root_manifestation_id :bigint
#
# Indexes
#
# index_series_statements_on_manifestation_id (manifestation_id)
# index_series_statements_on_root_manifestation_id (root_manifestation_id)
# index_series_statements_on_series_statement_identifier (series_statement_identifier)
#
| ruby | MIT | cd3cff6dcc8e67909e1cd0a12c38700b45af6a42 | 2026-01-04T17:52:15.550406Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.