Merge remote-tracking branch 'origin/master' into new/bug_6679
[koha.git] / acqui / addorderiso2709.pl
1 #!/usr/bin/perl
2
3 #A script that lets the user populate a basket from an iso2709 file
4 #the script first displays a list of import batches, then when a batch is selected displays all the biblios in it.
5 #The user can then pick which biblios he wants to order
6
7 # Copyright 2008 - 2011 BibLibre SARL
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along
21 # with Koha; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
24 use strict;
25 use warnings;
26 use CGI;
27 use Carp;
28 use Number::Format qw(:all);
29
30 use C4::Context;
31 use C4::Auth;
32 use C4::Input;
33 use C4::Output;
34 use C4::ImportBatch;
35 use C4::Matcher;
36 use C4::Search qw/FindDuplicate BiblioAddAuthorities/;
37 use C4::Acquisition;
38 use C4::Biblio;
39 use C4::Items;
40 use C4::Koha;
41 use C4::Budgets;
42 use C4::Acquisition;
43 use C4::Bookseller qw/GetBookSellerFromId/;
44 use C4::Dates;
45 use C4::Suggestions;    # GetSuggestion
46 use C4::Branch;         # GetBranches
47 use C4::Members;
48
49 my $input = new CGI;
50 my ($template, $loggedinuser, $cookie) = get_template_and_user({
51                                         template_name => "acqui/addorderiso2709.tmpl",
52                                         query => $input,
53                                         type => "intranet",
54                                         authnotrequired => 0,
55                                         flagsrequired   => { acquisition => 'order_manage' },
56                                         debug => 1,
57                                         });
58 my $cgiparams = $input->Vars;
59 my $op = $cgiparams->{'op'};
60 my $booksellerid  = $input->param('booksellerid');
61 my $bookseller = GetBookSellerFromId($booksellerid);
62 my $data;
63
64 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
65                 booksellerid => $booksellerid,
66                 booksellername => $bookseller->{name},
67                 );
68 my $ordernumber;
69
70 if ($cgiparams->{'import_batch_id'} && $op eq ""){
71     $op = "batch_details";
72 }
73
74 #Needed parameters:
75 if (! $cgiparams->{'basketno'}){
76     die "Basketnumber required to order from iso2709 file import";
77 }
78
79 #
80 # 1st step = choose the file to import into acquisition
81 #
82 if ($op eq ""){
83     $template->param("basketno" => $cgiparams->{'basketno'});
84 #display batches
85     import_batches_list($template);
86 #
87 # 2nd step = display the content of the choosen file
88 #
89 } elsif ($op eq "batch_details"){
90 #display lines inside the selected batch
91     # get currencies (for change rates calcs if needed)
92     my $active_currency = GetCurrency();
93     my $default_currency;
94     if (! $data->{currency} ) { # New order no currency set
95         if ( $bookseller->{listprice} ) {
96             $default_currency = $bookseller->{listprice};
97         }
98         else {
99             $default_currency = $active_currency->{currency};
100         }
101     }
102     my @rates = GetCurrencies();
103
104     # ## @rates
105
106     my @loop_currency = ();
107     for my $curr ( @rates ) {
108         my $selected;
109         if ($data->{currency} ) {
110             $selected = $curr->{currency} eq $data->{currency};
111         }
112         else {
113             $selected = $curr->{currency} eq $default_currency;
114         }
115         push @loop_currency, {
116             currcode => $curr->{currency},
117             rate     => $curr->{rate},
118             selected => $selected,
119         }
120     }
121
122     $template->param("batch_details" => 1,
123                      "basketno"      => $cgiparams->{'basketno'},
124                      loop_currencies  => \@loop_currency,
125                      );
126     import_biblios_list($template, $cgiparams->{'import_batch_id'});
127     if ( C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber ) {
128         # prepare empty item form
129         my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
130
131         #     warn "==> ".Data::Dumper::Dumper($cell);
132         unless ($cell) {
133             $cell = PrepareItemrecordDisplay( '', '', '', '' );
134             $template->param( 'NoACQframework' => 1 );
135         }
136         my @itemloop;
137         push @itemloop, $cell;
138
139         $template->param( items => \@itemloop );
140     }
141 #
142 # 3rd step = import the records
143 #
144 } elsif ( $op eq 'import_records' ) {
145     my $num=FormatNumber();
146 #import selected lines
147     $template->param('basketno' => $cgiparams->{'basketno'});
148 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
149     my $budgets = GetBudgets();
150     if (scalar @$budgets == 0){
151         die "No budgets defined, can't continue";
152     }
153     my $budget_id = @$budgets[0]->{'budget_id'};
154 #get all records from a batch, and check their import status to see if they are checked.
155 #(default values: quantity 1, uncertainprice yes, first budget)
156
157     # retrieve the file you want to import
158     my $import_batch_id = $cgiparams->{'import_batch_id'};
159     my $biblios = GetImportBibliosRange($import_batch_id);
160     for my $biblio (@$biblios){
161         # 1st insert the biblio, or find it through matcher
162         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
163         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
164         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
165         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
166
167         unless ( $biblionumber ) {
168             # add the biblio
169             my $bibitemnum;
170
171             # remove ISBN -
172             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );                
173             if ( $marcrecord->field($isbnfield) ) {
174                 foreach my $field ( $marcrecord->field($isbnfield) ) {
175                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
176                         my $newisbn = $field->subfield($isbnsubfield);
177                         $newisbn =~ s/-//g;
178                         $field->update( $isbnsubfield => $newisbn );
179                     }
180                 }
181             }
182             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
183             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
184             # 2nd add authorities if applicable
185             if (C4::Context->preference("BiblioAddsAuthorities")){
186                 my ($countlinked,$countcreated)=BiblioAddAuthorities($marcrecord, $cgiparams->{'frameworkcode'});
187             }
188         } else {
189             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
190         }
191         # 3rd add order
192         my $patron = C4::Members->GetMember( borrowernumber => $loggedinuser );
193         my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
194         my ($invoice);
195         # get quantity in the MARC record (1 if none)
196         my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
197         my %orderinfo = (
198             "biblionumber", $biblionumber, "basketno", $cgiparams->{'basketno'},
199             "quantity", $quantity, "branchcode", $branch, 
200             "booksellerinvoicenumber", $invoice, 
201             "budget_id", $budget_id, "uncertainprice", 1,
202             "sort1", $cgiparams->{'sort1'},"sort2", $cgiparams->{'sort2'},
203             "notes", $cgiparams->{'notes'}, "budget_id", $cgiparams->{'budget_id'},
204             "currency",$cgiparams->{'currency'},
205         );
206         # get the price if there is one.
207         # filter by storing only the 1st number
208         # we suppose the currency is correct, as we have no possibilities to get it.
209         my $price= GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
210         if ($price){
211             $price = $num->unformat_number($price);
212         }
213         if ($price){
214             $orderinfo{'listprice'} = $price;
215             eval {
216                 require C4::Acquisition;
217                 import C4::Acquisition qw/GetBasket/;
218             };
219             if ($@){
220                 croak $@;
221             }
222             eval {
223                 require C4::Bookseller;
224                 import C4::Bookseller qw/GetBookSellerFromId/;
225             };
226             if ($@){
227                 croak $@;
228             }
229             my $basket     = GetBasket( $orderinfo{basketno} );
230             my $bookseller = GetBookSellerFromId( $basket->{booksellerid} );
231             my $gst        = $bookseller->{gstrate} || C4::Context->preference("gist") || 0;
232             $orderinfo{'unitprice'} = $orderinfo{listprice} - ( $orderinfo{listprice} * ( $bookseller->{discount} / 100 ) );
233             $orderinfo{'ecost'} = $orderinfo{unitprice};
234         } else {
235             $orderinfo{'listprice'} = 0;
236         }
237         $orderinfo{'rrp'} = $orderinfo{'listprice'};
238
239         # remove uncertainprice flag if we have found a price in the MARC record
240         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
241         my $basketno;
242         ( $basketno, $ordernumber ) = NewOrder( \%orderinfo );
243
244         # 4th, add items if applicable
245         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
246         # this is not optimised, but it's working !
247         if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
248             my @tags         = $input->param('tag');
249             my @subfields    = $input->param('subfield');
250             my @field_values = $input->param('field_value');
251             my @serials      = $input->param('serial');
252             my @ind_tag   = $input->param('ind_tag');
253             my @indicator = $input->param('indicator');
254             my $item;
255             push @{ $item->{tags} },         $tags[0];
256             push @{ $item->{subfields} },    $subfields[0];
257             push @{ $item->{field_values} }, $field_values[0];
258             push @{ $item->{ind_tag} },      $ind_tag[0];
259             push @{ $item->{indicator} },    $indicator[0];
260             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
261             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
262             for (my $qtyloop=1;$qtyloop <=$quantity;$qtyloop++) {
263                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
264                 NewOrderItem( $itemnumber, $ordernumber );
265             }
266         } else {
267             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
268         }
269     }
270     # go to basket page
271     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
272     exit;
273 }
274
275 my $budgets = GetBudgets();
276 my $budget_id = @$budgets[0]->{'budget_id'};
277 # build bookfund list
278 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
279 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
280 my $budget = GetBudget($budget_id);
281
282 # build budget list
283 my $budget_loop = [];
284 $budgets = GetBudgetHierarchy( q{}, $borrower->{branchcode}, $borrower->{borrowernumber} );
285 foreach my $r ( @{$budgets} ) {
286     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
287         next;
288     }
289     push @{$budget_loop},
290       { b_id  => $r->{budget_id},
291         b_txt => $r->{budget_name},
292         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
293       };
294 }
295 $template->param( budget_loop    => $budget_loop,);
296
297 my $CGIsort1;
298 if ($budget) {    # its a mod ..
299     if ( defined $budget->{'sort1_authcat'} ) {    # with custom  Asort* planning values
300         $CGIsort1 = GetAuthvalueDropbox(  $budget->{'sort1_authcat'}, $data->{'sort1'} );
301     }
302 } elsif ( scalar(@$budgets) ) {
303     $CGIsort1 = GetAuthvalueDropbox(  @$budgets[0]->{'sort1_authcat'}, '' );
304 } else {
305     $CGIsort1 = GetAuthvalueDropbox(  '', '' );
306 }
307
308 # if CGIsort is successfully fetched, the use it
309 # else - failback to plain input-field
310 if ($CGIsort1) {
311     $template->param( CGIsort1 => $CGIsort1 );
312 } else {
313     $template->param( sort1 => $data->{'sort1'} );
314 }
315
316 my $CGIsort2;
317 if ($budget) {
318     if ( defined $budget->{'sort2_authcat'} ) {
319         $CGIsort2 = GetAuthvalueDropbox(  $budget->{'sort2_authcat'}, $data->{'sort2'} );
320     }
321 } elsif ( scalar(@$budgets) ) {
322     $CGIsort2 = GetAuthvalueDropbox(  @$budgets[0]->{sort2_authcat}, '' );
323 } else {
324     $CGIsort2 = GetAuthvalueDropbox( '', '' );
325 }
326
327 if ($CGIsort2) {
328     $template->param( CGIsort2 => $CGIsort2 );
329 } else {
330     $template->param( sort2 => $data->{'sort2'} );
331 }
332
333 output_html_with_http_headers $input, $cookie, $template->output;
334
335
336 sub import_batches_list {
337     my ($template) = @_;
338     my $batches = GetImportBatchRangeDesc();
339
340     my @list = ();
341     foreach my $batch (@$batches) {
342         if ($batch->{'import_status'} eq "staged") {
343             # check if there is at least 1 line still staged
344             my $stagedList=GetImportBibliosRange($batch->{'import_batch_id'}, undef, undef, 'staged');
345             if (scalar @$stagedList) {
346                 push @list, {
347                         import_batch_id => $batch->{'import_batch_id'},
348                         num_biblios => $batch->{'num_biblios'},
349                         num_items => $batch->{'num_items'},
350                         upload_timestamp => $batch->{'upload_timestamp'},
351                         import_status => $batch->{'import_status'},
352                         file_name => $batch->{'file_name'},
353                         comments => $batch->{'comments'},
354                 };
355             } else {
356                 # if there are no more line to includes, set the status to imported
357                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
358             }
359         }
360     }
361     $template->param(batch_list => \@list); 
362     my $num_batches = GetNumberOfNonZ3950ImportBatches();
363     $template->param(num_results => $num_batches);
364 }
365
366 sub import_biblios_list {
367     my ($template, $import_batch_id) = @_;
368     my $batch = GetImportBatch($import_batch_id,'staged');
369     my $biblios = GetImportBibliosRange($import_batch_id,'','','staged');
370     my @list = ();
371
372     foreach my $biblio (@$biblios) {
373         my $citation = $biblio->{'title'};
374         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
375         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
376         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
377         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
378         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
379         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
380         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
381         my %cellrecord = (
382             import_record_id => $biblio->{'import_record_id'},
383             citation => $citation,
384             import  => 1,
385             status => $biblio->{'status'},
386             record_sequence => $biblio->{'record_sequence'},
387             overlay_status => $biblio->{'overlay_status'},
388             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
389             match_citation => $#$match > -1 ? $match->[0]->{'title'} . ' ' . $match->[0]->{'author'} : '',
390             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
391         );
392         push @list, \%cellrecord;
393     }
394     my $num_biblios = $batch->{'num_biblios'};
395     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
396     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
397     my $item_action = GetImportBatchItemAction($import_batch_id);
398     $template->param(biblio_list => \@list,
399                         num_results => $num_biblios,
400                         import_batch_id => $import_batch_id,
401                         "overlay_action_${overlay_action}" => 1,
402                         overlay_action => $overlay_action,
403                         "nomatch_action_${nomatch_action}" => 1,
404                         nomatch_action => $nomatch_action,
405                         "item_action_${item_action}" => 1,
406                         item_action => $item_action
407                     );
408     batch_info($template, $batch);
409 }
410
411 sub batch_info {
412     my ($template, $batch) = @_;
413     $template->param(batch_info => 1,
414                                       file_name => $batch->{'file_name'},
415                                           comments => $batch->{'comments'},
416                                           import_status => $batch->{'import_status'},
417                                           upload_timestamp => $batch->{'upload_timestamp'},
418                                           num_biblios => $batch->{'num_biblios'},
419                                           num_items => $batch->{'num_biblios'});
420     if ($batch->{'num_biblios'} > 0) {
421         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
422             $template->param(can_commit => 1);
423         }
424         if ($batch->{'import_status'} eq 'imported') {
425             $template->param(can_revert => 1);
426         }
427     }
428     if (defined $batch->{'matcher_id'}) {
429         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
430         if (defined $matcher) {
431             $template->param('current_matcher_id' => $batch->{'matcher_id'},
432                                               'current_matcher_code' => $matcher->code(),
433                                               'current_matcher_description' => $matcher->description());
434         }
435     }
436     add_matcher_list($batch->{'matcher_id'});
437 }
438
439 sub add_matcher_list {
440     my $current_matcher_id = shift;
441     my @matchers = C4::Matcher::GetMatcherList();
442     if (defined $current_matcher_id) {
443         for (my $i = 0; $i <= $#matchers; $i++) {
444             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
445                 $matchers[$i]->{'selected'} = 1;
446             }
447         }
448     }
449     $template->param(available_matchers => \@matchers);
450 }