mirror of
https://gitlink.org.cn/Gitlink/forgeplus.git
synced 2026-05-03 03:40:49 +08:00
init project
This commit is contained in:
20
app/services/admins/add_department_member_service.rb
Normal file
20
app/services/admins/add_department_member_service.rb
Normal file
@@ -0,0 +1,20 @@
|
||||
class Admins::AddDepartmentMemberService < ApplicationService
|
||||
|
||||
attr_reader :department, :params
|
||||
|
||||
def initialize(department, params)
|
||||
@department = department
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
columns = %i[]
|
||||
DepartmentMember.bulk_insert(*columns) do |worker|
|
||||
Array.wrap(params[:user_ids]).compact.each do |user_id|
|
||||
next if department.department_members.exists?(user_id: user_id)
|
||||
|
||||
worker.add(department_id: department.id, user_id: user_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
19
app/services/admins/add_laboratory_user_service.rb
Normal file
19
app/services/admins/add_laboratory_user_service.rb
Normal file
@@ -0,0 +1,19 @@
|
||||
class Admins::AddLaboratoryUserService < ApplicationService
|
||||
attr_reader :laboratory, :params
|
||||
|
||||
def initialize(laboratory, params)
|
||||
@laboratory = laboratory
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
columns = %i[]
|
||||
LaboratoryUser.bulk_insert(*columns) do |worker|
|
||||
Array.wrap(params[:user_ids]).compact.each do |user_id|
|
||||
next if laboratory.laboratory_users.exists?(user_id: user_id)
|
||||
|
||||
worker.add(laboratory_id: laboratory.id, user_id: user_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
89
app/services/admins/check_shixun_mirrors_service.rb
Normal file
89
app/services/admins/check_shixun_mirrors_service.rb
Normal file
@@ -0,0 +1,89 @@
|
||||
class Admins::CheckShixunMirrorsService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
def call
|
||||
bridge_images
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
check_sync_mirrors!
|
||||
|
||||
check_mirrors!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def mirrors
|
||||
bridge_images['images']
|
||||
end
|
||||
|
||||
def sync_mirrors
|
||||
bridge_images['imagesNotSync']
|
||||
end
|
||||
|
||||
def check_mirrors!
|
||||
return if mirrors.blank?
|
||||
image_names = []
|
||||
|
||||
mirrors.each do |data|
|
||||
mirror = JSON.parse(data)
|
||||
|
||||
name_repository = MirrorRepository.find_by(name: mirror['imageName'])
|
||||
id_repository = MirrorRepository.find_by(mirrorID: mirror['imageID'])
|
||||
|
||||
image_names << mirror['imageName']
|
||||
|
||||
if name_repository.blank? && id_repository.present? # 镜像名称被修改
|
||||
id_repository.update_column(:status, 2)
|
||||
MirrorOperationRecord.create!(mirror_repository_id: id_repository.id, mirror_id: mirror['imageID'],
|
||||
mirror_name: mirror['imageName'], status: 2, user_id: -1)
|
||||
elsif name_repository.blank? # 镜像不存在、创建镜像
|
||||
new_repository = MirrorRepository.create!(mirrorID: mirror['imageID'], name: mirror['imageName'])
|
||||
MirrorOperationRecord.create!(mirror_repository_id: new_repository.id, mirror_id: mirror['imageID'],
|
||||
mirror_name: mirror['imageName'], status: 0, user_id: -1)
|
||||
elsif name_repository.mirrorID != mirror['imageID'] # 镜像ID被修改
|
||||
name_repository.update_column(:status, 2)
|
||||
MirrorOperationRecord.create!(mirror_repository_id: name_repository.id, mirror_id: mirror['imageID'],
|
||||
mirror_name: mirror['imageName'], status: 1, user_id: -1)
|
||||
end
|
||||
end
|
||||
|
||||
# 判断中间层镜像是否被删除
|
||||
MirrorRepository.find_each do |mirror|
|
||||
next if mirror&.name.blank? || image_names.index(mirror.name)
|
||||
|
||||
mirror.update_column(:status, 4)
|
||||
MirrorOperationRecord.create!(mirror_repository_id: mirror.id, mirror_id: mirror&.mirrorID,
|
||||
mirror_name: mirror.name, status: 3, user_id: -1)
|
||||
end
|
||||
end
|
||||
|
||||
def check_sync_mirrors!
|
||||
return if sync_mirrors.blank?
|
||||
|
||||
sync_mirrors.each do |data|
|
||||
mirror = JSON.parse(data)
|
||||
|
||||
repository = MirrorRepository.find_by(name: mirror['imageName'])
|
||||
next if repository.blank? || repository.status != 1
|
||||
|
||||
repository.update_column(:status, 5)
|
||||
MirrorOperationRecord.create!(mirror_repository_id: repository.id, mirror_id: mirror['imageID'],
|
||||
mirror_name: mirror['imageName'], status: 4, user_id: -1)
|
||||
end
|
||||
end
|
||||
|
||||
def bridge_images
|
||||
@_bridge_images ||= begin
|
||||
url = "#{EduSetting.get('cloud_bridge')}/bridge/docker/images"
|
||||
res = Faraday.get(url)
|
||||
res = JSON.parse(res.body)
|
||||
raise Error, '拉取镜像信息异常' if res && res['code'] != 0
|
||||
|
||||
res
|
||||
rescue => e
|
||||
Rails.logger.error("get response failed ! #{e.message}")
|
||||
raise Error, '实训云平台繁忙(繁忙等级:84)'
|
||||
end
|
||||
end
|
||||
end
|
||||
21
app/services/admins/choose_mirror_service.rb
Normal file
21
app/services/admins/choose_mirror_service.rb
Normal file
@@ -0,0 +1,21 @@
|
||||
class Admins::ChooseMirrorService < ApplicationService
|
||||
attr_reader :mirror, :user, :number
|
||||
|
||||
def initialize(mirror, user, mirror_number)
|
||||
@mirror = mirror
|
||||
@user = user
|
||||
@number = mirror_number
|
||||
end
|
||||
|
||||
def call
|
||||
if mirror.mirrorID == number
|
||||
mirror.update_column(:status, 1)
|
||||
return
|
||||
end
|
||||
|
||||
old_number = mirror.mirrorID
|
||||
mirror.update!(mirrorID: number, status: 1)
|
||||
MirrorOperationRecord.create!(mirror_repository_id: mirror.id, mirror_id: number, mirror_name: mirror.name,
|
||||
status: 1, user_id: user.id, old_tag: old_number, new_tag: mirror.mirrorID)
|
||||
end
|
||||
end
|
||||
20
app/services/admins/create_laboratory_service.rb
Normal file
20
app/services/admins/create_laboratory_service.rb
Normal file
@@ -0,0 +1,20 @@
|
||||
class Admins::CreateLaboratoryService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :params
|
||||
|
||||
def initialize(params)
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '单位不能为空' if params[:school_id].blank?
|
||||
raise Error, '该单位已存在' if Laboratory.exists?(school_id: params[:school_id])
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
laboratory = Laboratory.create!(school_id: params[:school_id])
|
||||
|
||||
laboratory.create_laboratory_setting!
|
||||
end
|
||||
end
|
||||
end
|
||||
56
app/services/admins/delete_unit_apply_service.rb
Normal file
56
app/services/admins/delete_unit_apply_service.rb
Normal file
@@ -0,0 +1,56 @@
|
||||
class Admins::DeleteUnitApplyService < ApplicationService
|
||||
|
||||
attr_reader :department, :params
|
||||
|
||||
def initialize(unit_apply, params)
|
||||
@unit_apply = unit_apply
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
@unit_apply.update_attribute("status",3)
|
||||
@unit_apply&.applied_messages&.update_all(status:3)
|
||||
@unit_apply&.school&.apply_add_departments&.update_all(status:3)
|
||||
|
||||
applied_departments = ApplyAddDepartment.where(school_id: @unit_apply.school_id)
|
||||
applied_departments.update_all(status: 3)
|
||||
|
||||
use_extensions = UserExtension&.where(school_id: @unit_apply.school_id)
|
||||
user_ids = UserExtension&.where(school_id: @unit_apply.school_id)&.pluck(:user_id)
|
||||
User.where(id: user_ids).update_all(profile_completed: false)
|
||||
use_extensions.update_all(school_id: nil,department_id: nil)
|
||||
|
||||
@unit_apply&.user&.user_extension&.update_attribute("department_id", nil)
|
||||
|
||||
# 申请了职业认证的用户撤销申请
|
||||
apply_user_auth = ApplyUserAuthentication.where(user_id: user_ids, auth_type: 2, status: 0)
|
||||
apply_user_auth.each do |apply|
|
||||
apply.tidings.destroy_all
|
||||
apply.update_attribute('status', 3)
|
||||
diskfile2 = disk_auth_filename('UserAuthentication', apply.user_id, 'PRO')
|
||||
diskfilePRO = diskfile2 + 'temp'
|
||||
File.delete(diskfilePRO) if File.exist?(diskfilePRO)
|
||||
File.delete(diskfile2) if File.exist?(diskfile2)
|
||||
end
|
||||
|
||||
# 未审批删除
|
||||
if params[:tip] == "unapplied"
|
||||
Tiding.where(:user_id => 1, :trigger_user_id => @unit_apply.user_id, :container_id => @unit_apply.id, :container_type => 'ApplyAddSchools', :status => 0, :tiding_type => "Apply").update_all(status: 1)
|
||||
Tiding.create(:user_id => @unit_apply.user_id, :trigger_user_id => 0, :container_id => @unit_apply.id, :container_type =>'ApplyAddSchools', :belong_container_id => @unit_apply.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 2, :extra => params[:reason])
|
||||
|
||||
Tiding.where(:user_id => 1, :container_id => applied_departments.pluck(:id), :container_type => 'ApplyAddDepartment', :status => 0, :tiding_type => "Apply").update_all(status: 1)
|
||||
if applied_departments&.first.present?
|
||||
Tiding.create(:user_id => applied_departments.first.user_id, :trigger_user_id => 0, :container_id => applied_departments.first.id, :container_type =>'ApplyAddDepartment', :belong_container_id => @unit_apply.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 2)
|
||||
AppliedMessage.create(:user_id => applied_departments.first.user_id, :status => 3, :viewed => 0, :applied_id => applied_departments.first.id, :applied_type => "ApplyAddDepartment", :name => applied_departments.first.name )
|
||||
end
|
||||
@unit_apply&.school&.destroy
|
||||
@unit_apply&.school&.departments&.destroy_all
|
||||
elsif params[:tip] == "applied"
|
||||
applied_departments.destroy_all
|
||||
@unit_apply.destroy
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
35
app/services/admins/drag_cooperative_service.rb
Normal file
35
app/services/admins/drag_cooperative_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Admins::DragCooperativeService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :move, :after
|
||||
|
||||
def initialize(move, after)
|
||||
@move = move
|
||||
@after = after # 移动后下一个位置的元素
|
||||
end
|
||||
|
||||
def call
|
||||
return if move.position + 1 == after&.position # 未移动
|
||||
raise Error, '未知错误' if after && move.img_type != after.img_type
|
||||
|
||||
coo_imgs = CooImg.where(img_type: move.img_type)
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
if after.blank? # 移动至末尾
|
||||
total = coo_imgs.count
|
||||
|
||||
coo_imgs.where('position > ?', move.position).update_all('position = position - 1')
|
||||
move.update!(position: total)
|
||||
return
|
||||
end
|
||||
|
||||
if move.position > after.position # 前移
|
||||
coo_imgs.where('position >= ? AND position < ?', after.position, move.position).update_all('position = position + 1')
|
||||
move.update!(position: after.position)
|
||||
else # 后移
|
||||
coo_imgs.where('position > ? AND position <= ?', move.position, after.position).update_all('position = position - 1')
|
||||
move.update!(position: after.position)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
35
app/services/admins/drag_portal_image_service.rb
Normal file
35
app/services/admins/drag_portal_image_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Admins::DragPortalImageService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :laboratory, :move, :after
|
||||
|
||||
def initialize(laboratory, move, after)
|
||||
@laboratory = laboratory
|
||||
@move = move
|
||||
@after = after # 移动后下一个位置的元素
|
||||
end
|
||||
|
||||
def call
|
||||
return if move.position + 1 == after&.position # 未移动
|
||||
|
||||
images = laboratory.portal_images
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
if after.blank? || move.id == after.id # 移动至末尾
|
||||
total = images.count
|
||||
|
||||
images.where('position > ?', move.position).update_all('position = position - 1')
|
||||
move.update!(position: total)
|
||||
return
|
||||
end
|
||||
|
||||
if move.position > after.position # 前移
|
||||
images.where('position >= ? AND position < ?', after.position, move.position).update_all('position = position + 1')
|
||||
move.update!(position: after.position)
|
||||
else # 后移
|
||||
images.where('position > ? AND position < ?', move.position, after.position).update_all('position = position - 1')
|
||||
move.update!(position: after.position - 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
32
app/services/admins/drag_weapp_advert_service.rb
Normal file
32
app/services/admins/drag_weapp_advert_service.rb
Normal file
@@ -0,0 +1,32 @@
|
||||
class Admins::DragWeappAdvertService < ApplicationService
|
||||
attr_reader :move, :after
|
||||
|
||||
def initialize(move, after)
|
||||
@move = move
|
||||
@after = after # 移动后下一个位置的元素
|
||||
end
|
||||
|
||||
def call
|
||||
return if move.position + 1 == after&.position # 未移动
|
||||
|
||||
adverts = WeappSettings::Advert.all
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
if after.blank? || move.id == after.id # 移动至末尾
|
||||
total = adverts.count
|
||||
|
||||
adverts.where('position > ?', move.position).update_all('position = position - 1')
|
||||
move.update!(position: total)
|
||||
return
|
||||
end
|
||||
|
||||
if move.position > after.position # 前移
|
||||
adverts.where('position >= ? AND position < ?', after.position, move.position).update_all('position = position + 1')
|
||||
move.update!(position: after.position)
|
||||
else # 后移
|
||||
adverts.where('position > ? AND position < ?', move.position, after.position).update_all('position = position - 1')
|
||||
move.update!(position: after.position - 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
32
app/services/admins/drag_weapp_carousel_service.rb
Normal file
32
app/services/admins/drag_weapp_carousel_service.rb
Normal file
@@ -0,0 +1,32 @@
|
||||
class Admins::DragWeappCarouselService < ApplicationService
|
||||
attr_reader :move, :after
|
||||
|
||||
def initialize(move, after)
|
||||
@move = move
|
||||
@after = after # 移动后下一个位置的元素
|
||||
end
|
||||
|
||||
def call
|
||||
return if move.position + 1 == after&.position # 未移动
|
||||
|
||||
carousels = WeappSettings::Carousel.all
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
if after.blank? || move.id == after.id # 移动至末尾
|
||||
total = carousels.count
|
||||
|
||||
carousels.where('position > ?', move.position).update_all('position = position - 1')
|
||||
move.update!(position: total)
|
||||
return
|
||||
end
|
||||
|
||||
if move.position > after.position # 前移
|
||||
carousels.where('position >= ? AND position < ?', after.position, move.position).update_all('position = position + 1')
|
||||
move.update!(position: after.position)
|
||||
else # 后移
|
||||
carousels.where('position > ? AND position < ?', move.position, after.position).update_all('position = position - 1')
|
||||
move.update!(position: after.position - 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
38
app/services/admins/identity_auths/agree_apply_service.rb
Normal file
38
app/services/admins/identity_auths/agree_apply_service.rb
Normal file
@@ -0,0 +1,38 @@
|
||||
class Admins::IdentityAuths::AgreeApplyService < ApplicationService
|
||||
attr_reader :apply, :user
|
||||
|
||||
def initialize(apply)
|
||||
@apply = apply
|
||||
@user = apply.user
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.update!(status: 1)
|
||||
user.update!(authentication: true)
|
||||
RewardGradeService.call(user, container_id: user.id, container_type: 'Authentication', score: 500)
|
||||
|
||||
deal_tiding!
|
||||
apply.attachment&.destroy
|
||||
# delete_auth_file!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply').update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyUserAuthentication',
|
||||
belong_container_id: apply.user_id, belong_container_type: 'User',
|
||||
status: 1, tiding_type: 'System')
|
||||
end
|
||||
|
||||
def delete_auth_file!
|
||||
path = Util::FileManage.disk_real_name_auth_filename(user.id)
|
||||
File.delete(path) if File.exists?(path)
|
||||
|
||||
apply.update!(is_delete: true)
|
||||
end
|
||||
end
|
||||
42
app/services/admins/identity_auths/refuse_apply_service.rb
Normal file
42
app/services/admins/identity_auths/refuse_apply_service.rb
Normal file
@@ -0,0 +1,42 @@
|
||||
class Admins::IdentityAuths::RefuseApplyService < ApplicationService
|
||||
attr_reader :apply, :user, :params
|
||||
|
||||
def initialize(apply, params)
|
||||
@apply = apply
|
||||
@user = apply.user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.update!(status: 2, remarks: reason)
|
||||
user.update!(authentication: false)
|
||||
|
||||
deal_tiding!
|
||||
apply.attachment&.destroy
|
||||
# delete_auth_file!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def reason
|
||||
params[:reason].to_s.strip
|
||||
end
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply').update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyUserAuthentication',
|
||||
belong_container_id: apply.user_id, belong_container_type: 'User',
|
||||
status: 2, tiding_type: 'System')
|
||||
end
|
||||
|
||||
def delete_auth_file!
|
||||
path = Util::FileManage.disk_real_name_auth_filename(user.id)
|
||||
File.delete(path) if File.exists?(path)
|
||||
|
||||
apply.update!(is_delete: true)
|
||||
end
|
||||
end
|
||||
26
app/services/admins/identity_auths/revoke_apply_service.rb
Normal file
26
app/services/admins/identity_auths/revoke_apply_service.rb
Normal file
@@ -0,0 +1,26 @@
|
||||
class Admins::IdentityAuths::RevokeApplyService < ApplicationService
|
||||
attr_reader :apply, :user
|
||||
|
||||
def initialize(apply)
|
||||
@apply = apply
|
||||
@user = apply.user
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.revoke!
|
||||
user.update!(authentication: false)
|
||||
|
||||
deal_tiding!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def deal_tiding!
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'CancelUserAuthentication',
|
||||
belong_container_id: apply.user_id, belong_container_type: 'User',
|
||||
status: 1, tiding_type: 'System')
|
||||
end
|
||||
end
|
||||
63
app/services/admins/import_course_member_service.rb
Normal file
63
app/services/admins/import_course_member_service.rb
Normal file
@@ -0,0 +1,63 @@
|
||||
class Admins::ImportCourseMemberService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :file, :result
|
||||
|
||||
def initialize(file)
|
||||
@file = file
|
||||
@result = { success: 0, fail: [] }
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '文件不存在' if file.blank?
|
||||
|
||||
excel = Admins::ImportCourseMemberExcel.new(file)
|
||||
excel.read_each(&method(:create_course_member))
|
||||
|
||||
result
|
||||
rescue ApplicationImport::Error => ex
|
||||
raise Error, ex.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def create_course_member(data)
|
||||
raise '课堂角色必须为 2、3、4' unless [2, 3, 4].include?(data.role.to_i)
|
||||
|
||||
user = User.joins(:user_extension).where(user_extensions: { student_id: data.student_id, school_id: data.school_id }).first
|
||||
raise '该学号的用户不存在' if user.blank?
|
||||
course = Course.find_by(id: data.course_id)
|
||||
raise '该课堂不存在' if course.blank?
|
||||
|
||||
course_group = nil
|
||||
if data.course_group_name.present?
|
||||
course_group = course.course_groups.find_or_create_by!(name: data.course_group_name)
|
||||
end
|
||||
|
||||
member = course.course_members.find_by(user_id: user.id, role: data.role.to_i)
|
||||
# 如果已是课堂成员且是学生身份and不在指定的分班则移动到该分班
|
||||
if member.present? && member.role == 'STUDENT' && course_group && member.course_group_id != course_group&.id.to_i
|
||||
member.update!(course_group_id: course_group&.id.to_i)
|
||||
elsif member.blank?
|
||||
course.course_members.create!(user_id: user.id, role: data.role.to_i, course_group_id: course_group&.id.to_i)
|
||||
extra =
|
||||
case data.role.to_i
|
||||
when 2 then 9
|
||||
when 3 then 7
|
||||
else 10
|
||||
end
|
||||
|
||||
Tiding.create!(user_id: user.id, trigger_user_id: course.tea_id, container_id: course.id,
|
||||
container_type: 'TeacherJoinCourse', belong_container_id: course.id,
|
||||
belong_container_type: 'Course', tiding_type: 'System', extra: extra)
|
||||
end
|
||||
|
||||
result[:success] += 1
|
||||
rescue Exception => ex
|
||||
fail_data = data.as_json
|
||||
fail_data[:data] = fail_data.values.join(',')
|
||||
fail_data[:message] = ex.message
|
||||
|
||||
result[:fail] << fail_data
|
||||
end
|
||||
end
|
||||
52
app/services/admins/import_discipline_service.rb
Normal file
52
app/services/admins/import_discipline_service.rb
Normal file
@@ -0,0 +1,52 @@
|
||||
class Admins::ImportDisciplineService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :file, :result
|
||||
|
||||
def initialize(file)
|
||||
@file = file
|
||||
@result = { success: 0, fail: [] }
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '文件不存在' if file.blank?
|
||||
|
||||
excel = Admins::ImportDisciplineExcel.new(file)
|
||||
excel.read_each(&method(:save_discipline))
|
||||
|
||||
result
|
||||
rescue ApplicationImport::Error => ex
|
||||
raise Error, ex.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def save_discipline(data)
|
||||
count = 0
|
||||
discipline_name = data.discipline_name.to_s.strip
|
||||
sub_discipline_name = data.sub_discipline_name.to_s.strip
|
||||
|
||||
return unless discipline_name.present?
|
||||
discipline = Discipline.find_by(name: discipline_name)
|
||||
if discipline.blank?
|
||||
discipline = Discipline.create!(name: discipline_name, position: Discipline.all.pluck(:position).max + 1)
|
||||
count += 1
|
||||
end
|
||||
|
||||
if sub_discipline_name.present?
|
||||
sub_discipline = SubDiscipline.find_by(name: discipline_name, discipline: discipline)
|
||||
if sub_discipline.blank?
|
||||
SubDiscipline.create!(name: sub_discipline_name, discipline: discipline, position: discipline.sub_disciplines.pluck(:position).max + 1)
|
||||
count += 1
|
||||
end
|
||||
end
|
||||
|
||||
result[:success] += count
|
||||
rescue Exception => ex
|
||||
fail_data = data.as_json
|
||||
fail_data[:data] = fail_data.values.join(',')
|
||||
fail_data[:message] = ex.message
|
||||
|
||||
result[:fail] << fail_data
|
||||
end
|
||||
end
|
||||
92
app/services/admins/import_user_service.rb
Normal file
92
app/services/admins/import_user_service.rb
Normal file
@@ -0,0 +1,92 @@
|
||||
class Admins::ImportUserService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :file, :school, :prefix, :result
|
||||
|
||||
def initialize(file)
|
||||
@file = file
|
||||
@result = { success: 0, fail: [] }
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '文件不存在' if file.blank?
|
||||
|
||||
excel = Admins::ImportUserExcel.new(file)
|
||||
@school = excel.school
|
||||
@prefix = excel.identifier
|
||||
|
||||
excel.read_each(&method(:save_user))
|
||||
|
||||
result
|
||||
rescue ApplicationImport::Error => ex
|
||||
raise Error, ex.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def save_user(data)
|
||||
user = find_user(data)
|
||||
|
||||
if user.blank?
|
||||
create_user(data)
|
||||
else
|
||||
user.update_column(:certification, 1)
|
||||
end
|
||||
|
||||
result[:success] += 1
|
||||
rescue Exception => ex
|
||||
fail_data = data.as_json
|
||||
fail_data[:data] = fail_data.values.join(',')
|
||||
fail_data[:message] = ex.message
|
||||
|
||||
result[:fail] << fail_data
|
||||
end
|
||||
|
||||
def create_user(data)
|
||||
department = school.departments.find_by(name: data.department_name)
|
||||
|
||||
attr = {
|
||||
type: 'User',
|
||||
status: User::STATUS_ACTIVE,
|
||||
login: "#{prefix}#{data.student_id}",
|
||||
firstname: '',
|
||||
lastname: data.name,
|
||||
nickname: data.name,
|
||||
professional_certification: 1,
|
||||
certification: 1,
|
||||
password: '12345678',
|
||||
phone: data.phone,
|
||||
mail: "#{prefix}#{data.student_id}@qq.com",
|
||||
profile_completed: true
|
||||
}
|
||||
ActiveRecord::Base.transaction do
|
||||
user = User.create!(attr)
|
||||
|
||||
extension_attr = {
|
||||
school_id: school.id, location: school.province, location_city: school.city,
|
||||
gender: 0, identity: data.identity.to_i, department_id: department&.id, student_id: data.student_id
|
||||
}
|
||||
|
||||
extension_attr[:technical_title] =
|
||||
case data.identity.to_i
|
||||
when 0 then %w(教授 副教授 讲师 助教).include?(data.technical_title) ? data.technical_title : '讲师'
|
||||
when 2 then %w(企业管理者 部门管理者 高级工程师 工程师 助理工程师).include?(data.technical_title) ? data.technical_title : '助理工程师'
|
||||
else nil
|
||||
end
|
||||
|
||||
user.create_user_extension!(extension_attr)
|
||||
end
|
||||
end
|
||||
|
||||
def find_user(data)
|
||||
users = User.joins(:user_extension).where(user_extensions: { identity: data.identity, school_id: school.id })
|
||||
|
||||
if data.identity.to_i == 1
|
||||
users = users.where(user_extensions: { student_id: data.student_id })
|
||||
else
|
||||
users = users.where(user_extensions: { technical_title: data.technical_title }).where('CONCAT(users.lastname,users.firstname) = ?', data.name)
|
||||
end
|
||||
|
||||
users.first
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
class Admins::ProfessionalAuths::AgreeApplyService < ApplicationService
|
||||
attr_reader :apply, :user
|
||||
|
||||
def initialize(apply)
|
||||
@apply = apply
|
||||
@user = apply.user
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.update!(status: 1)
|
||||
user.update!(professional_certification: true)
|
||||
user.update!(is_shixun_marker: true) if user.is_teacher?
|
||||
RewardGradeService.call(user, container_id: user.id, container_type: 'Professional', score: 500)
|
||||
|
||||
deal_tiding!
|
||||
apply.attachment&.destroy
|
||||
# delete_auth_file!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply').update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyUserAuthentication',
|
||||
belong_container_id: apply.user_id, belong_container_type: 'User',
|
||||
status: 1, tiding_type: 'System')
|
||||
end
|
||||
|
||||
def delete_auth_file!
|
||||
path = Util::FileManage.disk_professional_auth_filename(user.id)
|
||||
File.delete(path) if File.exists?(path)
|
||||
|
||||
apply.update!(is_delete: true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,42 @@
|
||||
class Admins::ProfessionalAuths::RefuseApplyService < ApplicationService
|
||||
attr_reader :apply, :user, :params
|
||||
|
||||
def initialize(apply, params)
|
||||
@apply = apply
|
||||
@user = apply.user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.update!(status: 2, remarks: reason)
|
||||
user.update!(professional_certification: false)
|
||||
|
||||
deal_tiding!
|
||||
apply.attachment&.destroy
|
||||
# delete_auth_file!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def reason
|
||||
params[:reason].to_s.strip
|
||||
end
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply').update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyUserAuthentication',
|
||||
belong_container_id: apply.user_id, belong_container_type: 'User',
|
||||
status: 2, tiding_type: 'System')
|
||||
end
|
||||
|
||||
def delete_auth_file!
|
||||
path = Util::FileManage.disk_professional_auth_filename(user.id)
|
||||
File.delete(path) if File.exists?(path)
|
||||
|
||||
apply.update!(is_delete: true)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,26 @@
|
||||
class Admins::ProfessionalAuths::RevokeApplyService < ApplicationService
|
||||
attr_reader :apply, :user
|
||||
|
||||
def initialize(apply)
|
||||
@apply = apply
|
||||
@user = apply.user
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.revoke!
|
||||
user.update!(professional_certification: false)
|
||||
|
||||
deal_tiding!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def deal_tiding!
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'CancelUserProCertification',
|
||||
belong_container_id: apply.user_id, belong_container_type: 'User',
|
||||
status: 1, tiding_type: 'System')
|
||||
end
|
||||
end
|
||||
56
app/services/admins/save_laboratory_setting_service.rb
Normal file
56
app/services/admins/save_laboratory_setting_service.rb
Normal file
@@ -0,0 +1,56 @@
|
||||
class Admins::SaveLaboratorySettingService < ApplicationService
|
||||
attr_reader :laboratory, :laboratory_setting, :params
|
||||
|
||||
def initialize(laboratory, params)
|
||||
@params = params
|
||||
@laboratory = laboratory
|
||||
@laboratory_setting = laboratory.laboratory_setting
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
laboratory.identifier = strip params[:identifier]
|
||||
laboratory_setting.name = strip params[:name]
|
||||
laboratory_setting.navbar = navbar_config
|
||||
laboratory_setting.footer = strip params[:footer]
|
||||
|
||||
laboratory.save!
|
||||
laboratory_setting.save!
|
||||
|
||||
deal_image_file
|
||||
end
|
||||
|
||||
laboratory
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def navbar_config
|
||||
params[:navbar].map do |nav|
|
||||
hash = {}
|
||||
hash[:name] = strip nav[:name]
|
||||
hash[:link] = strip nav[:link]
|
||||
hash[:hidden] = nav[:hidden].to_s != '0'
|
||||
hash
|
||||
end
|
||||
end
|
||||
|
||||
def deal_image_file
|
||||
save_image_file(params[:nav_logo], 'nav')
|
||||
save_image_file(params[:login_logo], 'login')
|
||||
save_image_file(params[:tab_logo], 'tab')
|
||||
save_image_file(params[:subject_banner], '_subject_banner')
|
||||
save_image_file(params[:course_banner], '_course_banner')
|
||||
save_image_file(params[:competition_banner], '_competition_banner')
|
||||
save_image_file(params[:moop_cases_banner], '_moop_cases_banner')
|
||||
save_image_file(params[:oj_banner], '_oj_banner')
|
||||
end
|
||||
|
||||
def save_image_file(file, type)
|
||||
return unless file.present? && file.is_a?(ActionDispatch::Http::UploadedFile)
|
||||
|
||||
file_path = Util::FileManage.source_disk_filename(laboratory_setting, type)
|
||||
File.delete(file_path) if File.exist?(file_path) # 删除之前的文件
|
||||
Util.write_file(file, file_path)
|
||||
end
|
||||
end
|
||||
37
app/services/admins/save_mirror_repository_service.rb
Normal file
37
app/services/admins/save_mirror_repository_service.rb
Normal file
@@ -0,0 +1,37 @@
|
||||
class Admins::SaveMirrorRepositoryService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :mirror, :user, :params
|
||||
|
||||
def initialize(mirror, user, params)
|
||||
@mirror = mirror
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
mirror.assign_attributes(params)
|
||||
|
||||
raise Error, '镜像别名重复' if MirrorRepository.where.not(id: mirror.id).exists?(type_name: params[:type_name])
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
record_operation! if mirror.persisted?
|
||||
|
||||
mirror.save!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def record_operation!
|
||||
if mirror.type_name_changed?
|
||||
MirrorOperationRecord.create!(mirror_repository_id: mirror.id, status: 5,
|
||||
user_id: user.id, old_tag: mirror.type_name_in_database,
|
||||
new_tag: mirror.type_name)
|
||||
elsif mirror.status_changed?
|
||||
MirrorOperationRecord.create!(mirror_repository_id: mirror.id, status: 5,
|
||||
user_id: user.id, old_tag: mirror.status_in_database,
|
||||
new_tag: mirror.status)
|
||||
end
|
||||
end
|
||||
end
|
||||
123
app/services/admins/school_daily_statistic_service.rb
Normal file
123
app/services/admins/school_daily_statistic_service.rb
Normal file
@@ -0,0 +1,123 @@
|
||||
class Admins::SchoolDailyStatisticService < ApplicationService
|
||||
include CustomSortable
|
||||
|
||||
attr_reader :params
|
||||
|
||||
sort_columns :student_count, :teacher_count, :homework_count, :other_homework_count,
|
||||
:course_count, :active_course_count, :nearly_course_time, :shixun_count, :shixun_evaluate_count,
|
||||
default_by: :teacher_count, default_direction: :desc
|
||||
|
||||
def initialize(params)
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
schools = School.group('schools.id')
|
||||
|
||||
keyword = params[:keyword].try(:to_s).try(:strip)
|
||||
if keyword.present?
|
||||
schools = schools.where("schools.name LIKE :keyword OR schools.id LIKE :keyword", keyword: "%#{keyword}%")
|
||||
end
|
||||
|
||||
count = schools.count.count
|
||||
|
||||
# 根据排序字段进行查询
|
||||
schools = query_by_sort_column(schools, params[:sort_by])
|
||||
schools = custom_sort(schools, params[:sort_by], params[:sort_direction])
|
||||
|
||||
schools = schools.limit(page_size).offset(offset)
|
||||
# 查询并组装其它数据
|
||||
schools = package_other_data(schools)
|
||||
|
||||
[count, schools]
|
||||
end
|
||||
|
||||
def package_other_data(schools)
|
||||
ids = schools.map(&:id)
|
||||
|
||||
student_map = UserExtension.where(school_id: ids, identity: :student).group(:school_id).count
|
||||
teacher_map = UserExtension.where(school_id: ids, identity: :teacher).group(:school_id).count
|
||||
|
||||
homeworks = HomeworkCommon.joins(:course)
|
||||
shixun_homework_map = homeworks.where(homework_type: 4, courses: { school_id: ids }).group('school_id').count
|
||||
other_homework_map = homeworks.where(homework_type: [1, 3], courses: { school_id: ids }).group('school_id').count
|
||||
|
||||
courses = Course.where(is_delete: 0, school_id: ids).group('school_id')
|
||||
course_map = courses.count
|
||||
nearly_course_time_map = courses.joins(:course_acts).maximum('course_activities.updated_at')
|
||||
active_course_map = courses.where(is_end: false).count
|
||||
|
||||
shixun_map = Shixun.joins(user: :user_extension).where(user_extensions: { identity: :teacher, school_id: ids })
|
||||
.where(fork_from: nil).group('school_id').count
|
||||
|
||||
reports = SchoolReport.where(school_id: ids)
|
||||
evaluate_count_map = reports.each_with_object({}) { |report, obj| obj[report.school_id] = report.shixun_evaluate_count }
|
||||
|
||||
schools.map do |school|
|
||||
{
|
||||
id: school.id,
|
||||
name: school.name,
|
||||
teacher_count: teacher_map[school.id],
|
||||
student_count: student_map[school.id],
|
||||
homework_count: shixun_homework_map[school.id],
|
||||
other_homework_count: other_homework_map[school.id],
|
||||
course_count: course_map[school.id],
|
||||
nearly_course_time: nearly_course_time_map[school.id],
|
||||
active_course_count: active_course_map[school.id],
|
||||
shixun_count: shixun_map.fetch(school.id, 0),
|
||||
shixun_evaluate_count: evaluate_count_map.fetch(school.id, 0)
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def query_by_sort_column(schools, sort_by_column)
|
||||
base_query_column = 'schools.id, schools.name'
|
||||
|
||||
case sort_by_column.to_s
|
||||
when 'teacher_count' then
|
||||
schools.joins('LEFT JOIN user_extensions ue ON ue.school_id = schools.id AND ue.identity = 0')
|
||||
.select("#{base_query_column}, COUNT(*) teacher_count")
|
||||
when 'student_count' then
|
||||
schools.joins('LEFT JOIN user_extensions ue ON ue.school_id = schools.id AND ue.identity = 1')
|
||||
.select("#{base_query_column}, COUNT(*) student_count")
|
||||
when 'homework_count' then
|
||||
schools.joins('LEFT JOIN courses ON courses.school_id = schools.id')
|
||||
.joins('LEFT JOIN homework_commons hc ON hc.course_id = courses.id AND hc.homework_type = 4')
|
||||
.select("#{base_query_column}, COUNT(*) homework_count")
|
||||
when 'other_homework_count' then
|
||||
schools.joins('LEFT JOIN courses ON courses.school_id = schools.id')
|
||||
.joins('LEFT JOIN homework_commons hc ON hc.course_id = courses.id AND hc.homework_type IN (1, 3)')
|
||||
.select("#{base_query_column}, COUNT(*) other_homework_count")
|
||||
when 'course_count' then
|
||||
schools.joins('LEFT JOIN courses cs ON cs.school_id = schools.id AND cs.is_delete = 0')
|
||||
.select("#{base_query_column}, COUNT(*) course_count")
|
||||
when 'shixun_count' then
|
||||
schools.joins('LEFT JOIN user_extensions ue ON ue.school_id = schools.id AND ue.identity = 0')
|
||||
.joins('LEFT JOIN users ON users.id = ue.user_id')
|
||||
.joins('LEFT JOIN shixuns sx ON sx.user_id = users.id AND sx.fork_from IS NULL')
|
||||
.select("#{base_query_column}, COUNT(*) shixun_count")
|
||||
when 'shixun_evaluate_count' then
|
||||
schools.joins('LEFT JOIN school_reports ON school_reports.school_id = schools.id')
|
||||
.select("#{base_query_column}, shixun_evaluate_count")
|
||||
when 'nearly_course_time' then
|
||||
schools.joins('LEFT JOIN courses cs ON cs.school_id = schools.id AND cs.is_delete = 0')
|
||||
.joins('LEFT JOIN course_activities acs ON acs.course_id = cs.id')
|
||||
.select("#{base_query_column}, MAX(acs.updated_at) nearly_course_time")
|
||||
when 'active_course_count' then
|
||||
schools.joins('LEFT JOIN courses cs ON cs.school_id = schools.id AND cs.is_delete = 0 AND cs.is_end = false')
|
||||
.select("#{base_query_column}, COUNT(*) active_course_count")
|
||||
else
|
||||
schools.joins('LEFT JOIN user_extensions ue ON ue.school_id = schools.id AND ue.identity = 0')
|
||||
.select("#{base_query_column}, COUNT(*) teacher_count")
|
||||
end
|
||||
end
|
||||
|
||||
def page_size
|
||||
params[:per_page] || 20
|
||||
end
|
||||
|
||||
def offset
|
||||
(params[:page].to_i.zero? ? 0 : params[:page].to_i - 1) * page_size
|
||||
end
|
||||
end
|
||||
43
app/services/admins/shixun_auths/agree_apply_service.rb
Normal file
43
app/services/admins/shixun_auths/agree_apply_service.rb
Normal file
@@ -0,0 +1,43 @@
|
||||
class Admins::ShixunAuths::AgreeApplyService < ApplicationService
|
||||
attr_reader :apply, :user, :shixun
|
||||
|
||||
def initialize(apply, user)
|
||||
@apply = apply
|
||||
@user = user
|
||||
@shixun = Shixun.find(apply.container_id)
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.update!(status: 1, dealer_id: user.id)
|
||||
shixun.update!(public: 2, publish_time: Time.now)
|
||||
|
||||
# 奖励金币、经验
|
||||
reward_grade_and_experience!
|
||||
|
||||
deal_tiding!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def reward_grade_and_experience!
|
||||
score = shixun.all_score
|
||||
shixun_creator = shixun.user
|
||||
|
||||
RewardGradeService.call(shixun_creator, container_id: shixun.id, container_type: 'shixunPublish', score: score)
|
||||
|
||||
Experience.create!(user_id: shixun_creator.id, container_id: shixun.id, container_type: 'shixunPublish', score: score)
|
||||
shixun_creator.update_column(:experience, shixun_creator.experience.to_i + score)
|
||||
end
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyAction',
|
||||
parent_container_id: apply.container_id, parent_container_type: apply.container_type,
|
||||
belong_container_id: apply.container_id, belong_container_type: 'Shixun',
|
||||
status: 1, tiding_type: 'System')
|
||||
end
|
||||
end
|
||||
35
app/services/admins/shixun_auths/refuse_apply_service.rb
Normal file
35
app/services/admins/shixun_auths/refuse_apply_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Admins::ShixunAuths::RefuseApplyService < ApplicationService
|
||||
attr_reader :apply, :user, :shixun, :params
|
||||
|
||||
def initialize(apply, user, params)
|
||||
@apply = apply
|
||||
@user = user
|
||||
@shixun = Shixun.find(apply.container_id)
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
shixun.update!(public: 0)
|
||||
apply.update!(status: 2, reason: reason, dealer_id: user.id)
|
||||
|
||||
deal_tiding!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def reason
|
||||
params[:reason].to_s.strip
|
||||
end
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyAction',
|
||||
parent_container_id: apply.container_id, parent_container_type: apply.container_type,
|
||||
belong_container_id: apply.container_id, belong_container_type: 'Shixun',
|
||||
status: 2, tiding_type: 'System')
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,80 @@
|
||||
class Admins::StatisticSchoolContrastDataService < ApplicationService
|
||||
ParameterError = Class.new(StandardError)
|
||||
|
||||
PAGE_SIZE = 20
|
||||
CONTRAST_COLUMN_LIST = %w(
|
||||
teacher_increase_count student_increase_count course_increase_count
|
||||
shixun_increase_count active_user_count shixun_homework_count shixun_evaluate_count
|
||||
).freeze
|
||||
|
||||
attr_reader :params, :sort_direction, :contrast_column
|
||||
|
||||
def initialize(params)
|
||||
@params = params
|
||||
@sort_direction = params[:sort_direction].to_s
|
||||
@contrast_column = params[:contrast_column].to_s
|
||||
end
|
||||
|
||||
def call
|
||||
validate_parameter!
|
||||
reports = School.joins(:school_daily_reports).select(select_columns)
|
||||
|
||||
keyword = params[:keyword].try(:to_s).try(:strip)
|
||||
if keyword.present?
|
||||
reports = reports.where("schools.name LIKE :keyword OR schools.id LIKE :keyword", keyword: "%#{keyword}%")
|
||||
end
|
||||
|
||||
count = reports.count('distinct(schools.id)')
|
||||
|
||||
sql = query_report_sql(reports.group('schools.id').to_sql)
|
||||
reports = SchoolDailyReport.find_by_sql(sql)
|
||||
|
||||
[count, reports]
|
||||
end
|
||||
|
||||
private
|
||||
def validate_parameter!
|
||||
if %i[begin_date end_date other_begin_date other_end_date].any? { |key| params[key].blank? }
|
||||
raise ParameterError
|
||||
end
|
||||
|
||||
unless %w(desc asc).include?(sort_direction)
|
||||
raise ParameterError
|
||||
end
|
||||
|
||||
unless CONTRAST_COLUMN_LIST.include?(contrast_column)
|
||||
raise ParameterError
|
||||
end
|
||||
end
|
||||
|
||||
def format_date(date)
|
||||
Time.zone.parse(date).strftime("%Y-%m-%d")
|
||||
end
|
||||
|
||||
def offset
|
||||
(params[:page].to_i.zero? ? 0 : params[:page].to_i - 1) * PAGE_SIZE
|
||||
end
|
||||
|
||||
def select_columns
|
||||
if contrast_column != 'active_user_count'
|
||||
"schools.id school_id, schools.name school_name,"\
|
||||
"(SUM(IF(date BETWEEN '#{format_date(params[:begin_date])}' AND '#{format_date(params[:end_date])}', #{contrast_column}, 0))) total,"\
|
||||
"(SUM(IF(date BETWEEN '#{format_date(params[:other_begin_date])}' AND '#{format_date(params[:other_end_date])}', #{contrast_column}, 0))) other_total"
|
||||
else
|
||||
# 活跃用户对比时处理方法不同
|
||||
relations = SchoolDailyActiveUser.select('COUNT(distinct user_id)').joins(:school_daily_report)
|
||||
.where('school_id = schools.id')
|
||||
total_subquery = relations.where("date BETWEEN '#{format_date(params[:begin_date])}' AND '#{format_date(params[:end_date])}'").to_sql
|
||||
other_total_subquery = relations.where("date BETWEEN '#{format_date(params[:other_begin_date])}' AND '#{format_date(params[:other_end_date])}'").to_sql
|
||||
|
||||
"schools.id school_id, schools.name school_name, (#{total_subquery}) AS total, (#{other_total_subquery}) AS other_total"
|
||||
end
|
||||
end
|
||||
|
||||
def query_report_sql(from_sql)
|
||||
order_by = "(total = 0 AND other_total != 0) #{sort_direction}, (percentage != 0) #{sort_direction}, percentage #{sort_direction}"
|
||||
|
||||
"SELECT reports.*, (other_total - total) increase, (IF(other_total - total = 0, 0.0, round((other_total - total) / IF(total = 0, 1, total), 5))) percentage "\
|
||||
"FROM (#{from_sql}) reports ORDER BY #{order_by} LIMIT #{PAGE_SIZE} OFFSET #{offset}"
|
||||
end
|
||||
end
|
||||
107
app/services/admins/statistic_school_data_grow_service.rb
Normal file
107
app/services/admins/statistic_school_data_grow_service.rb
Normal file
@@ -0,0 +1,107 @@
|
||||
class Admins::StatisticSchoolDataGrowService < ApplicationService
|
||||
include CustomSortable
|
||||
|
||||
PAGE_SIZE = 20
|
||||
|
||||
attr_reader :params
|
||||
|
||||
sort_columns :teacher_increase_count, :student_increase_count,
|
||||
:course_increase_count, :shixun_increase_count, :uniq_active_user_count,
|
||||
:shixun_homework_count, :shixun_evaluate_count,
|
||||
default_by: :teacher_increase_count, default_direction: :desc
|
||||
|
||||
def initialize(params)
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
reports = School.where(nil)
|
||||
|
||||
reports = search_filter(reports)
|
||||
|
||||
count = reports.count
|
||||
|
||||
subquery = SchoolDailyActiveUser.select('COUNT(distinct(user_id))').joins(:school_daily_report)
|
||||
.where(date_condition_sql).where("school_id is not null and school_id = schools.id").to_sql
|
||||
reports = reports.joins("LEFT JOIN school_daily_reports sdr ON sdr.school_id = schools.id AND #{date_condition_sql}")
|
||||
reports = reports.select(
|
||||
'schools.id school_id, schools.name school_name,'\
|
||||
'SUM(teacher_increase_count) teacher_increase_count,'\
|
||||
'SUM(student_increase_count) student_increase_count,'\
|
||||
'SUM(course_increase_count) course_increase_count,'\
|
||||
'SUM(shixun_increase_count) shixun_increase_count,'\
|
||||
'SUM(shixun_homework_count) shixun_homework_count,'\
|
||||
'SUM(shixun_evaluate_count) shixun_evaluate_count,'\
|
||||
"(#{subquery}) uniq_active_user_count,"\
|
||||
'SUM(active_user_count) active_user_count').group('schools.id')
|
||||
|
||||
reports = custom_sort(reports, params[:sort_by], params[:sort_direction])
|
||||
reports = reports.order('school_id asc').limit(PAGE_SIZE).offset(offset)
|
||||
|
||||
[count, reports]
|
||||
end
|
||||
|
||||
def grow_summary
|
||||
@_grow_summary ||= begin
|
||||
reports = School.joins("LEFT JOIN school_daily_reports sdr ON sdr.school_id = schools.id")
|
||||
.where(date_condition_sql)
|
||||
|
||||
subquery = SchoolDailyActiveUser.select('COUNT(distinct user_id)')
|
||||
.joins('LEFT JOIN school_daily_reports sdr ON sdr.id = school_daily_active_users.school_daily_report_id')
|
||||
.where(date_condition_sql).to_sql
|
||||
reports = search_filter(reports)
|
||||
reports.select(
|
||||
'SUM(teacher_increase_count) teacher_increase_count,'\
|
||||
'SUM(student_increase_count) student_increase_count,'\
|
||||
'SUM(course_increase_count) course_increase_count,'\
|
||||
'SUM(shixun_increase_count) shixun_increase_count,'\
|
||||
'SUM(shixun_homework_count) shixun_homework_count,'\
|
||||
'SUM(shixun_evaluate_count) shixun_evaluate_count,'\
|
||||
"(#{subquery}) uniq_active_user_count,"\
|
||||
'SUM(active_user_count) active_user_count'
|
||||
).first
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def search_filter(relations)
|
||||
keyword = params[:keyword].try(:to_s).try(:strip)
|
||||
if keyword.present?
|
||||
relations = relations.where("schools.name LIKE :keyword OR schools.id LIKE :keyword", keyword: "%#{keyword}%")
|
||||
end
|
||||
|
||||
relations
|
||||
end
|
||||
|
||||
def date_condition_sql
|
||||
date = query_date
|
||||
if date.is_a?(Range)
|
||||
"date BETWEEN '#{date.min.strftime('%Y-%m-%d')}' AND '#{date.max.strftime('%Y-%m-%d')}'"
|
||||
else
|
||||
"date = '#{date.strftime('%Y-%m-%d')}'"
|
||||
end
|
||||
end
|
||||
|
||||
def query_date
|
||||
if params[:grow_begin_date].present?
|
||||
begin_time = Time.zone.parse(params[:grow_begin_date])
|
||||
end_date = if params[:grow_end_date].present?
|
||||
Time.zone.parse(params[:grow_end_date])
|
||||
end
|
||||
|
||||
end_date.blank? || end_date == begin_time ? begin_time : begin_time..end_date
|
||||
else
|
||||
yesterday
|
||||
end
|
||||
end
|
||||
|
||||
def yesterday
|
||||
# 每日凌晨5点为节点, 25日凌晨4点、3点、2点等等,未到更新数据时间点,看到的数据是:23日-24日的统计数据
|
||||
(Time.zone.now - 5.hours).beginning_of_day - 1.days
|
||||
end
|
||||
|
||||
def offset
|
||||
(params[:page].to_i.zero? ? 0 : params[:page].to_i - 1) * PAGE_SIZE
|
||||
end
|
||||
end
|
||||
30
app/services/admins/subject_auths/agree_apply_service.rb
Normal file
30
app/services/admins/subject_auths/agree_apply_service.rb
Normal file
@@ -0,0 +1,30 @@
|
||||
class Admins::SubjectAuths::AgreeApplyService < ApplicationService
|
||||
attr_reader :apply, :user, :subject
|
||||
|
||||
def initialize(apply, user)
|
||||
@apply = apply
|
||||
@user = user
|
||||
@subject = Subject.find(apply.container_id)
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.update!(status: 1, dealer_id: user.id)
|
||||
subject.update!(public: 2, publish_time: Time.now)
|
||||
|
||||
deal_tiding!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyAction',
|
||||
parent_container_id: apply.container_id, parent_container_type: apply.container_type,
|
||||
belong_container_id: apply.container_id, belong_container_type: 'Subject',
|
||||
status: 1, tiding_type: 'System')
|
||||
end
|
||||
end
|
||||
35
app/services/admins/subject_auths/refuse_apply_service.rb
Normal file
35
app/services/admins/subject_auths/refuse_apply_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Admins::SubjectAuths::RefuseApplyService < ApplicationService
|
||||
attr_reader :apply, :user, :subject, :params
|
||||
|
||||
def initialize(apply, user, params)
|
||||
@apply = apply
|
||||
@user = user
|
||||
@subject = Subject.find(apply.container_id)
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
subject.update!(public: 0)
|
||||
apply.update!(status: 2, reason: reason, dealer_id: user.id)
|
||||
|
||||
deal_tiding!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def reason
|
||||
params[:reason].to_s.strip
|
||||
end
|
||||
|
||||
def deal_tiding!
|
||||
apply.tidings.where(tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: apply.user_id, trigger_user_id: 0,
|
||||
container_id: apply.id, container_type: 'ApplyAction',
|
||||
parent_container_id: apply.container_id, parent_container_type: apply.container_type,
|
||||
belong_container_id: apply.container_id, belong_container_type: 'Subject',
|
||||
status: 2, tiding_type: 'System')
|
||||
end
|
||||
end
|
||||
55
app/services/admins/update_user_service.rb
Normal file
55
app/services/admins/update_user_service.rb
Normal file
@@ -0,0 +1,55 @@
|
||||
class Admins::UpdateUserService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
user.assign_attributes(user_attributes)
|
||||
user.mail = params[:mail].to_s.presence
|
||||
user.phone = params[:phone].to_s.presence
|
||||
user.firstname = ''
|
||||
user.password = params[:password] if params[:password].present?
|
||||
|
||||
if params[:identity].to_s == 'student'
|
||||
params[:technical_title] = nil
|
||||
else
|
||||
params[:student_id] = nil
|
||||
end
|
||||
user.user_extension.assign_attributes(user_extension_attributes)
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
user.save!
|
||||
user.user_extension.save!
|
||||
user.update!(is_shixun_marker: true) if user.is_certification_teacher
|
||||
|
||||
update_gitlab_password if params[:password].present?
|
||||
end
|
||||
|
||||
user
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def user_attributes
|
||||
params.slice(*%i[lastname nickname mail phone admin business is_test
|
||||
professional_certification authentication is_shixun_marker])
|
||||
end
|
||||
|
||||
def user_extension_attributes
|
||||
params.slice(*%i[gender identity technical_title student_id location location_city school_id department_id])
|
||||
end
|
||||
|
||||
def update_gitlab_password
|
||||
return if user.gid.blank?
|
||||
# 同步修改gitlab密码
|
||||
Gitlab.client.edit_user(user.gid, password: params[:password])
|
||||
rescue Exception => ex
|
||||
Util.logger_error(ex)
|
||||
raise Error, '保存失败'
|
||||
end
|
||||
end
|
||||
17
app/services/application_service.rb
Normal file
17
app/services/application_service.rb
Normal file
@@ -0,0 +1,17 @@
|
||||
class ApplicationService
|
||||
include Callable
|
||||
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
def regix_emoji content
|
||||
" " if content.blank?
|
||||
regex = /[^a-zA-Z0-9\u4E00-\u9FFF]/
|
||||
content.gsub(regex, '')
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def strip(str)
|
||||
str.to_s.strip.presence
|
||||
end
|
||||
end
|
||||
27
app/services/concerns/accepts_nested_attributes_helper.rb
Normal file
27
app/services/concerns/accepts_nested_attributes_helper.rb
Normal file
@@ -0,0 +1,27 @@
|
||||
module AcceptsNestedAttributesHelper
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
def build_accepts_nested_attributes(obj, relations, data)
|
||||
# 新记录,全部为创建
|
||||
return data if obj.new_record?
|
||||
|
||||
# 更新时,需要处理删除数据
|
||||
old_ids = relations.loaded? ? relations.map(&:id) : relations.pluck(:id)
|
||||
new_ids =
|
||||
data.map do |item|
|
||||
yield(item) if block_given?
|
||||
|
||||
# 处理参数中错误的ID
|
||||
item[:id] = item[:id].to_i
|
||||
item[:id] = nil if item[:id].zero? || !old_ids.include?(item[:id])
|
||||
item[:id]
|
||||
end
|
||||
new_ids.compact!
|
||||
|
||||
# 被删除的子项ID数组
|
||||
destroy_ids = old_ids - new_ids
|
||||
destroy_attributes = destroy_ids.map { |id| { id: id, _destroy: true } }
|
||||
|
||||
data.concat(destroy_attributes)
|
||||
end
|
||||
end
|
||||
9
app/services/concerns/callable.rb
Normal file
9
app/services/concerns/callable.rb
Normal file
@@ -0,0 +1,9 @@
|
||||
module Callable
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
module ClassMethods
|
||||
def call(*parameters)
|
||||
new(*parameters).call
|
||||
end
|
||||
end
|
||||
end
|
||||
46
app/services/concerns/elasticsearch_able.rb
Normal file
46
app/services/concerns/elasticsearch_able.rb
Normal file
@@ -0,0 +1,46 @@
|
||||
module ElasticsearchAble
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def default_options
|
||||
{
|
||||
debug: Rails.env.development?,
|
||||
highlight: highlight_options,
|
||||
body_options: body_options,
|
||||
page: page,
|
||||
per_page: 20
|
||||
}
|
||||
end
|
||||
|
||||
def keyword
|
||||
params[:keyword].to_s.strip.presence || '*'
|
||||
end
|
||||
|
||||
def highlight_options
|
||||
{
|
||||
fragment_size: EduSetting.get('es_highlight_fragment_size') || 30,
|
||||
tag: '<span class="highlight">',
|
||||
fields: {
|
||||
'*' => { type: 'plain', number_of_fragments: 3 }
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def body_options
|
||||
hash = {}
|
||||
|
||||
hash[:min_score] = (EduSetting.get('es_min_score') || 10) if keyword != '*'
|
||||
|
||||
hash
|
||||
end
|
||||
|
||||
def per_page
|
||||
per_page = params[:per_page].to_s.strip.presence || params[:limit].to_s.strip.presence
|
||||
per_page.to_i <= 0 || per_page.to_i > 20 ? 20 : per_page.to_i
|
||||
end
|
||||
|
||||
def page
|
||||
params[:page].to_i <= 0 ? 1 : params[:page].to_i
|
||||
end
|
||||
end
|
||||
2
app/services/courses_service.rb
Normal file
2
app/services/courses_service.rb
Normal file
@@ -0,0 +1,2 @@
|
||||
class CoursesService
|
||||
end
|
||||
44
app/services/create_add_department_apply_service.rb
Normal file
44
app/services/create_add_department_apply_service.rb
Normal file
@@ -0,0 +1,44 @@
|
||||
class CreateAddDepartmentApplyService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
name = params[:name].to_s.strip
|
||||
raise Error, '名称不能为空' if name.blank?
|
||||
|
||||
school = School.find_by(id: params[:school_id])
|
||||
raise Error, '学校/单位不存在' if school.blank?
|
||||
raise Error, '部门已存在' if school.departments.exists?(name: name)
|
||||
|
||||
department = Department.new
|
||||
department.name = name
|
||||
department.school = school
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
department.save!
|
||||
|
||||
attrs = {
|
||||
user_id: user.id, department: department, school: school,
|
||||
name: department.name, remarks: params[:remarks], status: 0,
|
||||
}
|
||||
apply = ApplyAddDepartment.create!(attrs)
|
||||
|
||||
unless user.professional_certification?
|
||||
user.user_extension.update!(department_id: department.id)
|
||||
end
|
||||
|
||||
# 向管理员发送通知
|
||||
message = AppliedMessage.new(user_id: 1, status: 0, applied_user_id: user.id, viewed: 0,
|
||||
applied_id: apply.id, applied_type: 'ApplyAddDepartment', name: department.name)
|
||||
message.save(validate: false)
|
||||
end
|
||||
|
||||
department
|
||||
end
|
||||
end
|
||||
37
app/services/create_add_school_apply_service.rb
Normal file
37
app/services/create_add_school_apply_service.rb
Normal file
@@ -0,0 +1,37 @@
|
||||
class CreateAddSchoolApplyService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
AddSchoolApplyForm.new(params).validate!
|
||||
|
||||
name = params[:name].to_s.strip
|
||||
raise Error, '学校/单位已经存在' if name.present? && School.exists?(name: name)
|
||||
|
||||
school = School.new
|
||||
school.name = name
|
||||
school.province = params[:province].to_s.strip
|
||||
school.city = params[:city].to_s.strip
|
||||
school.address = params[:address].to_s.strip
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
school.save!
|
||||
|
||||
school_attrs = school.as_json(only: %i[name province city address])
|
||||
ApplyAddSchool.create!(school_attrs.merge(school: school, user_id: user.id, remarks: params[:remarks]))
|
||||
|
||||
# 向管理员发送通知
|
||||
message = AppliedMessage.new(user_id: 1, status: 0, applied_user_id: user.id, viewed: 0,
|
||||
applied_id: school.id, applied_type: 'ApplyAddSchools', name: school.name)
|
||||
message.save(validate: false)
|
||||
end
|
||||
|
||||
school
|
||||
end
|
||||
end
|
||||
54
app/services/create_bind_user_service.rb
Normal file
54
app/services/create_bind_user_service.rb
Normal file
@@ -0,0 +1,54 @@
|
||||
class CreateBindUserService < ApplicationService
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '系统错误' if open_user.blank?
|
||||
raise Error, '系统错误' unless can_bind_user?
|
||||
|
||||
if params[:not_bind].to_s == 'true'
|
||||
clear_can_bind_user_flag
|
||||
return user
|
||||
end
|
||||
|
||||
bind_user = User.try_to_login(params[:username], params[:password])
|
||||
raise Error, '用户名或者密码错误' if bind_user.blank?
|
||||
raise Error, '用户名或者密码错误' unless bind_user.check_password?(params[:password].to_s)
|
||||
raise Error, '该账号已被绑定,请更换其他账号进行绑定' if bind_user.bind_open_user?(params[:type].to_s)
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
open_user.user_id = bind_user.id
|
||||
open_user.save!
|
||||
|
||||
user.user_extension.delete
|
||||
user.delete
|
||||
end
|
||||
|
||||
clear_can_bind_user_flag
|
||||
|
||||
bind_user
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def open_user
|
||||
@_open_user ||= begin
|
||||
case params[:type].to_s
|
||||
when 'wechat' then user.wechat_open_user
|
||||
when 'qq' then user.qq_open_user
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def can_bind_user?
|
||||
Rails.cache.read(open_user.can_bind_cache_key).present?
|
||||
end
|
||||
|
||||
def clear_can_bind_user_flag
|
||||
Rails.cache.delete(open_user.can_bind_cache_key)
|
||||
end
|
||||
end
|
||||
48
app/services/create_diff_record_service.rb
Normal file
48
app/services/create_diff_record_service.rb
Normal file
@@ -0,0 +1,48 @@
|
||||
class CreateDiffRecordService < ApplicationService
|
||||
attr_reader :user, :obj, :column_name, :after, :before
|
||||
|
||||
def initialize(user, obj, column_name, before, after)
|
||||
@user = user
|
||||
@obj = obj
|
||||
@before = before
|
||||
@after = after
|
||||
@column_name = column_name
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
diff_record = DiffRecord.create!(user: user, container: obj, column_name: column_name)
|
||||
diff_record.create_diff_record_content!(content: diff_content)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def diff_content
|
||||
content = ''
|
||||
|
||||
arr = []
|
||||
index = 0
|
||||
fragment_size = 1
|
||||
Diffy::Diff.new(before, after).each do |line|
|
||||
unless line.include?("\\ 文件尾没有 newline 字符")
|
||||
unless line =~ /^[\+-]/
|
||||
if arr.empty? && index < fragment_size
|
||||
content += line
|
||||
index += 1
|
||||
else
|
||||
index = 0
|
||||
arr << line
|
||||
arr.shift if arr.size > fragment_size
|
||||
end
|
||||
next
|
||||
end
|
||||
|
||||
content += arr.join('') if arr.present?
|
||||
content += line
|
||||
arr.clear
|
||||
end
|
||||
end
|
||||
content
|
||||
end
|
||||
end
|
||||
164
app/services/duplicate_course_service.rb
Normal file
164
app/services/duplicate_course_service.rb
Normal file
@@ -0,0 +1,164 @@
|
||||
class DuplicateCourseService < ApplicationService
|
||||
attr_reader :origin_course, :user, :course
|
||||
|
||||
def initialize(origin_course, user)
|
||||
@user = user
|
||||
@origin_course = origin_course
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
@course = copy_course!
|
||||
|
||||
copy_course_modules!
|
||||
|
||||
join_course!
|
||||
|
||||
copy_homework_commons!
|
||||
|
||||
copy_exercises!
|
||||
|
||||
copy_polls!
|
||||
|
||||
copy_attachments!
|
||||
|
||||
course
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def copy_course!
|
||||
create_attrs = origin_course.as_json(only: %i[name class_period credit course_list_id])
|
||||
create_attrs.merge!(tea_id: user.id, school_id: user.school_id, is_public: 0, is_copy: 1)
|
||||
|
||||
Course.create!(create_attrs)
|
||||
end
|
||||
|
||||
def copy_course_modules!
|
||||
@second_category_list = {}
|
||||
origin_course.course_modules.each do |course_module|
|
||||
attrs = course_module.as_json(only: %i[module_type position hidden module_name])
|
||||
new_course_module = CourseModule.create!(attrs.merge(course_id: course.id))
|
||||
# 复制子目录
|
||||
course_module.course_second_categories.each do |second_category|
|
||||
category_attr = second_category.as_json(only: %i[category_type name position])
|
||||
new_second_category =
|
||||
CourseSecondCategory.create!(category_attr.merge(course_id: course.id, course_module_id: new_course_module.id))
|
||||
@second_category_list[second_category.id] = new_second_category.id
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def join_course!
|
||||
CourseMember.create!(course_id: course.id, user_id: user.id, role: 1)
|
||||
end
|
||||
|
||||
def copy_homework_commons!
|
||||
origin_course.homework_commons.where(homework_type: %i[normal group practice]).find_each do |origin_homework|
|
||||
homework_attrs = origin_homework.as_json(only: %i[name description homework_type homework_bank_id reference_answer])
|
||||
|
||||
course_second_category_id = @second_category_list[origin_homework.course_second_category_id]
|
||||
|
||||
homework = HomeworkCommon.create!(homework_attrs.merge(user_id: user.id, course_id: course.id,
|
||||
course_second_category_id:course_second_category_id))
|
||||
|
||||
origin_homework.attachments.find_each do |origin_attachment|
|
||||
attachment = origin_attachment.copy
|
||||
attrs = { container: homework, author_id: origin_homework.user_id, copy_from: origin_attachment.id }
|
||||
attachment.assign_attributes(attrs)
|
||||
attachment.save!
|
||||
|
||||
origin_attachment.increment!(:quotes)
|
||||
end
|
||||
|
||||
homework.create_homework_detail_manual!
|
||||
|
||||
if homework.group_homework_type?
|
||||
attrs = origin_homework.homework_detail_group.as_json(only: %i[min_num max_num base_on_project])
|
||||
homework.create_homework_detail_group!(attrs)
|
||||
elsif homework.practice_homework_type?
|
||||
HomeworkCommonsShixun.create!(homework_common_id: homework.id, shixun_id: origin_homework.homework_commons_shixun.shixun_id)
|
||||
HomeworksService.new.create_shixun_homework_cha_setting(homework, origin_homework.shixuns.first)
|
||||
end
|
||||
|
||||
|
||||
origin_homework.increment!(:quotes)
|
||||
origin_homework.homework_bank.increment!(:quotes) if origin_homework.homework_bank
|
||||
end
|
||||
end
|
||||
|
||||
def copy_exercises!
|
||||
origin_course.exercises.find_each do |origin_exercise|
|
||||
attrs = origin_exercise.as_json(only: %i[exercise_name exercise_description exercise_bank_id])
|
||||
exercise = course.exercises.create!(attrs.merge(user_id: user.id))
|
||||
|
||||
origin_exercise.exercise_questions.find_each do |origin_question|
|
||||
question_attrs = origin_question.as_json(only: %i[question_title question_type question_number question_score shixun_name shixun_id is_ordered level])
|
||||
# question_attrs[:question_type] ||= 1
|
||||
question = exercise.exercise_questions.create!(question_attrs)
|
||||
|
||||
exercise_choice_map = {}
|
||||
origin_question.exercise_choices.each_with_index do |origin_choice, index|
|
||||
choice_attrs = { choice_position: index + 1, choice_text: origin_choice.choice_text }
|
||||
choice = question.exercise_choices.create!(choice_attrs)
|
||||
|
||||
# exercise_choice_map[origin_choice.id] = choice.id 标准答案中存的是choice_position, 直接取原题的exercise_choice_id就行
|
||||
end
|
||||
|
||||
origin_question.exercise_standard_answers.find_each do |origin_answer|
|
||||
question.exercise_standard_answers.create!(
|
||||
exercise_choice_id: origin_answer.exercise_choice_id,
|
||||
answer_text: origin_answer.answer_text
|
||||
)
|
||||
end
|
||||
|
||||
origin_question.exercise_shixun_challenges.each_with_index do |sc, index|
|
||||
question.exercise_shixun_challenges.create!({position: index+1, challenge_id: sc.challenge_id,
|
||||
shixun_id: sc.shixun_id, question_score: sc.question_score})
|
||||
end
|
||||
end
|
||||
|
||||
origin_exercise.exercise_bank.increment!(:quotes) if exercise.exercise_bank
|
||||
end
|
||||
end
|
||||
|
||||
def copy_polls!
|
||||
origin_course.polls.includes(poll_questions: :poll_answers).find_each do |origin_poll|
|
||||
poll_attrs = origin_poll.as_json(only: %i[polls_name polls_description exercise_bank_id])
|
||||
poll = course.polls.create!(poll_attrs.merge(user_id: user.id))
|
||||
|
||||
origin_poll.poll_questions.each do |origin_question|
|
||||
attr_names = %i[question_title question_type is_necessary question_number max_choices min_choices]
|
||||
question_attrs = origin_question.as_json(only: attr_names)
|
||||
question_attrs[:question_type] ||= 1
|
||||
|
||||
question = poll.poll_questions.create!(question_attrs)
|
||||
|
||||
origin_question.poll_answers.each_with_index do |origin_answer, index|
|
||||
question.poll_answers.create!(answer_position: index + 1, answer_text: origin_answer.answer_text)
|
||||
end
|
||||
end
|
||||
|
||||
origin_poll.exercise_bank.increment!(:quotes) if origin_poll.exercise_bank
|
||||
end
|
||||
end
|
||||
|
||||
def copy_attachments!
|
||||
origin_course.attachments.each do |origin_attachment|
|
||||
attachment = origin_attachment.copy
|
||||
# attachment.tag_list.add(origin_attachment.tag_list) # tag关联
|
||||
attachment.container = course
|
||||
attachment.created_on = Time.now
|
||||
attachment.publish_time = nil
|
||||
attachment.author_id = User.current.id
|
||||
attachment.copy_from = origin_attachment.copy_from || origin_attachment.id
|
||||
attachment.is_publish = 0
|
||||
attachment.attachtype ||= 4
|
||||
attachment.course_second_category_id = @second_category_list[origin_attachment.course_second_category_id]
|
||||
|
||||
attachment.save!
|
||||
origin_course.update_quotes(attachment)
|
||||
end
|
||||
end
|
||||
end
|
||||
18
app/services/generate_db_service.rb
Normal file
18
app/services/generate_db_service.rb
Normal file
@@ -0,0 +1,18 @@
|
||||
class GenerateDbService
|
||||
def initialize
|
||||
end
|
||||
|
||||
def self.call(dir_url, key)
|
||||
if File::directory? dir_url
|
||||
Dir.entries(dir_url).each { |sub|
|
||||
if sub != '.' && sub != '..'
|
||||
puts "#{key} name: #{sub}"
|
||||
file_path = File.join(dir_url, sub)
|
||||
puts "#{key} path: #{file_path}"
|
||||
file_content = File.read(file_path)
|
||||
key.classify.constantize.find_or_create_by(name: sub, content: file_content)
|
||||
end
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
80
app/services/git_service.rb
Normal file
80
app/services/git_service.rb
Normal file
@@ -0,0 +1,80 @@
|
||||
#coding=utf-8
|
||||
#
|
||||
# 文档在 https://www.showdoc.cc/127895880302646?page_id=1077512172693249
|
||||
#
|
||||
require 'faraday'
|
||||
|
||||
class GitService
|
||||
|
||||
class << self
|
||||
|
||||
['add_repository', 'fork_repository', 'delete_repository', 'file_tree', 'update_file', 'file_content', 'commits',
|
||||
'add_tree', 'delete_file', 'update_file_base64'].each do |method|
|
||||
define_method method do |params|
|
||||
post(method, params)
|
||||
end
|
||||
end
|
||||
|
||||
def make_new_multipar_file(full_file_path)
|
||||
Faraday::FilePart.new(full_file_path, 'application/octet-stream')
|
||||
end
|
||||
|
||||
#上传二进制文件
|
||||
#参数构造形式
|
||||
# {a: 'a', file: make_new_multipar_file('1.txt') }
|
||||
def update_file_binary(params)
|
||||
post_form('update_file', params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def root_url
|
||||
new_git_address = EduSetting.get('git_address_domain')
|
||||
raise 'error: new_git_address not configuration' unless new_git_address.present?
|
||||
new_git_address
|
||||
end
|
||||
|
||||
def logger
|
||||
Rails.logger
|
||||
end
|
||||
|
||||
def post_form(action,params)
|
||||
conn = Faraday.new(root_url) do |f|
|
||||
f.request :multipart
|
||||
f.request :url_encoded
|
||||
f.adapter :net_http
|
||||
end
|
||||
|
||||
resp = conn.post("/api/#{action}", params)
|
||||
|
||||
body = resp.body
|
||||
parse_return(body)
|
||||
end
|
||||
|
||||
def post(action, params)
|
||||
uri = URI.parse("#{root_url}/api/#{action}")
|
||||
https = Net::HTTP.new(uri.host, uri.port)
|
||||
https.use_ssl = root_url.start_with?('https')
|
||||
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' => 'text/plain;charset=utf-8'})
|
||||
req.body = params.to_json
|
||||
res = https.request(req)
|
||||
body = res.body
|
||||
|
||||
parse_return(body)
|
||||
end
|
||||
|
||||
def parse_return(body)
|
||||
#logger.info("--uri_exec: .....res is #{body}")
|
||||
|
||||
content = JSON.parse(body)
|
||||
if content["code"] != 0
|
||||
logger.error("repository error: #{content['msg']}")
|
||||
raise("版本库异常")
|
||||
end
|
||||
#raise content["msg"] if content["code"] != 0
|
||||
|
||||
content["data"]
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
164
app/services/gitea/client_service.rb
Normal file
164
app/services/gitea/client_service.rb
Normal file
@@ -0,0 +1,164 @@
|
||||
class Gitea::ClientService < ApplicationService
|
||||
attr_reader :username, :secret, :token, :url, :params
|
||||
|
||||
def initialize(options={})
|
||||
@username = options[:username]
|
||||
@secret = options[:password]
|
||||
@token = options[:token]
|
||||
@url = options[:url]
|
||||
@params = options[:params]
|
||||
end
|
||||
|
||||
# params
|
||||
# EXA:
|
||||
# {
|
||||
# token: {},
|
||||
# data: {}
|
||||
# }
|
||||
def post(url, params={})
|
||||
puts "[gitea] request params: #{params}"
|
||||
request_url = [api_url, url].join('').freeze
|
||||
auth_token = authen_params(params[:token])
|
||||
response = conn(auth_token).post do |req|
|
||||
req.url "#{request_url}"
|
||||
req.body = params[:data].to_json
|
||||
end
|
||||
render_status(response)
|
||||
end
|
||||
|
||||
def get(url, params={})
|
||||
auth_token = authen_params(params[:token])
|
||||
conn(auth_token).get do |req|
|
||||
req.url full_url(url)
|
||||
params.except(:token).each_pair do |key, value|
|
||||
req.params["#{key}"] = value
|
||||
end
|
||||
end
|
||||
|
||||
# response.headers.each do |k,v|
|
||||
# puts "#{k}:#{v}"
|
||||
# end #=> 响应头
|
||||
end
|
||||
|
||||
def delete(url, params={})
|
||||
auth_token = authen_params(params[:token])
|
||||
conn(auth_token).delete do |req|
|
||||
req.url full_url(url)
|
||||
req.body = params[:data].to_json
|
||||
end
|
||||
end
|
||||
|
||||
def patch(url, params={})
|
||||
puts "[gitea] request params: #{params}"
|
||||
auth_token = authen_params(params[:token])
|
||||
conn(auth_token).patch do |req|
|
||||
req.url full_url(url)
|
||||
req.body = params[:data].to_json
|
||||
end
|
||||
end
|
||||
|
||||
def put(url, params={})
|
||||
puts "[gitea] put request params: #{params}"
|
||||
conn(authen_params(params[:token])).put do |req|
|
||||
req.url full_url(url)
|
||||
req.body = params[:data].to_json
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def conn(auth={})
|
||||
username = auth[:username] || access_key_id
|
||||
secret = auth[:password] || access_key_secret
|
||||
token = auth[:token]
|
||||
puts "[gitea] username: #{username}"
|
||||
puts "[gitea] secret: #{secret}"
|
||||
puts "[gitea] token: #{token}"
|
||||
|
||||
@client ||= begin
|
||||
Faraday.new(url: domain) do |req|
|
||||
req.request :url_encoded
|
||||
req.headers['Content-Type'] = 'application/json'
|
||||
req.response :logger # 显示日志
|
||||
req.adapter Faraday.default_adapter
|
||||
if token.blank?
|
||||
req.basic_auth(username, secret)
|
||||
else
|
||||
req.authorization :Bearer, token
|
||||
req.headers['Authorization']
|
||||
end
|
||||
end
|
||||
end
|
||||
@client
|
||||
end
|
||||
|
||||
def base_url
|
||||
Gitea.gitea_config[:base_url]
|
||||
end
|
||||
|
||||
def domain
|
||||
Gitea.gitea_config[:domain]
|
||||
end
|
||||
|
||||
def access_key_id
|
||||
Gitea.gitea_config[:access_key_id]
|
||||
end
|
||||
|
||||
def access_key_secret
|
||||
Gitea.gitea_config[:access_key_secret]
|
||||
end
|
||||
|
||||
def api_url
|
||||
[domain, base_url].join('')
|
||||
end
|
||||
|
||||
def full_url(api_rest)
|
||||
[api_url, api_rest].join('').freeze
|
||||
end
|
||||
|
||||
def render_status(response)
|
||||
mark = "[gitea] "
|
||||
case response.status
|
||||
when 201, 200, 202
|
||||
if response.body.size > 0
|
||||
JSON.parse(response&.body)
|
||||
else
|
||||
{status: 200}
|
||||
end
|
||||
when 401
|
||||
raise Error, mark + "401"
|
||||
when 422
|
||||
result = JSON.parse(response&.body)
|
||||
puts "[gitea] parse body: #{result}"
|
||||
# return {status: -1, message: result[0]}
|
||||
raise Error, result[0]
|
||||
when 204
|
||||
|
||||
puts "[gitea] "
|
||||
raise Error, "[gitea] delete ok"
|
||||
when 409
|
||||
message = "创建失败,请检查该分支合并是否已存在"
|
||||
raise Error, mark + message
|
||||
else
|
||||
if response&.body.blank?
|
||||
message = "请求失败"
|
||||
else
|
||||
result = JSON.parse(response&.body)
|
||||
message = result['message']
|
||||
end
|
||||
raise Error, mark + message
|
||||
end
|
||||
end
|
||||
|
||||
def authen_params(token)
|
||||
(token.is_a? String) ? {token: token} : Hash(token)
|
||||
end
|
||||
|
||||
def render_data(response)
|
||||
case response.status
|
||||
when 201, 200
|
||||
JSON.parse(response.body)
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
29
app/services/gitea/labels/create_service.rb
Normal file
29
app/services/gitea/labels/create_service.rb
Normal file
@@ -0,0 +1,29 @@
|
||||
class Gitea::Labels::CreateService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :params
|
||||
|
||||
# params ex:
|
||||
# {
|
||||
# name: 'pull request title',
|
||||
# description: 'pull request content',
|
||||
# color: '#ffff',
|
||||
# }
|
||||
# repo: 仓库名称
|
||||
def initialize(user, repo, params={})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}/labels".freeze
|
||||
end
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: user.gitea_token, data: params)
|
||||
end
|
||||
end
|
||||
39
app/services/gitea/labels/delete_service.rb
Normal file
39
app/services/gitea/labels/delete_service.rb
Normal file
@@ -0,0 +1,39 @@
|
||||
class Gitea::Labels::DeleteService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name,:label_id
|
||||
|
||||
def initialize(user, repo_name, label_id)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@label_id = label_id
|
||||
end
|
||||
|
||||
def call
|
||||
response = delete(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/labels/#{label_id}".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
return_body = response.body
|
||||
if return_body.present?
|
||||
body = JSON.parse(response.body)
|
||||
else
|
||||
body = []
|
||||
end
|
||||
case response.status
|
||||
when 204
|
||||
body
|
||||
else
|
||||
{status: -1, message: "#{body['message'] if body.present?}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
32
app/services/gitea/labels/list_service.rb
Normal file
32
app/services/gitea/labels/list_service.rb
Normal file
@@ -0,0 +1,32 @@
|
||||
class Gitea::Labels::ListService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name
|
||||
|
||||
|
||||
def initialize(user, repo_name)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/labels".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200 then body
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
30
app/services/gitea/labels/update_service.rb
Normal file
30
app/services/gitea/labels/update_service.rb
Normal file
@@ -0,0 +1,30 @@
|
||||
class Gitea::Labels::UpdateService < Gitea::ClientService
|
||||
attr_reader :user, :repo,:label_id, :params
|
||||
|
||||
# params ex:
|
||||
# {
|
||||
# name: 'pull request title',
|
||||
# description: 'pull request content',
|
||||
# color: '#ffff',
|
||||
# }
|
||||
# repo: 仓库名称
|
||||
def initialize(user, repo,label_id, params={})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@params = params
|
||||
@label_id = label_id
|
||||
end
|
||||
|
||||
def call
|
||||
put(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}/labels/#{label_id}".freeze
|
||||
end
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: user.gitea_token, data: params)
|
||||
end
|
||||
end
|
||||
35
app/services/gitea/pull_request/check_service.rb
Normal file
35
app/services/gitea/pull_request/check_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
# Check if a pull request has been merged
|
||||
class Gitea::PullRequest::CheckService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :pull_request_id
|
||||
|
||||
# user: 用户
|
||||
# repo: 仓库名称/标识
|
||||
# pull_request_id: pull request主键id
|
||||
def initialize(user, repo, pull_request_id)
|
||||
super({token: user.gitea_token})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@pull_request_id = pull_request_id
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_response(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}/pulls/#{pull_request_id}/merge".freeze
|
||||
end
|
||||
|
||||
def render_response(response)
|
||||
case response.status
|
||||
when 204 then true
|
||||
when 404 then false
|
||||
end
|
||||
end
|
||||
end
|
||||
34
app/services/gitea/pull_request/create_service.rb
Normal file
34
app/services/gitea/pull_request/create_service.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
|
||||
class Gitea::PullRequest::CreateService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :params
|
||||
|
||||
# params ex:
|
||||
# {
|
||||
# title: 'pull request title',
|
||||
# body: 'pull request content',
|
||||
# head: 'develop', // from branch 源分支
|
||||
# base: 'master' // to branch 目标分支
|
||||
# }
|
||||
# 以上列子说明从develop分支合并到master分支
|
||||
# repo: 仓库名称
|
||||
def initialize(user, repo, params={})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
|
||||
def url
|
||||
"/repos/#{@user.login}/#{@repo}/pulls".freeze
|
||||
end
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: @user.gitea_token, data: @params)
|
||||
end
|
||||
end
|
||||
37
app/services/gitea/pull_request/get_service.rb
Normal file
37
app/services/gitea/pull_request/get_service.rb
Normal file
@@ -0,0 +1,37 @@
|
||||
# Get a pull request
|
||||
class Gitea::PullRequest::GetService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :pull_request_id
|
||||
|
||||
# user: 用户
|
||||
# repo: 仓库名称/标识
|
||||
# pull_request_id: pull request主键id
|
||||
def initialize(user, repo, pull_request_id)
|
||||
super({token: user.gitea_token})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@pull_request_id = pull_request_id
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}/pulls/#{pull_request_id}".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
case response.status
|
||||
when 200
|
||||
JSON.parse(response.body)
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
34
app/services/gitea/pull_request/list_service.rb
Normal file
34
app/services/gitea/pull_request/list_service.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
# Get a list of all commits from a repository
|
||||
class Gitea::PullRequest::ListService < Gitea::ClientService
|
||||
attr_reader :user, :repo
|
||||
|
||||
# sha: SHA or branch to start listing commits from (usually 'master')
|
||||
def initialize(user, repo)
|
||||
@user = user
|
||||
@repo = repo
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{@user.try(:login)}/#{@repo}/pulls".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200
|
||||
body
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
31
app/services/gitea/pull_request/merge_service.rb
Normal file
31
app/services/gitea/pull_request/merge_service.rb
Normal file
@@ -0,0 +1,31 @@
|
||||
# Merge a pull request
|
||||
class Gitea::PullRequest::MergeService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :pull_request_id, :params
|
||||
|
||||
# parameters:
|
||||
# repo: name of the repo
|
||||
# pull_request_id: index of the pull request to merge
|
||||
# params:
|
||||
# title: merge标题
|
||||
# message: merge说明
|
||||
def initialize(user, repo, pull_request_id, params={})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@params = params
|
||||
@pull_request_id = pull_request_id
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}/pulls/#{pull_request_id}/merge"
|
||||
end
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: user.gitea_token, data: params)
|
||||
end
|
||||
|
||||
end
|
||||
26
app/services/gitea/pull_request/update_service.rb
Normal file
26
app/services/gitea/pull_request/update_service.rb
Normal file
@@ -0,0 +1,26 @@
|
||||
class Gitea::PullRequest::UpdateService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :params,:pull_request_id
|
||||
|
||||
|
||||
def initialize(user, repo, params,pull_request_id)
|
||||
@user = user
|
||||
@repo = repo
|
||||
@params = params
|
||||
@pull_request_id = pull_request_id
|
||||
end
|
||||
|
||||
def call
|
||||
put(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: @user.gitea_token, data: @params)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{@user.try(:login)}/#{@repo}/pulls/#{@pull_request_id}".freeze
|
||||
end
|
||||
|
||||
end
|
||||
22
app/services/gitea/repository/branches_service.rb
Normal file
22
app/services/gitea/repository/branches_service.rb
Normal file
@@ -0,0 +1,22 @@
|
||||
class Gitea::Repository::BranchesService < Gitea::ClientService
|
||||
attr_reader :user, :repo
|
||||
|
||||
def initialize(user, repo)
|
||||
@user = user
|
||||
@repo = repo
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_data(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}/branches".freeze
|
||||
end
|
||||
end
|
||||
35
app/services/gitea/repository/commits/get_service.rb
Normal file
35
app/services/gitea/repository/commits/get_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
# Get a single commit from a repository
|
||||
class Gitea::Repository::Commits::GetService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :sha
|
||||
|
||||
# sha: the commit hash
|
||||
def initialize(user, repo_name, sha)
|
||||
@user = user
|
||||
@sha = sha
|
||||
@repo_name = repo_name
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/git/commits/#{sha}".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200
|
||||
JSON.parse(response.body)
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
39
app/services/gitea/repository/commits/list_service.rb
Normal file
39
app/services/gitea/repository/commits/list_service.rb
Normal file
@@ -0,0 +1,39 @@
|
||||
# Get a list of all commits from a repository
|
||||
class Gitea::Repository::Commits::ListService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :args
|
||||
|
||||
# sha: SHA or branch to start listing commits from (usually 'master')
|
||||
def initialize(user, repo_name, **args)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@args = { sha: 'master', page: 1 }.merge(args.compact)
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
@args.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/commits".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200
|
||||
result = {}
|
||||
headers = response.headers.to_hash
|
||||
body = JSON.parse(response.body)
|
||||
total_count = headers["x-total"]
|
||||
result.merge(total_count: total_count.to_i, body: body)
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
34
app/services/gitea/repository/create_service.rb
Normal file
34
app/services/gitea/repository/create_service.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
class Gitea::Repository::CreateService < Gitea::ClientService
|
||||
attr_reader :token, :params
|
||||
|
||||
# params EX:
|
||||
# {
|
||||
# "auto_init": true,
|
||||
# "description": "string",
|
||||
# "gitignores": "string",
|
||||
# "issue_labels": "string",
|
||||
# "license": "string",
|
||||
# "name": "string", *
|
||||
# "private": true,
|
||||
# "readme": "string"
|
||||
# }
|
||||
def initialize(token, params)
|
||||
@token = token
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: token, data: params)
|
||||
end
|
||||
|
||||
def url
|
||||
"/user/repos".freeze
|
||||
end
|
||||
|
||||
end
|
||||
22
app/services/gitea/repository/delete_service.rb
Normal file
22
app/services/gitea/repository/delete_service.rb
Normal file
@@ -0,0 +1,22 @@
|
||||
class Gitea::Repository::DeleteService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name
|
||||
|
||||
def initialize(user, repo_name)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
end
|
||||
|
||||
def call
|
||||
delete(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}".freeze
|
||||
end
|
||||
end
|
||||
43
app/services/gitea/repository/entries/create_service.rb
Normal file
43
app/services/gitea/repository/entries/create_service.rb
Normal file
@@ -0,0 +1,43 @@
|
||||
class Gitea::Repository::Entries::CreateService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :filepath, :body
|
||||
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
# filepath: path of the dir, file, symlink or submodule in the repo
|
||||
# repo_name: the name of repository
|
||||
# body:
|
||||
# {
|
||||
# "author": {
|
||||
# "email": "user@example.com",
|
||||
# "name": "string"
|
||||
# },
|
||||
# "branch": "string",
|
||||
# "committer": {
|
||||
# "email": "user@example.com",
|
||||
# "name": "string"
|
||||
# },
|
||||
# "content": "string", # content must be base64 encoded
|
||||
# "message": "string",
|
||||
# "new_branch": "string"
|
||||
# }
|
||||
#
|
||||
def initialize(user, repo_name, filepath, body)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@filepath = filepath
|
||||
@body = body
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token, data: body)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/contents/#{filepath}".freeze
|
||||
end
|
||||
|
||||
end
|
||||
42
app/services/gitea/repository/entries/delete_service.rb
Normal file
42
app/services/gitea/repository/entries/delete_service.rb
Normal file
@@ -0,0 +1,42 @@
|
||||
class Gitea::Repository::Entries::DeleteService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :filepath, :body
|
||||
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
# filepath: path of the dir, file, symlink or submodule in the repo
|
||||
# repo_name: the name of repository
|
||||
# body:
|
||||
# {
|
||||
# "author": {
|
||||
# "email": "user@example.com",
|
||||
# "name": "string"
|
||||
# },
|
||||
# "branch": "string",
|
||||
# "committer": {
|
||||
# "email": "user@example.com",
|
||||
# "name": "string"
|
||||
# },
|
||||
# "message": "string",
|
||||
# "new_branch": "string",
|
||||
# "sha": "string", #require
|
||||
# }
|
||||
def initialize(user, repo_name, filepath, body)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@filepath = filepath
|
||||
@body = body
|
||||
end
|
||||
|
||||
def call
|
||||
delete(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token, data: body)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/contents/#{filepath}".freeze
|
||||
end
|
||||
|
||||
end
|
||||
38
app/services/gitea/repository/entries/get_service.rb
Normal file
38
app/services/gitea/repository/entries/get_service.rb
Normal file
@@ -0,0 +1,38 @@
|
||||
class Gitea::Repository::Entries::GetService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :filepath, :args
|
||||
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
# filepath: path of the dir, file, symlink or submodule in the repo
|
||||
# repo_name: the name of repository
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
def initialize(user, repo_name, filepath, **args)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@filepath = filepath
|
||||
@args = {ref: 'master'}.merge(args.compact)
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
@args.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/contents/#{filepath}".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200
|
||||
body
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
35
app/services/gitea/repository/entries/list_service.rb
Normal file
35
app/services/gitea/repository/entries/list_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Gitea::Repository::Entries::ListService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :args
|
||||
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
# repo_name: the name of repository
|
||||
def initialize(user, repo_name, **args)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@args = {ref: 'master'}.merge(args.compact)
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
@args.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/contents".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200
|
||||
body
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
43
app/services/gitea/repository/entries/update_service.rb
Normal file
43
app/services/gitea/repository/entries/update_service.rb
Normal file
@@ -0,0 +1,43 @@
|
||||
class Gitea::Repository::Entries::UpdateService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name, :filepath, :body
|
||||
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
# filepath: path of the dir, file, symlink or submodule in the repo
|
||||
# repo_name: the name of repository
|
||||
# body:
|
||||
# {
|
||||
# "author": {
|
||||
# "email": "user@example.com",
|
||||
# "name": "string"
|
||||
# },
|
||||
# "branch": "string",
|
||||
# "committer": {
|
||||
# "email": "user@example.com",
|
||||
# "name": "string"
|
||||
# },
|
||||
# "content": "string", # content must be base64 encoded
|
||||
# "message": "string",
|
||||
# "new_branch": "string"
|
||||
# }
|
||||
#
|
||||
def initialize(user, repo_name, filepath, body)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
@filepath = filepath
|
||||
@body = body
|
||||
end
|
||||
|
||||
def call
|
||||
put(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token, data: body)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/contents/#{filepath}".freeze
|
||||
end
|
||||
|
||||
end
|
||||
32
app/services/gitea/repository/fork_service.rb
Normal file
32
app/services/gitea/repository/fork_service.rb
Normal file
@@ -0,0 +1,32 @@
|
||||
class Gitea::Repository::ForkService < Gitea::ClientService
|
||||
attr_reader :old_owner, :target_owner, :repo_name, :organization
|
||||
|
||||
# old_owner: 被clone的项目(源项目)拥有者
|
||||
# target_owner: clone后的醒目(新项目)的拥有者
|
||||
# body:
|
||||
# {
|
||||
# "organization": "string" #组织名称
|
||||
# }
|
||||
def initialize(old_owner, target_owner, repo_name, organization=nil)
|
||||
@old_owner = old_owner
|
||||
@target_owner = target_owner
|
||||
@repo_name = repo_name
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def request_params
|
||||
hash = Hash.new.merge(token: target_owner.gitea_token)
|
||||
hash = hash.merge(data: {organization: organization}) if organization
|
||||
hash
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{old_owner.login}/#{repo_name}/forks".freeze
|
||||
end
|
||||
|
||||
end
|
||||
31
app/services/gitea/repository/get_service.rb
Normal file
31
app/services/gitea/repository/get_service.rb
Normal file
@@ -0,0 +1,31 @@
|
||||
class Gitea::Repository::GetService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name
|
||||
|
||||
def initialize(user, repo_name)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
case response.status
|
||||
when 200
|
||||
JSON.parse(response.body)
|
||||
else
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
28
app/services/gitea/repository/members/add_service.rb
Normal file
28
app/services/gitea/repository/members/add_service.rb
Normal file
@@ -0,0 +1,28 @@
|
||||
# 添加协作者/或者更改协作这的可读写权限
|
||||
class Gitea::Repository::Members::AddService < Gitea::ClientService
|
||||
attr_reader :owner, :repo_name, :collaborator, :permission
|
||||
|
||||
# owner: owner of the repo
|
||||
# repo_name: name of the repo
|
||||
# collaborator: username of the collaborator
|
||||
# permission: permission name, FIX: admin | read | write
|
||||
def initialize(owner, repo_name, collaborator, permission)
|
||||
@owner = owner
|
||||
@repo_name = repo_name
|
||||
@collaborator = collaborator
|
||||
@permission = permission
|
||||
end
|
||||
|
||||
def call
|
||||
put(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: owner.gitea_token, data: {permission: permission})
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{owner.login}/#{repo_name}/collaborators/#{collaborator}".freeze
|
||||
end
|
||||
end
|
||||
25
app/services/gitea/repository/members/delete_service.rb
Normal file
25
app/services/gitea/repository/members/delete_service.rb
Normal file
@@ -0,0 +1,25 @@
|
||||
class Gitea::Repository::Members::DeleteService < Gitea::ClientService
|
||||
attr_reader :owner, :repo_name, :collaborator
|
||||
|
||||
# owner: owner of the repo
|
||||
# repo_name: name of the repo
|
||||
# collaborator: username of the collaborator
|
||||
def initialize(owner, repo_name, collaborator)
|
||||
@owner = owner
|
||||
@repo_name = repo_name
|
||||
@collaborator = collaborator
|
||||
end
|
||||
|
||||
def call
|
||||
delete(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: owner.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{owner.login}/#{repo_name}/collaborators/#{collaborator}".freeze
|
||||
end
|
||||
end
|
||||
47
app/services/gitea/repository/migrate_service.rb
Normal file
47
app/services/gitea/repository/migrate_service.rb
Normal file
@@ -0,0 +1,47 @@
|
||||
class Gitea::Repository::MigrateService < Gitea::ClientService
|
||||
attr_reader :token, :params
|
||||
|
||||
# params description:
|
||||
# {
|
||||
# auth_username string
|
||||
# clone_addr* string #clone地址
|
||||
# description string
|
||||
# issues boolean
|
||||
# labels boolean
|
||||
# milestones boolean
|
||||
# mirror boolean
|
||||
# private boolean
|
||||
# pull_requests boolean
|
||||
# releases boolean
|
||||
# repo_name* string #仓库名称
|
||||
# uid* integer($int64) #gitea用户id或组织id
|
||||
# wiki boolean
|
||||
# }
|
||||
# EX:
|
||||
# params = {
|
||||
# clone_addr: 'xxx.com',
|
||||
# repo_name: 'repo_name',
|
||||
# uid: 2,
|
||||
# private: false
|
||||
# }
|
||||
|
||||
def initialize(token, params)
|
||||
@token = token
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: token, data: params)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/migrate".freeze
|
||||
end
|
||||
|
||||
end
|
||||
33
app/services/gitea/repository/tags/list_service.rb
Normal file
33
app/services/gitea/repository/tags/list_service.rb
Normal file
@@ -0,0 +1,33 @@
|
||||
class Gitea::Repository::Tags::ListService < Gitea::ClientService
|
||||
attr_reader :user, :repo_name
|
||||
|
||||
# ref: The name of the commit/branch/tag. Default the repository’s default branch (usually master)
|
||||
# repo_name: the name of repository
|
||||
def initialize(user, repo_name)
|
||||
@user = user
|
||||
@repo_name = repo_name
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: user.gitea_token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo_name}/tags".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200 then body
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
33
app/services/gitea/repository/update_service.rb
Normal file
33
app/services/gitea/repository/update_service.rb
Normal file
@@ -0,0 +1,33 @@
|
||||
class Gitea::Repository::UpdateService < Gitea::ClientService
|
||||
attr_reader :user, :repo, :params
|
||||
|
||||
# params:
|
||||
# {
|
||||
# name: 'name of the repository',
|
||||
# default_branch: 'sets the default branch for this repository.',
|
||||
# description: 'string a short description of the repository.',
|
||||
# private: 'boolean either true to make the repository private or false to make it public.',
|
||||
# has_issues: 'boolean either true to enable issues for this repository or false to disable them.',
|
||||
# has_pull_requests: 'boolean either true to allow pull requests, or false to prevent pull request.',
|
||||
# allow_merge_commits: 'boolean either true to allow merging pull requests with a merge commit, or false to prevent merging pull requests with merge commits. has_pull_requests must be true.'
|
||||
# }
|
||||
|
||||
def initialize(user, repo, params={})
|
||||
@user = user
|
||||
@repo = repo
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
patch(url, data_params)
|
||||
end
|
||||
|
||||
private
|
||||
def url
|
||||
"/repos/#{user.login}/#{repo}"
|
||||
end
|
||||
|
||||
def data_params
|
||||
Hash.new.merge(token: user.gitea_token, data: params)
|
||||
end
|
||||
end
|
||||
28
app/services/gitea/user/generate_token_service.rb
Normal file
28
app/services/gitea/user/generate_token_service.rb
Normal file
@@ -0,0 +1,28 @@
|
||||
# 根据对应的用户名和秘密生成token
|
||||
class Gitea::User::GenerateTokenService < Gitea::ClientService
|
||||
attr_reader :username, :password
|
||||
|
||||
def initialize(username, password)
|
||||
@username = username
|
||||
@password = password
|
||||
end
|
||||
|
||||
def call
|
||||
params = {}
|
||||
url = "/users/#{username}/tokens".freeze
|
||||
params = params.merge(token: token_params, data: request_params)
|
||||
post(url, params)
|
||||
end
|
||||
|
||||
private
|
||||
def token_params
|
||||
{
|
||||
username: username,
|
||||
password: password
|
||||
}
|
||||
end
|
||||
|
||||
def request_params
|
||||
{ name: username }
|
||||
end
|
||||
end
|
||||
28
app/services/gitea/user/register_service.rb
Normal file
28
app/services/gitea/user/register_service.rb
Normal file
@@ -0,0 +1,28 @@
|
||||
class Gitea::User::RegisterService < Gitea::ClientService
|
||||
API_REST = "/admin/users"
|
||||
def initialize(options = {})
|
||||
options.each_pair do |key, value|
|
||||
instance_variable_set("@#{key}", value)
|
||||
end
|
||||
end
|
||||
|
||||
def call
|
||||
params = {}
|
||||
params = params.merge(data: user_params)
|
||||
post(API_REST, params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :email, :username, :password
|
||||
|
||||
def user_params
|
||||
{
|
||||
email: email,
|
||||
username: username,
|
||||
password: password,
|
||||
must_change_password: false #允许不更改秘密就可以登录
|
||||
}
|
||||
end
|
||||
|
||||
end
|
||||
34
app/services/gitea/versions/create_service.rb
Normal file
34
app/services/gitea/versions/create_service.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
class Gitea::Versions::CreateService < Gitea::ClientService
|
||||
attr_reader :token, :user_name, :repo, :params
|
||||
|
||||
# params EX:
|
||||
# {
|
||||
# "body": "sylor", #user_name
|
||||
# "draft": false,
|
||||
# "name": "string",
|
||||
# "prerelease": true,
|
||||
# "tag_name": "string",
|
||||
# "target_commitish": "string"
|
||||
# }
|
||||
def initialize(token, user_name, repo, params)
|
||||
@token = token
|
||||
@params = params
|
||||
@user_name = user_name
|
||||
@repo = repo
|
||||
end
|
||||
|
||||
def call
|
||||
post(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: token, data: params)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{@user_name}/#{@repo}/releases".freeze
|
||||
end
|
||||
|
||||
end
|
||||
26
app/services/gitea/versions/delete_service.rb
Normal file
26
app/services/gitea/versions/delete_service.rb
Normal file
@@ -0,0 +1,26 @@
|
||||
class Gitea::Versions::DeleteService < Gitea::ClientService
|
||||
attr_reader :token, :user_name, :repo,:version_gid
|
||||
|
||||
def initialize(token, user_name, repo,version_gid)
|
||||
@token = token
|
||||
@user_name = user_name
|
||||
@repo = repo
|
||||
@version_gid = version_gid
|
||||
end
|
||||
|
||||
def call
|
||||
response = delete(url, params)
|
||||
return response
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def params
|
||||
Hash.new.merge(token: @token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{@user_name}/#{@repo}/releases/#{@version_gid}".freeze
|
||||
end
|
||||
|
||||
end
|
||||
35
app/services/gitea/versions/list_service.rb
Normal file
35
app/services/gitea/versions/list_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
# Get a list of all commits from a repository
|
||||
class Gitea::Versions::ListService < Gitea::ClientService
|
||||
attr_reader :token, :user_name, :repo
|
||||
|
||||
# sha: SHA or branch to start listing commits from (usually 'master')
|
||||
def initialize(token, user_name, repo)
|
||||
@token = token
|
||||
@user_name = user_name
|
||||
@repo = repo
|
||||
end
|
||||
|
||||
def call
|
||||
response = get(url, params)
|
||||
render_result(response)
|
||||
end
|
||||
|
||||
private
|
||||
def params
|
||||
Hash.new.merge(token: token)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{@user_name}/#{@repo}/releases".freeze
|
||||
end
|
||||
|
||||
def render_result(response)
|
||||
body = JSON.parse(response.body)
|
||||
case response.status
|
||||
when 200
|
||||
body
|
||||
else
|
||||
{status: -1, message: "#{body['message']}"}
|
||||
end
|
||||
end
|
||||
end
|
||||
35
app/services/gitea/versions/update_service.rb
Normal file
35
app/services/gitea/versions/update_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Gitea::Versions::UpdateService < Gitea::ClientService
|
||||
attr_reader :token, :user_name, :repo, :params, :version_gid
|
||||
|
||||
# params EX:
|
||||
# {
|
||||
# "body": "sylor", #user_name
|
||||
# "draft": false,
|
||||
# "name": "string",
|
||||
# "prerelease": true,
|
||||
# "tag_name": "string",
|
||||
# "target_commitish": "string"
|
||||
# }
|
||||
def initialize(token, user_name, repo, params,version_gid)
|
||||
@token = token
|
||||
@params = params
|
||||
@user_name = user_name
|
||||
@repo = repo
|
||||
@version_gid = version_gid
|
||||
end
|
||||
|
||||
def call
|
||||
patch(url, request_params)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def request_params
|
||||
Hash.new.merge(token: token, data: params)
|
||||
end
|
||||
|
||||
def url
|
||||
"/repos/#{@user_name}/#{@repo}/releases/#{@version_gid}".freeze
|
||||
end
|
||||
|
||||
end
|
||||
32
app/services/libraries/agree_apply_service.rb
Normal file
32
app/services/libraries/agree_apply_service.rb
Normal file
@@ -0,0 +1,32 @@
|
||||
class Libraries::AgreeApplyService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :library_apply, :library, :user
|
||||
|
||||
def initialize(library_apply, user)
|
||||
@library_apply = library_apply
|
||||
@library = library_apply.library
|
||||
@user = user
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '该状态下不能进行此操作' unless library_apply.may_agree?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
library_apply.agree!
|
||||
library_apply.library.publish!
|
||||
|
||||
# 将消息改为已处理
|
||||
Tiding.where(container_id: library.id, container_type: 'Library', tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
notify_library_author!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def notify_library_author!
|
||||
Tiding.create!(user_id: library.user_id, trigger_user_id: 0,
|
||||
container_id: library.id, container_type: 'Library',
|
||||
tiding_type: 'System', status: 1)
|
||||
end
|
||||
end
|
||||
39
app/services/libraries/refuse_apply_service.rb
Normal file
39
app/services/libraries/refuse_apply_service.rb
Normal file
@@ -0,0 +1,39 @@
|
||||
class Libraries::RefuseApplyService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :library_apply, :library, :user, :params
|
||||
|
||||
def initialize(library_apply, user, params)
|
||||
@library_apply = library_apply
|
||||
@library = library_apply.library
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
reason = params[:reason].to_s.strip
|
||||
raise Error, '原因不能为空' if reason.blank?
|
||||
raise Error, '该状态下不能进行此操作' unless library_apply.may_refuse?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
library_apply.reason = reason
|
||||
library_apply.refused_at = Time.current
|
||||
library_apply.refuse
|
||||
library_apply.save!
|
||||
|
||||
library.refuse!
|
||||
|
||||
# 将消息改为已处理
|
||||
Tiding.where(container_id: library.id, container_type: 'Library', tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
notify_library_author!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def notify_library_author!
|
||||
Tiding.create!(user_id: library.user_id, trigger_user_id: 0,
|
||||
container_id: library.id, container_type: 'Library',
|
||||
tiding_type: 'System', status: 2, extra: library_apply.reason)
|
||||
end
|
||||
end
|
||||
69
app/services/libraries/save_service.rb
Normal file
69
app/services/libraries/save_service.rb
Normal file
@@ -0,0 +1,69 @@
|
||||
class Libraries::SaveService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :library, :user, :params
|
||||
|
||||
def initialize(library, user, params)
|
||||
@library = library
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
Libraries::SaveForm.new(params).validate!
|
||||
|
||||
if library.new_record?
|
||||
library.user_id = user.id
|
||||
library.generate_uuid
|
||||
end
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
library.assign_attributes(library_params)
|
||||
library.save!
|
||||
|
||||
deal_library_tag!
|
||||
deal_attachments!
|
||||
|
||||
Libraries::SubmitService.call(library) if with_publish?
|
||||
end
|
||||
|
||||
library
|
||||
rescue Libraries::SubmitService::Error => ex
|
||||
raise Error, ex.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def deal_library_tag!
|
||||
new_tag_ids = LibraryTag.where(id: Array.wrap(params[:tag_ids]).compact).pluck(:id)
|
||||
old_tag_ids = library.library_library_tags.pluck(:library_tag_id)
|
||||
|
||||
# 删除标签
|
||||
destroy_ids = old_tag_ids - new_tag_ids
|
||||
library.library_library_tags.where(library_tag_id: destroy_ids).delete_all
|
||||
|
||||
# 创建标签
|
||||
created_ids = new_tag_ids - old_tag_ids
|
||||
created_ids.each do |id|
|
||||
library.library_library_tags.create!(library_tag_id: id)
|
||||
end
|
||||
end
|
||||
|
||||
def deal_attachments!
|
||||
attachment_ids = Array.wrap(params[:attachment_ids]).compact.map(&:to_i)
|
||||
old_attachment_id = library.attachments.pluck(:id)
|
||||
|
||||
destroy_ids = old_attachment_id - attachment_ids
|
||||
library.attachments.where(id: destroy_ids).delete_all
|
||||
|
||||
Attachment.where(id: attachment_ids, author_id: user.id).update_all(container_type: library.class.to_s, container_id: library.id)
|
||||
end
|
||||
|
||||
def library_params
|
||||
params.slice(*%i[title content author_name author_school_name cover_id])
|
||||
end
|
||||
|
||||
def with_publish?
|
||||
params[:publish].to_s == 'true'
|
||||
end
|
||||
end
|
||||
32
app/services/libraries/submit_service.rb
Normal file
32
app/services/libraries/submit_service.rb
Normal file
@@ -0,0 +1,32 @@
|
||||
class Libraries::SubmitService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :library
|
||||
|
||||
def initialize(library)
|
||||
@library = library
|
||||
end
|
||||
|
||||
def call
|
||||
return if library.processing? || library.published?
|
||||
|
||||
raise Error, '该状态下不能提交审核' unless library.may_submit?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
library.published_at = Time.current
|
||||
library.submit
|
||||
library.save!
|
||||
|
||||
library.library_applies.create!
|
||||
send_library_apply_notify!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def send_library_apply_notify!
|
||||
Tiding.create!(user_id: 1, trigger_user_id: library.user_id,
|
||||
container_id: library.id, container_type: 'Library',
|
||||
tiding_type: 'Apply', status: 0)
|
||||
end
|
||||
end
|
||||
31
app/services/oauth/create_or_find_cas_user_service.rb
Normal file
31
app/services/oauth/create_or_find_cas_user_service.rb
Normal file
@@ -0,0 +1,31 @@
|
||||
class Oauth::CreateORFindCasUserService < ApplicationService
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
return [@user, false] if @user
|
||||
|
||||
open_user = OpenUsers::Cas.find_or_initialize_by(uid: @params['user']) do |u|
|
||||
u.extra = @params
|
||||
end
|
||||
|
||||
return [open_user.user, false] if open_user.persisted?
|
||||
|
||||
@user = User.new(login: User.generate_login('C'), type: 'User', status: User::STATUS_ACTIVE, nickname: @params['comsys_name'], lastname: @params['comsys_name'])
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
@user.save!
|
||||
@user.create_user_extension!
|
||||
|
||||
open_user.user = @user
|
||||
open_user.save!
|
||||
|
||||
Rails.cache.write(open_user.can_bind_cache_key, 1, expires_in: 1.hours)
|
||||
end
|
||||
|
||||
[@user, true]
|
||||
end
|
||||
end
|
||||
42
app/services/oauth/create_or_find_qq_account_service.rb
Normal file
42
app/services/oauth/create_or_find_qq_account_service.rb
Normal file
@@ -0,0 +1,42 @@
|
||||
class Oauth::CreateOrFindQqAccountService < ApplicationService
|
||||
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
new_user = false
|
||||
# 存在该用户
|
||||
open_user = OpenUsers::QQ.find_by(uid: params['uid'])
|
||||
return [open_user.user, new_user] if open_user.present?
|
||||
|
||||
if user.blank? || !user.logged?
|
||||
new_user = true
|
||||
# 新用户
|
||||
login = User.generate_login('Q')
|
||||
#nickname = regix_emoji params.dig('info', 'nickname')
|
||||
@user = User.new(login: login, type: 'User', status: User::STATUS_ACTIVE)
|
||||
end
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
if user.new_record?
|
||||
user.save!
|
||||
|
||||
gender = params.dig('extra', 'raw_info', 'gender') == '女' ? 1 : 0
|
||||
user.create_user_extension!(gender: gender)
|
||||
# 下载头像
|
||||
avatar_path = Util::FileManage.source_disk_filename(user)
|
||||
Util.download_file(params.dig('info', 'image'), avatar_path)
|
||||
end
|
||||
|
||||
new_open_user = OpenUsers::QQ.create!(user: user, uid: params['uid'])
|
||||
|
||||
Rails.cache.write(new_open_user.can_bind_cache_key, 1, expires_in: 1.hours) if new_user # 方便后面进行账号绑定
|
||||
end
|
||||
|
||||
[user, new_user]
|
||||
end
|
||||
end
|
||||
65
app/services/oauth/create_or_find_wechat_account_service.rb
Normal file
65
app/services/oauth/create_or_find_wechat_account_service.rb
Normal file
@@ -0,0 +1,65 @@
|
||||
class Oauth::CreateOrFindWechatAccountService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
code = params['code'].to_s.strip
|
||||
raise Error, 'Code不能为空' if code.blank?
|
||||
new_user = false
|
||||
|
||||
result = WechatOauth::Service.access_token(code)
|
||||
result = WechatOauth::Service.user_info(result['access_token'], result['openid'])
|
||||
|
||||
# 存在该用户
|
||||
open_user = OpenUsers::Wechat.find_by(uid: result['unionid'])
|
||||
return [open_user.user, new_user] if open_user.present? && open_user.user.present?
|
||||
|
||||
if user.blank? || !user.logged?
|
||||
new_user = true
|
||||
# 新用户
|
||||
# login = User.generate_login('w')
|
||||
# result['nickname'] = regix_emoji(result['nickname'])
|
||||
# @user = User.new(login: login, type: 'User', status: User::STATUS_ACTIVE)
|
||||
# @user = User.new(login: login, nickname: result['nickname'], type: 'User', status: User::STATUS_ACTIVE)
|
||||
set_session_openid(result['openid'])
|
||||
set_session_unionid(result['unionid'])
|
||||
else
|
||||
OpenUsers::Wechat.create!(user: user, uid: result['unionid'])
|
||||
end
|
||||
|
||||
=begin
|
||||
ActiveRecord::Base.transaction do
|
||||
if new_user
|
||||
user.save!
|
||||
|
||||
gender = result['sex'].to_i == 1 ? 0 : 1
|
||||
user.create_user_extension!(gender: gender)
|
||||
|
||||
# 下载头像
|
||||
avatar_path = Util::FileManage.source_disk_filename(user)
|
||||
Util.download_file(result['headimgurl'], avatar_path)
|
||||
end
|
||||
|
||||
new_open_user= OpenUsers::Wechat.create!(user: user, uid: result['unionid'])
|
||||
|
||||
Rails.cache.write(new_open_user.can_bind_cache_key, 1, expires_in: 1.hours) if new_user # 方便后面进行账号绑定
|
||||
end
|
||||
=end
|
||||
|
||||
[user, new_user]
|
||||
rescue WechatOauth::Error => ex
|
||||
raise Error, ex.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def code
|
||||
params[:code].to_s.strip
|
||||
end
|
||||
end
|
||||
35
app/services/private_messages/create_service.rb
Normal file
35
app/services/private_messages/create_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class PrivateMessages::CreateService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :sender, :receiver, :params
|
||||
|
||||
def initialize(sender, receiver, params)
|
||||
@sender = sender
|
||||
@receiver = receiver
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
validate!
|
||||
|
||||
same_attr = { sender: sender, receiver: receiver, content: content, send_time: Time.now }
|
||||
|
||||
message = nil
|
||||
ActiveRecord::Base.transaction do
|
||||
message = sender.private_messages.create!(same_attr.merge(target: receiver, status: 1))
|
||||
receiver.private_messages.create!(same_attr.merge(target: sender, status: 0))
|
||||
end
|
||||
message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def content
|
||||
@_content ||= params[:content].to_s.strip
|
||||
end
|
||||
|
||||
def validate!
|
||||
raise Error, '内容不能为空' if content.blank?
|
||||
raise Error, '内容太长' if content.size > 500
|
||||
end
|
||||
end
|
||||
36
app/services/project_packages/agree_apply_service.rb
Normal file
36
app/services/project_packages/agree_apply_service.rb
Normal file
@@ -0,0 +1,36 @@
|
||||
class ProjectPackages::AgreeApplyService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :apply, :package
|
||||
|
||||
def initialize(apply)
|
||||
@apply = apply
|
||||
@package = apply.project_package
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '该状态下不能进行此操作' unless apply.may_agree? && package.may_publish?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.agree!
|
||||
|
||||
# 发布
|
||||
package.publish
|
||||
package.published_at = Time.now
|
||||
package.save!
|
||||
|
||||
# 消息
|
||||
send_agree_notify!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
def send_agree_notify!
|
||||
Tiding.where(container_id: package.id, container_type: 'ProjectPackage',
|
||||
tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: package.creator_id, trigger_user_id: 0,
|
||||
container_id: package.id, container_type: 'ProjectPackage',
|
||||
tiding_type: 'System', status: 1)
|
||||
end
|
||||
end
|
||||
31
app/services/project_packages/apply_publish_service.rb
Normal file
31
app/services/project_packages/apply_publish_service.rb
Normal file
@@ -0,0 +1,31 @@
|
||||
class ProjectPackages::ApplyPublishService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :package
|
||||
|
||||
def initialize(package)
|
||||
@package = package
|
||||
end
|
||||
|
||||
def call
|
||||
return if package.applying?
|
||||
|
||||
raise Error, '该状态下不能申请发布' unless package.may_apply?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
package.apply!
|
||||
|
||||
package.project_package_applies.create!
|
||||
|
||||
send_project_package_apply_notify!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def send_project_package_apply_notify!
|
||||
Tiding.create!(user_id: 1, trigger_user_id: package.creator_id,
|
||||
container_id: package.id, container_type: 'ProjectPackage',
|
||||
tiding_type: 'Apply', status: 0)
|
||||
end
|
||||
end
|
||||
29
app/services/project_packages/bidding_service.rb
Normal file
29
app/services/project_packages/bidding_service.rb
Normal file
@@ -0,0 +1,29 @@
|
||||
class ProjectPackages::BiddingService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :package, :user
|
||||
|
||||
def initialize(package, user)
|
||||
@package = package
|
||||
@user = user
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '竞标已截止' if package.bidding_end?
|
||||
raise Error, '不能参与自己发布的竞标' if package.creator_id == user.id
|
||||
raise Error, '您已参与竞标' if package.bidding_users.exists?(user_id: user.id)
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
package.bidding_users.create!(user_id: user.id)
|
||||
|
||||
send_bidding_notify!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def send_bidding_notify!
|
||||
Tiding.create!(user_id: package.creator_id, trigger_user_id: user.id,
|
||||
container_id: package.id, container_type: 'ProjectPackage', tiding_type: 'Bidding')
|
||||
end
|
||||
end
|
||||
26
app/services/project_packages/end_bidding_service.rb
Normal file
26
app/services/project_packages/end_bidding_service.rb
Normal file
@@ -0,0 +1,26 @@
|
||||
class ProjectPackages::EndBiddingService < ApplicationService
|
||||
attr_reader :package
|
||||
|
||||
def initialize(package)
|
||||
@package = package
|
||||
end
|
||||
|
||||
def call
|
||||
return unless package_deadline?
|
||||
|
||||
package.end_bidding!
|
||||
|
||||
send_bidding_end_notify!
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def send_bidding_end_notify!
|
||||
Tiding.create!(user_id: package.creator_id, trigger_user_id: 0,
|
||||
container_id: package.id, container_type: 'ProjectPackage', tiding_type: 'BiddingEnd')
|
||||
end
|
||||
|
||||
def package_deadline?
|
||||
package.may_end_bidding? && package.deadline_at < Time.now
|
||||
end
|
||||
end
|
||||
38
app/services/project_packages/refuse_apply_service.rb
Normal file
38
app/services/project_packages/refuse_apply_service.rb
Normal file
@@ -0,0 +1,38 @@
|
||||
class ProjectPackages::RefuseApplyService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :apply, :package, :params
|
||||
|
||||
def initialize(apply, params)
|
||||
@apply = apply
|
||||
@package = apply.project_package
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '该状态下不能进行此操作' unless apply.may_refuse? && package.may_refuse?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
apply.refuse
|
||||
apply.reason = params[:reason].to_s.strip
|
||||
apply.save!
|
||||
|
||||
# 发布
|
||||
package.refuse!
|
||||
|
||||
# 消息
|
||||
send_refuse_notify!
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def send_refuse_notify!
|
||||
Tiding.where(container_id: package.id, container_type: 'ProjectPackage',
|
||||
tiding_type: 'Apply', status: 0).update_all(status: 1)
|
||||
|
||||
Tiding.create!(user_id: package.creator_id, trigger_user_id: 0,
|
||||
container_id: package.id, container_type: 'ProjectPackage',
|
||||
tiding_type: 'System', status: 2, extra: apply.reason)
|
||||
end
|
||||
end
|
||||
81
app/services/project_packages/save_service.rb
Normal file
81
app/services/project_packages/save_service.rb
Normal file
@@ -0,0 +1,81 @@
|
||||
class ProjectPackages::SaveService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :package, :params
|
||||
|
||||
def initialize(package, params)
|
||||
@package = package
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
ProjectPackages::SaveForm.new(params).validate!
|
||||
|
||||
check_code_valid! if need_check_code?
|
||||
|
||||
is_create = package.new_record?
|
||||
raise Error, '类型不存在' unless ProjectPackageCategory.where(id: params[:category_id]).exists?
|
||||
params[:project_package_category_id] = params.delete(:category_id).to_i
|
||||
|
||||
raise Error, '竞标截止时间不能小于当前时间' if params[:deadline_at].present? && params[:deadline_at].to_time < Time.now
|
||||
|
||||
if params[:min_price].blank? && params[:max_price].present?
|
||||
params[:min_price] = params[:max_price]
|
||||
params[:max_price] = nil
|
||||
end
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
columns = %i[project_package_category_id title content deadline_at
|
||||
min_price max_price contact_name contact_phone]
|
||||
package.assign_attributes(params.slice(*columns))
|
||||
package.save!
|
||||
|
||||
# 处理附件
|
||||
deal_attachments
|
||||
|
||||
send_create_notify! if is_create
|
||||
|
||||
ProjectPackages::ApplyPublishService.call(package) if with_publish?
|
||||
end
|
||||
|
||||
package
|
||||
rescue ProjectPackages::ApplyPublishService::Error => ex
|
||||
raise Error, ex.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def need_check_code?
|
||||
(package.new_record? && params[:contact_phone] != package.creator.phone) ||
|
||||
(!package.new_record? && package.contact_phone != params[:contact_phone])
|
||||
end
|
||||
|
||||
def check_code_valid!
|
||||
raise Error, '验证码不能为空' if params[:code].blank?
|
||||
|
||||
code = VerificationCode.where(phone: params[:contact_phone], code_type: 9, code: params[:code]).last
|
||||
raise Error, '无效的验证码' if code.blank? || !code.effective?
|
||||
end
|
||||
|
||||
def deal_attachments
|
||||
attachment_ids = Array.wrap(params[:attachment_ids]).compact.map(&:to_i) || []
|
||||
old_attachment_ids = package.attachments.pluck(:id)
|
||||
|
||||
destroy_ids = old_attachment_ids - attachment_ids
|
||||
package.attachments.where(id: destroy_ids).delete_all
|
||||
|
||||
new_ids = attachment_ids - old_attachment_ids
|
||||
if new_ids.present?
|
||||
Attachment.where(id: new_ids, container_id: nil).update_all(container_id: package.id, container_type: 'ProjectPackage')
|
||||
end
|
||||
end
|
||||
|
||||
def send_create_notify!
|
||||
Tiding.create!(user_id: package.creator_id, trigger_user_id: 0,
|
||||
container_id: package.id, container_type: 'ProjectPackage', tiding_type: 'Created')
|
||||
end
|
||||
|
||||
def with_publish?
|
||||
params[:publish].to_s == 'true'
|
||||
end
|
||||
end
|
||||
52
app/services/project_packages/win_bidding_service.rb
Normal file
52
app/services/project_packages/win_bidding_service.rb
Normal file
@@ -0,0 +1,52 @@
|
||||
class ProjectPackages::WinBiddingService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :package, :user, :params
|
||||
|
||||
def initialize(package, user, params)
|
||||
@package = package
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
raise Error, '没有权限' unless package.creator_id == user.id || user.admin_or_business?
|
||||
raise Error, '竞标报名还未结束' unless package.bidding_end?
|
||||
raise Error, '该状态下不能选择中标者' unless package.may_finish_bidding?
|
||||
|
||||
win_user_ids = Array.wrap(params[:user_ids]).compact.map(&:to_i)
|
||||
bidding_user_ids = package.bidding_users.pluck(:user_id)
|
||||
|
||||
win_user_ids = bidding_user_ids & win_user_ids
|
||||
raise Error, '请选择中标者' if win_user_ids.blank?
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
package.finish_bidding!
|
||||
|
||||
# win bidding users
|
||||
package.bidding_users.where(user_id: win_user_ids).update_all(status: :bidding_won)
|
||||
# lose bidding users
|
||||
lost_user_ids = bidding_user_ids - win_user_ids
|
||||
package.bidding_users.where(user_id: lost_user_ids).update_all(status: :bidding_lost)
|
||||
|
||||
send_bidding_result_notify!('BiddingWon', win_user_ids)
|
||||
send_bidding_result_notify!('BiddingLost', lost_user_ids)
|
||||
end
|
||||
|
||||
package
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def send_bidding_result_notify!(type, user_ids)
|
||||
columns = %i[user_id trigger_user_id container_id container_type tiding_type created_at updated_at]
|
||||
|
||||
Tiding.bulk_insert(*columns) do |worker|
|
||||
base_attr = { trigger_user_id: package.creator_id, container_id: package.id,
|
||||
container_type: 'ProjectPackage', tiding_type: type }
|
||||
user_ids.each do |user_id|
|
||||
worker.add(base_attr.merge(user_id: user_id))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
85
app/services/projects/apply_join_service.rb
Normal file
85
app/services/projects/apply_join_service.rb
Normal file
@@ -0,0 +1,85 @@
|
||||
class Projects::ApplyJoinService < ApplicationService
|
||||
Error = Class.new(StandardError)
|
||||
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
validate!
|
||||
|
||||
# 项目报告人员直接加入项目
|
||||
if params[:role] == 'reporter'
|
||||
Projects::JoinService.call(project, user, role: 'reporter')
|
||||
return project
|
||||
end
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
apply = user.applied_projects.create!(project: project, role: role_value)
|
||||
|
||||
apply.forge_activities.find_or_create_by!(user: user, project: project)
|
||||
|
||||
notify_project_manager!(apply)
|
||||
end
|
||||
|
||||
# notify_project_owner
|
||||
ApplyJoinProjectNotifyJob.perform_later(user.id, project.id, role_value)
|
||||
|
||||
project
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def project
|
||||
@_project ||= Project.find_by(invite_code: params[:code].to_s.strip)
|
||||
end
|
||||
|
||||
def role_value
|
||||
@_role ||=
|
||||
case params[:role]
|
||||
when 'manager' then 3
|
||||
when 'developer' then 4
|
||||
when 'reporter' then 5
|
||||
else raise Error, '角色无效'
|
||||
end
|
||||
end
|
||||
|
||||
def notify_project_manager!(apply)
|
||||
columns = %i[user_id applied_id applied_type status viewed applied_user_id role project_id created_at updated_at]
|
||||
AppliedMessage.bulk_insert(*columns) do |worker|
|
||||
base_attr = {
|
||||
applied_id: apply.id, applied_type: 'AppliedProject', status: false, viewed: false,
|
||||
applied_user_id: user.id, role: role_value, project_id: project.id
|
||||
}
|
||||
|
||||
project.manager_members.each do |manager|
|
||||
worker.add(base_attr.merge(user_id: manager.user_id))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def notify_project_owner
|
||||
owner = project.user
|
||||
return if owner.phone.blank?
|
||||
|
||||
Educoder::Sms.send(mobile: owner.phone, send_type:'applied_project_info',
|
||||
user_name: owner.show_name, name: project.name)
|
||||
rescue Exception => ex
|
||||
Rails.logger.error("发送短信失败 => #{ex.message}")
|
||||
end
|
||||
|
||||
def validate!
|
||||
# params check
|
||||
raise Error, '邀请码不能为空' if params[:code].blank?
|
||||
raise Error, '角色不能为空' if params[:role].blank?
|
||||
raise Error, '角色无效' unless %w(manager developer reporter).include?(params[:role])
|
||||
|
||||
# logical check
|
||||
raise Error, '邀请码无效' if project.blank?
|
||||
raise Error, '您已在该项目中' if project.member?(user)
|
||||
raise Error, '您已经提交过申请' if user.applied_projects.pending.exists?(project: project)
|
||||
end
|
||||
end
|
||||
18
app/services/projects/change_member_role_service.rb
Normal file
18
app/services/projects/change_member_role_service.rb
Normal file
@@ -0,0 +1,18 @@
|
||||
class Projects::ChangeMemberRoleService < ApplicationService
|
||||
attr_reader :project, :user_id, :role
|
||||
|
||||
def initialize(project, user_id, role)
|
||||
@project = project
|
||||
@user_id = user_id
|
||||
@role = role
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
tmp_role = Role.find_by_name role
|
||||
@project.change_member_role!(user_id, tmp_role)
|
||||
end
|
||||
rescue => e
|
||||
raise Error, e.message
|
||||
end
|
||||
end
|
||||
51
app/services/projects/create_service.rb
Normal file
51
app/services/projects/create_service.rb
Normal file
@@ -0,0 +1,51 @@
|
||||
class Projects::CreateService < ApplicationService
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
@project = Project.new(project_params)
|
||||
ActiveRecord::Base.transaction do
|
||||
if @project.save!
|
||||
Repositories::CreateService.new(user, @project, repository_params).call
|
||||
else
|
||||
#
|
||||
end
|
||||
end
|
||||
@project
|
||||
rescue => e
|
||||
puts "create project service error: #{e.message}"
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def project_params
|
||||
{
|
||||
name: params[:name],
|
||||
user_id: params[:user_id],
|
||||
description: params[:description],
|
||||
project_category_id: params[:project_category_id],
|
||||
project_language_id: params[:project_language_id],
|
||||
is_public: get_is_public,
|
||||
ignore_id: params[:ignore_id],
|
||||
license_id: params[:license_id],
|
||||
identifier: params[:repository_name] #新增,hs
|
||||
}
|
||||
end
|
||||
|
||||
def repository_params
|
||||
{
|
||||
hidden: get_is_public,
|
||||
user_id: params[:user_id],
|
||||
identifier: params[:repository_name]
|
||||
}
|
||||
end
|
||||
|
||||
def get_is_public
|
||||
params[:private] || true
|
||||
end
|
||||
end
|
||||
38
app/services/projects/fork_service.rb
Normal file
38
app/services/projects/fork_service.rb
Normal file
@@ -0,0 +1,38 @@
|
||||
class Projects::ForkService < ApplicationService
|
||||
attr_reader :target_owner, :project, :organization
|
||||
|
||||
def initialize(target_owner, project, organization=nil)
|
||||
@target_owner = target_owner
|
||||
@project = project
|
||||
@organization = organization
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
clone_project =
|
||||
@project.deep_clone include: :repository,
|
||||
only: [:name, :description,:is_public, :identifier,
|
||||
:rep_identifier, :project_category_id, :project_language_id,
|
||||
:license_id, :ignore_id, {repository: [:identifier, :hidden]}]
|
||||
|
||||
clone_project.owner = @target_owner
|
||||
clone_project.forked_from_project_id = @project.id
|
||||
clone_project.save!
|
||||
|
||||
new_repository = clone_project.repository
|
||||
new_repository.user = @target_owner
|
||||
new_repository.save!
|
||||
|
||||
result = Gitea::Repository::ForkService.new(@project.owner, @target_owner, @project.identifier, @organization).call
|
||||
|
||||
@project.update_column('forked_count', @project.forked_count + 1)
|
||||
new_repository.update_column('url', result['clone_url']) if result
|
||||
|
||||
clone_project
|
||||
end
|
||||
rescue => e
|
||||
puts "clone project service error: #{e.message}"
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
end
|
||||
35
app/services/projects/join_service.rb
Normal file
35
app/services/projects/join_service.rb
Normal file
@@ -0,0 +1,35 @@
|
||||
class Projects::JoinService < ApplicationService
|
||||
attr_reader :project, :user, :opts
|
||||
|
||||
def initialize(project, user, **opts)
|
||||
@project = project
|
||||
@user = user
|
||||
@opts = opts
|
||||
end
|
||||
|
||||
def call
|
||||
ActiveRecord::Base.transaction do
|
||||
member = project.members.create!(user: user)
|
||||
|
||||
member.member_roles.create!(role_id: role_value)
|
||||
|
||||
project.user_grades.find_or_create_by!(user: user)
|
||||
end
|
||||
|
||||
ApplyJoinProjectNotifyJob.perform_later(user, project, role_value)
|
||||
|
||||
project
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def role_value
|
||||
@_role ||=
|
||||
case opts[:role]
|
||||
when 'manager' then 3
|
||||
when 'developer' then 4
|
||||
when 'reporter' then 5
|
||||
else raise ArgumentError
|
||||
end
|
||||
end
|
||||
end
|
||||
55
app/services/projects/migrate_service.rb
Normal file
55
app/services/projects/migrate_service.rb
Normal file
@@ -0,0 +1,55 @@
|
||||
class Projects::MigrateService < ApplicationService
|
||||
attr_reader :user, :params
|
||||
|
||||
def initialize(user, params)
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
@project = Project.new(project_params)
|
||||
ActiveRecord::Base.transaction do
|
||||
if @project.save!
|
||||
Repositories::MigrateService.new(user, @project, repository_params).call
|
||||
else
|
||||
#
|
||||
end
|
||||
end
|
||||
@project
|
||||
rescue => e
|
||||
puts "create mirror project service error: #{e.message}"
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def project_params
|
||||
{
|
||||
name: params[:name],
|
||||
user_id: params[:user_id],
|
||||
description: params[:description],
|
||||
project_category_id: params[:project_category_id],
|
||||
project_language_id: params[:project_language_id],
|
||||
is_public: project_secretion[:public],
|
||||
project_type: Project.project_types[:mirror]
|
||||
}
|
||||
end
|
||||
|
||||
def repository_params
|
||||
{
|
||||
hidden: project_secretion[:hidden],
|
||||
identifier: params[:repository_name],
|
||||
mirror_url: params[:clone_addr],
|
||||
user_id: user.id,
|
||||
login: user.login
|
||||
}
|
||||
end
|
||||
|
||||
def project_secretion
|
||||
# 默认公开
|
||||
public, hidden = true, false
|
||||
public, hidden = false, true if ActiveModel::Type::Boolean.new.cast(params[:private]) == true
|
||||
|
||||
{ public: public, hidden: hidden }
|
||||
end
|
||||
end
|
||||
69
app/services/repositories/create_service.rb
Normal file
69
app/services/repositories/create_service.rb
Normal file
@@ -0,0 +1,69 @@
|
||||
class Repositories::CreateService < ApplicationService
|
||||
attr_reader :user, :project, :params
|
||||
|
||||
def initialize(user, project, params)
|
||||
@project = project
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
@repository = Repository.new(repository_params)
|
||||
ActiveRecord::Base.transaction do
|
||||
if @repository.save!
|
||||
gitea_repository = Gitea::Repository::CreateService.new(user.gitea_token, gitea_repository_params).call
|
||||
sync_project(@repository, gitea_repository)
|
||||
sync_repository(@repository, gitea_repository)
|
||||
end
|
||||
@repository
|
||||
end
|
||||
rescue => e
|
||||
puts "create repository service error: #{e.message}"
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def sync_project(repository, gitea_repository)
|
||||
if gitea_repository
|
||||
project.update_columns(
|
||||
gpid: gitea_repository["id"],
|
||||
identifier: repository.identifier,
|
||||
forked_count: gitea_repository["forks_count"])
|
||||
end
|
||||
end
|
||||
|
||||
def sync_repository(repository, gitea_repository)
|
||||
repository.update_columns(url: remote_repository_url,) if gitea_repository
|
||||
end
|
||||
|
||||
def remote_repository_url
|
||||
[Gitea.gitea_config[:domain], '/', user.login, '/', params[:identifier], ".git"].join("")
|
||||
end
|
||||
|
||||
def repository_params
|
||||
params.merge(project_id: project.id)
|
||||
end
|
||||
|
||||
def gitea_repository_params
|
||||
hash = {
|
||||
name: params[:identifier],
|
||||
private: !params[:hidden]
|
||||
# "auto_init": true,
|
||||
# "description": "string",
|
||||
# "gitignores": "string",
|
||||
# "issue_labels": "string",
|
||||
# "license": "string",
|
||||
# "name": "string",
|
||||
# "private": true,
|
||||
# "readme": "string"
|
||||
}
|
||||
|
||||
ignore = project.ignore
|
||||
license = project.license
|
||||
hash = hash.merge(license: license.name) if license
|
||||
hash = hash.merge(gitignores: ignore.name) if ignore
|
||||
hash = hash.merge(auto_init: true) if ignore || license
|
||||
hash
|
||||
end
|
||||
end
|
||||
47
app/services/repositories/migrate_service.rb
Normal file
47
app/services/repositories/migrate_service.rb
Normal file
@@ -0,0 +1,47 @@
|
||||
class Repositories::MigrateService < ApplicationService
|
||||
attr_reader :user, :project, :params
|
||||
|
||||
def initialize(user, project, params)
|
||||
@project = project
|
||||
@user = user
|
||||
@params = params
|
||||
end
|
||||
|
||||
def call
|
||||
@repository = Repository.new(repository_params)
|
||||
ActiveRecord::Base.transaction do
|
||||
if @repository.save!
|
||||
gitea_repository = Gitea::Repository::MigrateService.new(user.gitea_token, gitea_repository_params).call
|
||||
sync_project(gitea_repository)
|
||||
sync_repository(@repository, gitea_repository)
|
||||
end
|
||||
@repository
|
||||
end
|
||||
rescue => e
|
||||
puts "create mirror repository service error: #{e.message}"
|
||||
raise Error, e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def sync_project(gitea_repository)
|
||||
project.update_columns(gpid: gitea_repository["id"], identifier: gitea_repository["name"]) if gitea_repository
|
||||
end
|
||||
|
||||
def sync_repository(repository, gitea_repository)
|
||||
repository.update_columns(url: gitea_repository["clone_url"]) if gitea_repository
|
||||
end
|
||||
|
||||
def repository_params
|
||||
params.merge(project_id: project.id)
|
||||
end
|
||||
|
||||
def gitea_repository_params
|
||||
{
|
||||
clone_addr: params[:mirror_url],
|
||||
repo_name: params[:identifier],
|
||||
uid: user.gitea_uid,
|
||||
private: params[:hidden]
|
||||
}
|
||||
end
|
||||
end
|
||||
231
app/services/review_service.rb
Normal file
231
app/services/review_service.rb
Normal file
@@ -0,0 +1,231 @@
|
||||
#coding=utf-8
|
||||
#
|
||||
require 'net/http'
|
||||
require 'uri'
|
||||
|
||||
class ReviewService
|
||||
@review_server_url = EduSetting.get('review_server_url')
|
||||
|
||||
|
||||
def self.logger
|
||||
@logger ||= Logger.new(File.join(Rails.root, "log", "review.log"), 'daily')
|
||||
end
|
||||
|
||||
def self.root_url
|
||||
@review_server_url.presence || 'http://10.9.79.221:80'
|
||||
end
|
||||
|
||||
def self.postForm(action, map)
|
||||
Rails.logger.info("##################------action: #{action}")
|
||||
Rails.logger.info("##################------action: #{map}")
|
||||
begin
|
||||
uri = URI.parse("#{root_url}/api/v1/#{action}")
|
||||
|
||||
Rails.logger.info "请求url: #{uri}"
|
||||
Rails.logger.info "参数: "
|
||||
map.each do |k, v|
|
||||
Rails.logger.info "#{k}=>#{v}"
|
||||
end
|
||||
|
||||
res = Net::HTTP.post_form uri, map
|
||||
body = res.body
|
||||
Rails.logger.info("返回: #{body}")
|
||||
content = JSON.parse(body)
|
||||
content
|
||||
rescue => e
|
||||
Rails.logger.error("post #{action}: exception #{e.message}")
|
||||
end
|
||||
end
|
||||
|
||||
def self.postJson(action, params)
|
||||
begin
|
||||
uri = URI.parse("#{root_url}/api/v1/#{action}")
|
||||
https = Net::HTTP.new(uri.host, uri.port)
|
||||
https.use_ssl = root_url.start_with?('https')
|
||||
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8'})
|
||||
req.body = params.to_json
|
||||
res = https.request(req)
|
||||
body = res.body
|
||||
logger.info("--uri_exec: .....res is #{body}")
|
||||
content = JSON.parse(body)
|
||||
raise content["msg"] if content["code"] != 0
|
||||
|
||||
content["data"]
|
||||
rescue Exception => e
|
||||
logger.error("--uri_exec: exception #{e.message}")
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
class CheckResponse
|
||||
attr_accessor :status, :msg, :query_id
|
||||
|
||||
def initialize(status, msg, query_id)
|
||||
@status = status
|
||||
@msg = msg
|
||||
@query_id = query_id
|
||||
end
|
||||
end
|
||||
|
||||
#查重
|
||||
# 参数说明
|
||||
# user_list [
|
||||
# {
|
||||
# user_id: 1,
|
||||
# code_info: [
|
||||
# {
|
||||
# "path": "src/step1/HelloWorld.java",
|
||||
# "content: "ADAGWDSSAS22",
|
||||
# "passed_time": "2016-01-08 00:00:00"
|
||||
# },
|
||||
# ]
|
||||
# },
|
||||
# ]
|
||||
#
|
||||
# 返回说明
|
||||
#
|
||||
# {
|
||||
# code: 0, 0 成功,其他失败
|
||||
# msg: '', //失败时的错误消息
|
||||
# query_id: '123123123', //本次查重的查询号
|
||||
# }
|
||||
#
|
||||
#
|
||||
def self.check(user_list = [], language='java')
|
||||
File.open("/tmp/check_codes_#{Time.now}.json", 'w+') do |f|
|
||||
f.write(user_list.to_json)
|
||||
end
|
||||
|
||||
data = postForm('check_codes', {user_data: user_list.to_json, language: language})
|
||||
if data.nil?
|
||||
return CheckResponse.new(-1, "系统调用出错", "")
|
||||
end
|
||||
Rails.logger.info("@@@@@@@@@@@@@@@@------------#{data}")
|
||||
CheckResponse.new(data["status"], data["msg"], data["query_id"])
|
||||
end
|
||||
|
||||
|
||||
class QueryResultResponse
|
||||
UserList = Struct.new(:user_id, :target_user_id, :origin_path, :target_path, :rate)
|
||||
attr_accessor :status, :msg, :user_lists
|
||||
|
||||
def initialize(status, msg, user_lists)
|
||||
@status, @msg, @user_lists = status, msg, []
|
||||
|
||||
if user_lists.present?
|
||||
user_lists.each do |info|
|
||||
user = find_by_user_id_and_origin_path(info["user_id"], info["path"]["origin"])
|
||||
if !user.present?
|
||||
add_user_list(info)
|
||||
elsif user.rate < info["rate"]
|
||||
set_user_list(user, info)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def set_user_list(user, obj)
|
||||
user.user_id = obj["user_id"]
|
||||
user.target_user_id = obj["target_user_id"]
|
||||
user.origin_path = obj["path"]["origin"]
|
||||
user.target_path = obj["path"]["target"]
|
||||
user.rate = obj["rate"]
|
||||
end
|
||||
|
||||
def add_user_list(obj)
|
||||
user_list = UserList.new
|
||||
set_user_list(user_list, obj)
|
||||
@user_lists << user_list
|
||||
end
|
||||
|
||||
def find_by_user_id_and_origin_path(user_id, origin_path)
|
||||
self.user_lists.each do |user|
|
||||
return user if user.user_id == user_id and user.origin_path == origin_path
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
|
||||
class QueryDetailResultResponse
|
||||
CodeInfo = Struct.new(:origin_path, :target_path, :origin_content, :target_content, :target_user_id, :rate)
|
||||
|
||||
|
||||
attr_accessor :status, :msg, :code_info
|
||||
|
||||
def initialize(status, msg, code_info)
|
||||
@status, @msg, @code_info = status, msg, []
|
||||
|
||||
if code_info.present?
|
||||
code_info.each do |code|
|
||||
info = find_by_path(code["path"]["origin"])
|
||||
if !info.present?
|
||||
add_code_info(code)
|
||||
elsif info.rate < code["rate"]
|
||||
set_code_info(info, code)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def set_code_info(info, obj)
|
||||
info.origin_path = obj["path"]["origin"]
|
||||
info.target_path = obj["path"]["target"]
|
||||
info.origin_content = obj["content"]["origin"]
|
||||
info.target_content = obj["content"]["target"]
|
||||
info.target_user_id = obj["target_user_id"]
|
||||
info.rate = obj["rate"]
|
||||
end
|
||||
|
||||
def add_code_info(obj)
|
||||
info = CodeInfo.new
|
||||
set_code_info(info, obj)
|
||||
@code_info << info
|
||||
end
|
||||
|
||||
def find_by_path(path)
|
||||
self.code_info.each do |code_info|
|
||||
return code_info if code_info.origin_path == path
|
||||
end
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
#查询查重的结果
|
||||
#
|
||||
# 输入参数
|
||||
# query_id 待查询的ID
|
||||
# user_id 传入则查详情
|
||||
#
|
||||
# 文档参考 https://www.showdoc.cc/127895880302646?page_id=1271144663669096
|
||||
#
|
||||
def self.query_result(opt = {})
|
||||
unless opt[:query_id].present?
|
||||
logger.error "query_id没有传"
|
||||
return
|
||||
end
|
||||
|
||||
if opt[:user_id].present?
|
||||
data = postForm('check_info', query_id: opt[:query_id], user_id: opt[:user_id])
|
||||
if data.nil?
|
||||
return QueryDetailResultResponse.new(-1, "系统调用出错", [])
|
||||
end
|
||||
|
||||
response = QueryDetailResultResponse.new(data['status'], data['msg'], data["code_info"])
|
||||
return response
|
||||
|
||||
else
|
||||
data = postForm('check_lists', query_id: opt[:query_id])
|
||||
if data.nil?
|
||||
return CheckResponse.new(-1, "系统调用出错", "")
|
||||
end
|
||||
|
||||
response = QueryResultResponse.new(data['status'], data['msg'], data["user_lists"])
|
||||
return response
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
24
app/services/reward_experience_service.rb
Normal file
24
app/services/reward_experience_service.rb
Normal file
@@ -0,0 +1,24 @@
|
||||
class RewardExperienceService
|
||||
attr_reader :user, :attrs
|
||||
|
||||
def initialize(user, **attrs)
|
||||
@user = user
|
||||
@attrs = attrs.slice(*%i[container_id container_type score])
|
||||
end
|
||||
|
||||
def call
|
||||
return if user.experiences.exists?(attrs.except(:score))
|
||||
|
||||
ActiveRecord::Base.transaction do
|
||||
experience = user.experiences.create!(attrs)
|
||||
|
||||
user.increment!(:experience, experience.score)
|
||||
|
||||
experience
|
||||
end
|
||||
end
|
||||
|
||||
def self.call(user, **attrs)
|
||||
new(user, attrs).call
|
||||
end
|
||||
end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user