dawarich/app/jobs/users/import_data_job.rb

69 lines
1.8 KiB
Ruby
Raw Normal View History

2025-06-28 06:22:56 -04:00
# frozen_string_literal: true
class Users::ImportDataJob < ApplicationJob
queue_as :imports
sidekiq_options retry: false
def perform(import_id)
import = Import.find(import_id)
user = import.user
archive_path = download_import_archive(import)
unless File.exist?(archive_path)
raise StandardError, "Archive file not found: #{archive_path}"
end
import_stats = Users::ImportData.new(user, archive_path).import
User.reset_counters(user.id, :points)
2025-06-28 06:22:56 -04:00
Rails.logger.info "Import completed successfully for user #{user.email}: #{import_stats}"
2025-06-30 17:49:07 -04:00
rescue ActiveRecord::RecordNotFound => e
ExceptionReporter.call(e, "Import job failed for import_id #{import_id} - import not found")
raise e
2025-06-28 06:22:56 -04:00
rescue StandardError => e
2025-06-30 16:29:28 -04:00
user_id = user&.id || import&.user_id || 'unknown'
2025-06-28 06:22:56 -04:00
ExceptionReporter.call(e, "Import job failed for user #{user_id}")
2025-06-30 16:29:28 -04:00
create_import_failed_notification(user, e)
2025-06-28 06:22:56 -04:00
raise e
ensure
if archive_path && File.exist?(archive_path)
File.delete(archive_path)
2025-06-30 16:29:28 -04:00
2025-06-28 06:22:56 -04:00
Rails.logger.info "Cleaned up archive file: #{archive_path}"
end
end
private
def download_import_archive(import)
require 'tmpdir'
timestamp = Time.current.to_i
filename = "user_import_#{import.user_id}_#{import.id}_#{timestamp}.zip"
temp_path = File.join(Dir.tmpdir, filename)
File.open(temp_path, 'wb') do |file_handle|
import.file.download do |chunk|
file_handle.write(chunk)
end
end
temp_path
end
2025-06-30 16:29:28 -04:00
def create_import_failed_notification(user, error)
::Notifications::Create.new(
user: user,
title: 'Data import failed',
content: "Your data import failed with error: #{error.message}. Please check the archive format and try again.",
kind: :error
).call
end
2025-06-28 06:22:56 -04:00
end