View | Details | Raw Unified | Return to bug 27421
Collapse All | Expand All

(-)a/C4/ImportBatch.pm (+15 lines)
Lines 390-395 sub BatchStageMarcRecords { Link Here
390
    }
390
    }
391
    # FIXME branch_code, number of bibs, number of items
391
    # FIXME branch_code, number of bibs, number of items
392
    _update_batch_record_counts($batch_id);
392
    _update_batch_record_counts($batch_id);
393
    if ($progress_interval){
394
        &$progress_callback($rec_num);
395
    }
396
393
    return ($batch_id, $num_valid, $num_items, @invalid_records);
397
    return ($batch_id, $num_valid, $num_items, @invalid_records);
394
}
398
}
395
399
Lines 495-500 sub BatchFindDuplicates { Link Here
495
            SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'no_match');
499
            SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'no_match');
496
        }
500
        }
497
    }
501
    }
502
503
    if ($progress_interval){
504
        &$progress_callback($rec_num);
505
    }
506
498
    $sth->finish();
507
    $sth->finish();
499
    return $num_with_matches;
508
    return $num_with_matches;
500
}
509
}
Lines 687-693 sub BatchCommitRecords { Link Here
687
            SetImportRecordStatus($rowref->{'import_record_id'}, 'ignored');
696
            SetImportRecordStatus($rowref->{'import_record_id'}, 'ignored');
688
        }
697
        }
689
    }
698
    }
699
700
    if ($progress_interval){
701
        &$progress_callback($rec_num);
702
    }
703
690
    $schema->txn_commit; # Commit final records that may not have hit callback threshold
704
    $schema->txn_commit; # Commit final records that may not have hit callback threshold
705
691
    $sth->finish();
706
    $sth->finish();
