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