You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
educoder/app/services/admins/import_user_service.rb

85 lines
2.4 KiB

class Admins::ImportUserService < ApplicationService
Error = Class.new(StandardError)
attr_reader :file, :result
attr_accessor :school, :department
def initialize(file)
@file = file
@result = { success: 0, fail: [] }
end
def call
raise Error, '文件不存在' if file.blank?
excel = Admins::ImportUserExcel.new(file)
excel.read_each(&method(:save_user))
result
rescue ApplicationImport::Error => ex
raise Error, ex.message
end
private
def save_user(data)
ActiveRecord::Base.transaction do
if school.blank? || school.name != data.school
@school = School.find_or_create_by!(name: data.school)
end
if department.blank? || department.school_id != school.id || department.name != data.department
@department = school.departments.find_or_initialize_by(name: data.department)
@department.is_auth = true
@department.save!
end
user =
if data.phone && data.mail
User.find_by(phone: data.phone, mail: data.mail)
elsif data.phone && data.mail.blank?
User.find_by(phone: data.phone)
elsif data.phone.blank? && data.mail
User.find_by(mail: data.mail)
elsif
User.joins(:user_extension).where(user_extensions: { student_id: data.student_id }).first
end
user ||= User.new
attrs = {
type: 'User',
status: User::STATUS_ACTIVE,
5 years ago
login: user.login.presence || data.student_id || User.generate_login("local"),
firstname: '',
lastname: data.name,
nickname: data.name,
password: '12345678',
professional_certification: 1,
certification: 1,
phone: data.phone,
mail: data.mail,
profile_completed: true,
}
user.assign_attributes(attrs)
user.save!
identity = data.identity.present? ? data.identity.to_i : 2
extension_attrs = {
school_id: school.id, location: school.province, location_city: school.city,
gender: 0, identity: identity, department_id: department.id, student_id: data.student_id.presence
}
extension = user.user_extension || user.build_user_extension
extension.assign_attributes(extension_attrs)
extension.save!
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