692
707
693
    if ( @biblio_ids ) {
708
    if ( @biblio_ids ) {
(-)a/Koha/BackgroundJob.pm (+1 lines)
Lines 406-411 sub core_types_to_classes { Link Here
406
        batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
406
        batch_hold_cancel                   => 'Koha::BackgroundJob::BatchCancelHold',
407
        update_elastic_index                => 'Koha::BackgroundJob::UpdateElasticIndex',
407
        update_elastic_index                => 'Koha::BackgroundJob::UpdateElasticIndex',
408
        update_holds_queue_for_biblios      => 'Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue',
408
        update_holds_queue_for_biblios      => 'Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue',
409
        stage_marc_for_import               => 'Koha::BackgroundJob::StageMARCForImport',
409
    };
410
    };
410
}
411
}
411
412
(-)a/Koha/BackgroundJob/StageMARCForImport.pm (+198 lines)
Line 0 Link Here
1
package Koha::BackgroundJob::StageMARCForImport;
2
3
# This file is part of Koha.
4
#
5
# Koha is free software; you can redistribute it and/or modify it
6
# under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 3 of the License, or
8
# (at your option) any later version.
9
#
10
# Koha is distributed in the hope that it will be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
use Modern::Perl;
19
use Try::Tiny;
20
21
use base 'Koha::BackgroundJob';
22
23
use C4::Matcher;
24
use C4::ImportBatch qw(
25
    RecordsFromMARCXMLFile
26
    RecordsFromISO2709File
27
    RecordsFromMarcPlugin
28
    BatchStageMarcRecords
29
    BatchFindDuplicates
30
    SetImportBatchMatcher
31
    SetImportBatchOverlayAction
32
    SetImportBatchNoMatchAction
33
    SetImportBatchItemAction
34
);
35
36
=head1 NAME
37
38
Koha::BackgroundJob::StageMARCForImport - Stage MARC records for import
39
40
This is a subclass of Koha::BackgroundJob.
41
42
=head1 API
43
44
=head2 Class methods
45
46
=head3 job_type
47
48
Define the job type of this job: stage_marc_for_import
49
50
=cut
51
52
sub job_type {
53
    return 'stage_marc_for_import';
54
}
55
56
=head3 process
57
58
Stage the MARC records for import.
59
60
=cut
61
62
sub process {
63
    my ( $self, $args ) = @_;
64
65
    $self->start;
66
67
    my $record_type                = $args->{record_type};
68
    my $encoding                   = $args->{encoding};
69
    my $format                     = $args->{format};
70
    my $filepath                   = $args->{filepath};
71
    my $filename                   = $args->{filename};
72
    my $marc_modification_template = $args->{marc_modification_template};
73
    my $comments                   = $args->{comments};
74
    my $parse_items                = $args->{parse_items};
75
    my $matcher_id                 = $args->{matcher_id};
76
    my $overlay_action             = $args->{overlay_action};
77
    my $nomatch_action             = $args->{nomatch_action};
78
    my $item_action                = $args->{item_action};
79
    my $vendor_id                  = $args->{vendor_id};
80
    my $basket_id                  = $args->{basket_id};
81
    my $profile_id                 = $args->{profile_id};
82
83
    my @messages;
84
    my ( $batch_id, $num_valid, $num_items, @import_errors );
85
    my $num_with_matches = 0;
86
    my $checked_matches  = 0;
87
    my $matcher_failed   = 0;
88
    my $matcher_code     = "";
89
90
    try {
91
        my $schema = Koha::Database->new->schema;
92
        $schema->storage->txn_begin;
93
94
        my ( $errors, $marcrecords );
95
        if ( $format eq 'MARCXML' ) {
96
            ( $errors, $marcrecords ) =
97
              C4::ImportBatch::RecordsFromMARCXMLFile( $filepath, $encoding );
98
        }
99
        elsif ( $format eq 'ISO2709' ) {
100
            ( $errors, $marcrecords ) =
101
              C4::ImportBatch::RecordsFromISO2709File( $filepath, $record_type,
102
                $encoding );
103
        }
104
        else {    # plugin based
105
            $errors = [];
106
            $marcrecords =
107
              C4::ImportBatch::RecordsFromMarcPlugin( $filepath, $format,
108
                $encoding );
109
        }
110
111
        $self->size(scalar @$marcrecords)->store;
112
113
        ( $batch_id, $num_valid, $num_items, @import_errors ) =
114
          BatchStageMarcRecords(
115
            $record_type,                $encoding,
116
            $marcrecords,                $filename,
117
            $marc_modification_template, $comments,
118
            '',                          $parse_items,
119
            0,                           50,
120
            sub {
121
                my $job_progress = shift;
122
                if ($matcher_id) {
123
                    $job_progress /= 2;
124
                }
125
                $self->progress( int($job_progress) )->store;
126
              }
127
          );
128
129
        if ($profile_id) {
130
            my $ibatch = Koha::ImportBatches->find($batch_id);
131
            $ibatch->set( { profile_id => $profile_id } )->store;
132
        }
133
134
        if ($matcher_id) {
135
            my $matcher = C4::Matcher->fetch($matcher_id);
136
            if ( defined $matcher ) {
137
                $checked_matches = 1;
138
                $matcher_code    = $matcher->code();
139
                $num_with_matches =
140
                  BatchFindDuplicates( $batch_id, $matcher, 10, 50,
141
                    sub { my $job_progress = shift; $self->progress( $self->progress + $job_progress )->store } );
142
                SetImportBatchMatcher( $batch_id, $matcher_id );
143
                SetImportBatchOverlayAction( $batch_id, $overlay_action );
144
                SetImportBatchNoMatchAction( $batch_id, $nomatch_action );
145
                SetImportBatchItemAction( $batch_id, $item_action );
146
                $schema->storage->txn_commit;
147
            }
148
            else {
149
                $matcher_failed = 1;
150
                $schema->storage->txn_rollback;
151
            }
152
        } else {
153
            $schema->storage->txn_commit;
154
        }
155
    }
156
    catch {
157
        warn $_;
158
        die "Something terrible has happened!"
159
          if ( $_ =~ /Rollback failed/ );    # Rollback failed
160
    };
161
162
    my $report = {
163
        staged          => $num_valid,
164
        matched         => $num_with_matches,
165
        num_items       => $num_items,
166
        import_errors   => scalar(@import_errors),
167
        total           => $num_valid + scalar(@import_errors),
168
        checked_matches => $checked_matches,
169
        matcher_failed  => $matcher_failed,
170
        matcher_code    => $matcher_code,
171
        import_batch_id => $batch_id,
172
        vendor_id       => $vendor_id,
173
        basket_id       => $basket_id,
174
    };
175
176
    my $data = $self->decoded_data;
177
    $data->{messages} = \@messages;
178
    $data->{report}   = $report;
179
180
    $self->finish($data);
181
}
182
183
=head3 enqueue
184
185
Enqueue the new job
186
187
=cut
188
189
sub enqueue {
190
    my ( $self, $args) = @_;
191
192
    $self->SUPER::enqueue({
193
        job_size => 0, # unknown for now
194
        job_args => $args
195
    });
196
}
197
198
1;
(-)a/debian/templates/apache-shared-intranet-plack.conf (-1 lines)
Lines 15-21 Link Here
15
        ProxyPass "/cgi-bin/koha/tools/background-job-progress.pl" "!"
