60147f8e20fa4dec9cba2bac5b9392209cd298bf
[kivitendo-erp.git] / SL / BackgroundJob / CsvImport.pm
1 package SL::BackgroundJob::CsvImport;
2
3 use strict;
4
5 use parent qw(SL::BackgroundJob::Base);
6
7 use YAML ();
8 use SL::Controller::CsvImport;
9 use SL::DB::CsvImportProfile;
10 use SL::SessionFile::Random;
11
12 sub create_job {
13   my ($self_or_class, %params) = @_;
14
15   my $package       = ref($self_or_class) || $self_or_class;
16   $package          =~ s/SL::BackgroundJob:://;
17
18   my $profile = delete $params{profile} || SL::DB::CsvImportProfile->new;
19   my $new_profile = $profile->clone_and_reset_deep;
20   $new_profile->save;
21
22   my %data = (
23     %params,
24     profile_id => $new_profile->id,
25     session_id => $::auth->get_session_id,
26   );
27
28   my $job = SL::DB::BackgroundJob->new(
29     type         => 'once',
30     active       => 1,
31     package_name => $package,
32     data         => YAML::Dump(\%data),
33   );
34
35   return $job;
36 }
37
38 sub profile {
39   my ($self) = @_;
40
41   if (!$self->{profile}) {
42     my $data = YAML::Load($self->{db_obj}->data);
43     $self->{profile} = SL::DB::Manager::CsvImportProfile->find_by(id => $data->{profile_id});
44   }
45
46   return $self->{profile};
47 }
48
49 sub run {
50   my $self        = shift;
51   $self->{db_obj} = shift;
52
53   $self->do_import;
54
55   $self->cleanup;
56 }
57
58 sub do_import {
59   my ($self) = @_;
60
61   my $c = SL::Controller::CsvImport->new;
62
63   $c->profile($self->profile);
64   $c->type($self->{db_obj}->data_as_hash->{type});
65   $c->add_progress_tracker($self);
66
67   $c->test_and_import(test => 1, session_id => $self->{db_obj}->data_as_hash->{session_id});
68
69   my $report_id = $c->save_report;
70   $self->{db_obj}->set_data(report_id => $report_id);
71   $self->{db_obj}->save;
72
73   $c->track_progress(100);
74 }
75
76 sub track_progress {
77   my ($self, $progress) = @_;
78
79   $self->{db_obj}->set_data(progress => $progress);
80   $self->{db_obj}->save;
81 }
82
83 sub cleanup {
84
85 }
86
87 1;
88
89 __END__
90
91 =encoding utf-8
92
93 =head1 NAME
94
95 SL::Background::CsvImport - backend for automatic imports of csv data
96
97 =head1 SYNOPSIS
98
99
100 use SL::BackgroundJob::CsvImport;
101
102
103 From a controller or external source:
104
105   my $job = SL::BackgroundJob::CsvImport->create_job(
106     file => $file,
107     %import_options
108   );
109
110 =head1 DESCRIPTION
111
112 =head1 FUNCTIONS
113
114 =head1 BUGS
115
116 =head1 AUTHOR
117
118 Sven Schoeling E<lt>s.schoeling@linet-services.deE<gt>
119
120 =cut