15
        ProxyPass "/cgi-bin/koha/tools/background-job-progress.pl" "!"
16
        ProxyPass "/cgi-bin/koha/tools/export.pl" "!"
16
        ProxyPass "/cgi-bin/koha/tools/export.pl" "!"
17
        ProxyPass "/cgi-bin/koha/tools/manage-marc-import.pl" "!"
17
        ProxyPass "/cgi-bin/koha/tools/manage-marc-import.pl" "!"
18
        ProxyPass "/cgi-bin/koha/tools/stage-marc-import.pl" "!"
19
        ProxyPass "/cgi-bin/koha/tools/upload-cover-image.pl" "!"
18
        ProxyPass "/cgi-bin/koha/tools/upload-cover-image.pl" "!"
20
        ProxyPass "/cgi-bin/koha/svc/cataloguing/metasearch" "!"
19
        ProxyPass "/cgi-bin/koha/svc/cataloguing/metasearch" "!"
21
20
(-)a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/stage_marc_for_import.inc (+46 lines)
Line 0 Link Here
1
[% USE Koha %]
2
3
[% BLOCK report %]
4
    [% SET report = job.report %]
5
    [% IF report %]
6
        <h2>MARC staging results</h2>
7
        [% SWITCH (record_type) %]
8
        [% CASE 'biblio' %]
9
            <h3>Processing bibliographic records</h3>
10
        [% CASE 'auth' %]
11
            <h3>Processing authority records</h3>
12
        [% END %]
13
        <ul>
14
            <li>[% report.total | html %]  records in file</li>
15
            <li>[% report.import_errors | html %] records not staged because of MARC error</li>
16
            <li>[% report.staged | html %] records staged</li>
17
            [% IF ( report.checked_matches ) %]
18
            <li>[% report.matched | html %] records with at least one match in catalog per matching rule
19
                &quot;[% report.matcher_code | html %]&quot;</li>
20
            [% ELSE %]
21
                [% IF ( report.matcher_failed ) %]
22
                    <li>Record matching failed -- unable to retrieve selected matching rule.</li>
23
                [% ELSE %]
24
                    <li>Did not check for matches with existing records in catalog</li>
25
                [% END %]
26
            [% END %]
27
            [% IF report.record_type == 'biblio' %]
28
                <li>[% report.num_items | html %] item records found and staged</li>
29
            [% END %]
30
            [% IF ( report.label_batch ) %]
31
                <li>New label batch created: # [% report.label_batch | html %] </li>
32
            [% END %]
33
        </ul>
34
        [% IF report.basketno && report.booksellerid %]
35
        <p>
36
            <a id="addtobasket" class="btn btn-default" href="/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=[% report.import_batch_id | html %]&basketno=[% report.basketno | html %]&booksellerid=[% report.booksellerid | html %]">Add staged files to basket</a>
37
        </p>
38
        [% END %]
39
    [% END %]
40
[% END %]
41
42
[% BLOCK detail %]
43
[% END %]
44
45
[% BLOCK js %]
46
[% END %]
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/background_jobs.tt (+2 lines)
Lines 41-46 Link Here
41
        <span>Update Elasticsearch index</span>
41
        <span>Update Elasticsearch index</span>
42
    [% CASE 'update_holds_queue_for_biblios' %]
42
    [% CASE 'update_holds_queue_for_biblios' %]
43
        <span>Holds queue update</span>
43
        <span>Holds queue update</span>
44
    [% CASE 'stage_marc_for_import' %]
45
        <span>Staged MARC records for import</span>
44
    [% CASE %]<span>Unknown job type '[% job_type | html %]'</span>
46
    [% CASE %]<span>Unknown job type '[% job_type | html %]'</span>
45
    [% END %]
47
    [% END %]
46
48
(-)a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stage-marc-import.tt (-57 / +40 lines)
Lines 48-101 Link Here
48
        <div class="col-sm-10 col-sm-push-2">
48
        <div class="col-sm-10 col-sm-push-2">
49
            <main>
49
            <main>
50
50
51
[% IF ( uploadmarc ) %]
51
        [% FOREACH message IN messages %]
52
<div id="toolbar" class="btn-toolbar">
52
          [% IF message.type == 'success' %]
53
        <a class="btn btn-default" href="/cgi-bin/koha/tools/stage-marc-import.pl"><i class="fa fa-plus"></i> Stage MARC records</a>
53
            <div class="dialog message">
54
        <a class="btn btn-default" href="/cgi-bin/koha/tools/manage-marc-import.pl?import_batch_id=[% import_batch_id | html %]"><i class="fa fa-list-ul"></i> Manage staged records</a>
54
          [% ELSIF message.type == 'warning' %]
55
</div>
55
            <div class="dialog alert">
56
[% END %]
56
          [% ELSIF message.type == 'error' %]
57
            <div class="dialog alert" style="margin:auto;">
58
          [% END %]
59
          [% IF message.code == 'cannot_enqueue_job' %]
60
              <span>Cannot enqueue this job.</span>
61
          [% END %]
62
          [% IF message.error %]
63
            <span>(The error was: [% message.error | html %], see the Koha log file for more information).</span>
64
          [% END %]
65
          </div>
66
        [% END %]
57
67
58
[% IF ( uploadmarc ) %]
68
        [% IF job_enqueued %]
59
<h1>MARC staging results</h1>
69
            <div id="toolbar" class="btn-toolbar">
60
<ul>
70
                    <a class="btn btn-default" href="/cgi-bin/koha/tools/stage-marc-import.pl"><i class="fa fa-plus"></i> Stage MARC records</a>
61
    [% SWITCH (record_type) %]
71
                    <a class="btn btn-default" href="/cgi-bin/koha/tools/manage-marc-import.pl?import_batch_id=[% import_batch_id | html %]"><i class="fa fa-list-ul"></i> Manage staged records</a>
62
    [% CASE 'biblio' %]
72
            </div>
63
        <li>Processing bibliographic records</li>
73
64
    [% CASE 'auth' %]
74
            <h1>MARC staging</h1>
65
        <li>Processing authority records</li>
75
            <div class="dialog message">
66
    [% END %]
76
              <p>The job has been enqueued! It will be processed as soon as possible.</p>
67
	<li>[% total | html %]  records in file</li>
77
              <p><a href="/cgi-bin/koha/admin/background_jobs.pl?op=view&id=[% job_id | uri %]" title="View detail of the enqueued job">View detail of the enqueued job</a>
68
	<li>[% import_errors | html %] records not staged because of MARC error</li>
78
            </div>
69
	<li>[% staged | html %] records staged</li>
70
    [% IF ( checked_matches ) %]
71
	<li>[% matched | html %] records with at least one match in catalog per matching rule 
72
        &quot;[% matcher_code | html %]&quot;</li>
73
    [% ELSE %]
74
        [% IF ( matcher_failed ) %]
75
          <li>Record matching failed -- unable to retrieve selected matching rule.</li>
76
        [% ELSE %]
79
        [% ELSE %]
77
          <li>Did not check for matches with existing records in catalog</li>
78
        [% END %]
79
    [% END %]
80
    [% IF record_type == 'biblio' %]
81
        <li>[% num_items | html %] item records found and staged</li>
82
    [% END %]
83
	[% IF ( label_batch ) %]
84
	  <li>New label batch created: # [% label_batch | html %] </li>
85
    [% END %]
86
</ul>
87
[% IF basketno && booksellerid %]
88
<p>
89
    <a id="addtobasket" class="btn btn-default" href="/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=[% import_batch_id | html %]&basketno=[% basketno | html %]&booksellerid=[% booksellerid | html %]">Add staged files to basket</a>
90
</p>
91
[% END %]
92
[% ELSE %]
93
<h1>Stage MARC records for import</h1>
80
<h1>Stage MARC records for import</h1>
94
<ul>
81
<ul>
95
    <li>Select a MARC file to stage in the import reservoir.  It will be parsed, and each valid record staged for later import into the catalog.</li>
82
    <li>Select a MARC file to stage in the import reservoir.  It will be parsed, and each valid record staged for later import into the catalog.</li>
96
    <li>You can enter a name for this import. It may be useful, when creating a record, to remember where the suggested MARC data comes from!</li>
83
    <li>You can enter a name for this import. It may be useful, when creating a record, to remember where the suggested MARC data comes from!</li>
97
</ul>
84
</ul>
98
<form method="post" action="[% SCRIPT_NAME | html %]" id="uploadfile" enctype="multipart/form-data">
85
<form method="post" id="uploadfile" enctype="multipart/form-data">
99
<fieldset class="rows" id="uploadform">
86
<fieldset class="rows" id="uploadform">
100
<legend>Upload a file to stage</legend>
87
<legend>Upload a file to stage</legend>
101
<ol>
88
<ol>
Lines 136-142 Link Here
136
    </ol>
123
    </ol>
137
</fieldset>
124
</fieldset>
138
125
139
    <form method="post" id="processfile" action="[% SCRIPT_NAME | html %]" enctype="multipart/form-data">
126
    <form method="post" id="processfile" enctype="multipart/form-data">
140
[% IF basketno && booksellerid %]
127
[% IF basketno && booksellerid %]
141
    <input type="hidden" name="basketno" id="basketno" value="[% basketno | html %]" />
128
    <input type="hidden" name="basketno" id="basketno" value="[% basketno | html %]" />
142
    <input type="hidden" name="booksellerid" id="booksellerid" value="[% booksellerid | html %]" />
129
    <input type="hidden" name="booksellerid" id="booksellerid" value="[% booksellerid | html %]" />
Lines 253-262 Link Here
253
  <fieldset class="action">
240
  <fieldset class="action">
254
    <input type="button" id="mainformsubmit" value="Stage for import" />
241
    <input type="button" id="mainformsubmit" value="Stage for import" />
255
  </fieldset>
242
  </fieldset>
256
 
243
257
       <div id="jobpanel"><div id="jobstatus" class="progress_panel">Job progress: <div id="jobprogress"></div> <span id="jobprogresspercent">0</span>%</div>
258
     <div id="jobfailed"></div></div>
259
  
260
</form>
244
</form>
261
[% END %]
245
[% END %]
262
246
Lines 273-279 Link Here
273
[% MACRO jsinclude BLOCK %]
257
[% MACRO jsinclude BLOCK %]
274
    [% Asset.js("js/tools-menu.js") | $raw %]
258
    [% Asset.js("js/tools-menu.js") | $raw %]
275
    [% Asset.js("lib/jquery/plugins/humanmsg.js") | $raw %]
259
    [% Asset.js("lib/jquery/plugins/humanmsg.js") | $raw %]
276
    [% Asset.js("js/background-job-progressbar.js") | $raw %]
277
    [% Asset.js("js/file-upload.js") | $raw %]
260
    [% Asset.js("js/file-upload.js") | $raw %]
278
    <script>
261
    <script>
279
        var xhr;
262
        var xhr;
Lines 297-305 Link Here
297
                e.preventDefault();
280
                e.preventDefault();
298
                CancelUpload();
281
                CancelUpload();
299
            });
282
            });
300
            $("#mainformsubmit").on("click",function(){
283
            $("#mainformsubmit").on("click",function(e){
301
                return CheckForm( document.getElementById("processfile"));
284
                e.preventDefault();
285
                if ($("#fileToUpload").value == '') {
286
                    alert(_("Please upload a file first."));
287
                    return false;
288
                } else {
289
                    $("#processfile").submit();
290
                    return true;
291
                }
302
            });
292
            });
293
303
            getProfiles();
294
            getProfiles();
304
            $('#profile').change(function(){
295
            $('#profile').change(function(){
305
                if(this.value=='') {
296
                if(this.value=='') {
Lines 432-445 Link Here
432
            });
423
            });
433
        });
424
        });
434
425
435
        function CheckForm(f) {
436
            if ($("#fileToUpload").value == '') {
437
                alert(_("Please upload a file first."));
438
            } else {
439
                return submitBackgroundJob(f);
440
            }
441
            return false;
442
        }
443
        function StartUpload() {
426
        function StartUpload() {
444
            if( $('#fileToUpload').prop('files').length == 0 ) return;
427
            if( $('#fileToUpload').prop('files').length == 0 ) return;
445
            $('#fileuploadbutton').hide();
428
            $('#fileuploadbutton').hide();
(-)a/tools/stage-marc-import.pl (-153 / +37 lines)
Lines 30-53 use Modern::Perl; Link Here
30
use CGI qw ( -utf8 );
30
use CGI qw ( -utf8 );
31
use CGI::Cookie;
31
use CGI::Cookie;
32
use MARC::File::USMARC;
32
use MARC::File::USMARC;
33
use Try::Tiny;
33
34
34
# Koha modules used
35
# Koha modules used
35
use C4::Context;
36
use C4::Context;
36
use C4::Auth qw( get_template_and_user );
37
use C4::Auth qw( get_template_and_user );
37
use C4::Output qw( output_html_with_http_headers );
38
use C4::Output qw( output_html_with_http_headers );
38
use C4::ImportBatch qw( RecordsFromMARCXMLFile RecordsFromISO2709File RecordsFromMarcPlugin BatchStageMarcRecords BatchFindDuplicates SetImportBatchMatcher SetImportBatchOverlayAction SetImportBatchNoMatchAction SetImportBatchItemAction );
39
use C4::Matcher;
39
use C4::Matcher;
40
use Koha::UploadedFiles;
40
use Koha::UploadedFiles;
41
use C4::BackgroundJob;
42
use C4::MarcModificationTemplates qw( GetModificationTemplates );
41
use C4::MarcModificationTemplates qw( GetModificationTemplates );
43
use Koha::Plugins;
42
use Koha::Plugins;
44
use Koha::ImportBatches;
43
use Koha::ImportBatches;
44
use Koha::BackgroundJob::StageMARCForImport;
45
45
46
my $input = CGI->new;
46
my $input = CGI->new;
47
47
48
my $fileID                     = $input->param('uploadedfileid');
48
my $fileID                     = $input->param('uploadedfileid');
49
my $runinbackground            = $input->param('runinbackground');
50
my $completedJobID             = $input->param('completedJobID');
51
my $matcher_id                 = $input->param('matcher');
49
my $matcher_id                 = $input->param('matcher');
52
my $overlay_action             = $input->param('overlay_action');
50
my $overlay_action             = $input->param('overlay_action');
53
my $nomatch_action             = $input->param('nomatch_action');
51
my $nomatch_action             = $input->param('nomatch_action');
Lines 61-66 my $marc_modification_template = $input->param('marc_modification_template_id'); Link Here
61
my $basketno                   = $input->param('basketno');
59
my $basketno                   = $input->param('basketno');
62
my $booksellerid               = $input->param('booksellerid');
60
my $booksellerid               = $input->param('booksellerid');
63
my $profile_id                 = $input->param('profile_id');
61
my $profile_id                 = $input->param('profile_id');
62
my @messages;
64
63
65
my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
64
my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
66
    {
65
    {
Lines 72-215 my ( $template, $loggedinuser, $cookie ) = get_template_and_user( Link Here
72
);
71
);
73
72
74
$template->param(
73
$template->param(
75
    SCRIPT_NAME => '/cgi-bin/koha/tools/stage-marc-import.pl',
74
    basketno     => $basketno,
76
    uploadmarc  => $fileID,
77
    record_type => $record_type,
78
    basketno => $basketno,
79
    booksellerid => $booksellerid,
75
    booksellerid => $booksellerid,
80
);
76
);
81
77
82
my %cookies = CGI::Cookie->fetch();
78
if ($fileID) {
83
my $sessionID = $cookies{'CGISESSID'}->value;
84
if ($completedJobID) {
85
    my $job = C4::BackgroundJob->fetch($sessionID, $completedJobID);
86
    my $results = $job->results();
87
    $template->param(map { $_ => $results->{$_} } keys %{ $results });
88
} elsif ($fileID) {
89
    my $upload = Koha::UploadedFiles->find( $fileID );
79
    my $upload = Koha::UploadedFiles->find( $fileID );
90
    my $file = $upload->full_path;
80
    my $filepath = $upload->full_path;
91
    my $filename = $upload->filename;
81
    my $filename = $upload->filename;
92
82
93
    my ( $errors, $marcrecords );
83
    my $params = {
94
    if( $format eq 'MARCXML' ) {
84
        record_type                => $record_type,
95
        ( $errors, $marcrecords ) = C4::ImportBatch::RecordsFromMARCXMLFile( $file, $encoding);
85
        encoding                   => $encoding,
96
    } elsif( $format eq 'ISO2709' ) {
86
        format                     => $format,
97
        ( $errors, $marcrecords ) = C4::ImportBatch::RecordsFromISO2709File( $file, $record_type, $encoding );
87
        filepath                   => $filepath,
98
    } else { # plugin based
88
        filename                   => $filename,
99
        $errors = [];
89
        marc_modification_template => $marc_modification_template,
100
        $marcrecords = C4::ImportBatch::RecordsFromMarcPlugin( $file, $format, $encoding );
90
        comments                   => $comments,
101
    }
91
        parse_items                => $parse_items,
102
    warn "$filename: " . ( join ',', @$errors ) if @$errors;
92
        matcher_id                 => $matcher_id,
103
        # no need to exit if we have no records (or only errors) here
93
        overlay_action             => $overlay_action,
104
        # BatchStageMarcRecords can handle that
94
        nomatch_action             => $nomatch_action,
105
95
        item_action                => $item_action,
106
    my $job = undef;
96
    };
107
    if ($runinbackground) {
97
    try {
108
        my $job_size = scalar(@$marcrecords);
98
        my $job_id = Koha::BackgroundJob::StageMARCForImport->new->enqueue( $params );
109
        # if we're matching, job size is doubled
99
        if ($job_id) {
110
        $job_size *= 2 if ($matcher_id ne "");
100
            $template->param(
111
        $job = C4::BackgroundJob->new($sessionID, $filename, '/cgi-bin/koha/tools/stage-marc-import.pl', $job_size);
101
                job_enqueued => 1,
112
        my $jobID = $job->id();
102
                job_id => $job_id,
113
103
            );
114
        # fork off
115
        if (my $pid = fork) {
116
            # parent
117
            # return job ID as JSON
118
            my $reply = CGI->new("");
119
            print $reply->header(-type => 'text/html');
120
            print '{"jobID":"' . $jobID . '"}';
121
            exit 0;
122
        } elsif (defined $pid) {
123
            # child
124
            # close STDOUT/STDERR to signal to end CGI session with Apache
125
            # Otherwise, the AJAX request to this script won't return properly
126
            close STDOUT;
127
            close STDERR;
128
        } else {
129
            # fork failed, so exit immediately
130
            warn "fork failed while attempting to run tools/stage-marc-import.pl as a background job: $!";
131
            exit 0;
132
        }
133
134
        # if we get here, we're a child that has detached
135
        # itself from Apache
136
137
    }
138
139
    my $schema = Koha::Database->new->schema;
140
    $schema->storage->txn_begin;
141
142
    # FIXME branch code
143
    my ( $batch_id, $num_valid, $num_items, @import_errors ) =
144
      BatchStageMarcRecords(
145
        $record_type,    $encoding,
146
        $marcrecords,    $filename,
147
        $marc_modification_template,
148
        $comments,       '',
149
        $parse_items,    0,
150
        50, staging_progress_callback( $job )
151
      );
152
153
    if($profile_id) {
154
        my $ibatch = Koha::ImportBatches->find($batch_id);
155
        $ibatch->set({profile_id => $profile_id})->store;
156
    }
157
158
    my $num_with_matches = 0;
159
    my $checked_matches = 0;
160
    my $matcher_failed = 0;
161
    my $matcher_code = "";
162
    if ($matcher_id ne "") {
163
        my $matcher = C4::Matcher->fetch($matcher_id);
164
        if (defined $matcher) {
165
            $checked_matches = 1;
166
            $matcher_code = $matcher->code();
167
            $num_with_matches =
168
              BatchFindDuplicates( $batch_id, $matcher, 10, 50,
169
                matching_progress_callback($job) );
170
            SetImportBatchMatcher($batch_id, $matcher_id);
171
            SetImportBatchOverlayAction($batch_id, $overlay_action);
172
            SetImportBatchNoMatchAction($batch_id, $nomatch_action);
173
            SetImportBatchItemAction($batch_id, $item_action);
174
            $schema->storage->txn_commit;
175
        } else {
176
            $matcher_failed = 1;
177
            $schema->storage->txn_rollback;
178
        }
104
        }
179
    } else {
180
        $schema->storage->txn_commit;
181
    }
105
    }
182
106
    catch {
183
    my $results = {
107
        warn $_;
184
        staged          => $num_valid,
108
        push @messages,
185
        matched         => $num_with_matches,
109
          {
186
        num_items       => $num_items,
110
            type  => 'error',
187
        import_errors   => scalar(@import_errors),
111
            code  => 'cannot_enqueue_job',
188
        total           => $num_valid + scalar(@import_errors),
112
            error => $_,
189
        checked_matches => $checked_matches,
113
          };
190
        matcher_failed  => $matcher_failed,
191
        matcher_code    => $matcher_code,
192
        import_batch_id => $batch_id,
193
        booksellerid    => $booksellerid,
194
        basketno        => $basketno
195
    };
114
    };
196
    if ($runinbackground) {
197
        $job->finish($results);
198
        exit 0;
199
    } else {
200
	    $template->param(staged => $num_valid,
201
 	                     matched => $num_with_matches,
202
                         num_items => $num_items,
203
                         import_errors => scalar(@import_errors),
204
                         total => $num_valid + scalar(@import_errors),
205
                         checked_matches => $checked_matches,
206
                         matcher_failed => $matcher_failed,
207
                         matcher_code => $matcher_code,
208
                         import_batch_id => $batch_id,
209
                         booksellerid => $booksellerid,
210
                         basketno => $basketno
211
                        );
212
    }
213
115
214
} else {
116
} else {
215
    # initial form
117
    # initial form
Lines 231-253 if ($completedJobID) { Link Here
231
    }
133
    }
232
}
134
}
233
135
234
output_html_with_http_headers $input, $cookie, $template->output;
136
$template->param( messages => \@messages );
235
236
exit 0;
237
137
238
sub staging_progress_callback {
138
output_html_with_http_headers $input, $cookie, $template->output;
239
    my $job = shift;
240
    return sub {
241
        my $progress = shift;
242
        $job->progress($progress);
243
    }
244
}
245
246
sub matching_progress_callback {
247
    my $job = shift;
248
    my $start_progress = $job->progress();
249
    return sub {
250
        my $progress = shift;
251
        $job->progress($start_progress + $progress);
252
    }
253
}
254
- 

Return to bug 27421