Merge remote-tracking branch 'kc/new/enh/bug_5922' into kcmaster
[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 Number::Format qw(:all);
28
29 use C4::Context;
30 use C4::Auth;
31 use C4::Input;
32 use C4::Output;
33 use C4::ImportBatch;
34 use C4::Matcher;
35 use C4::Search qw/FindDuplicate BiblioAddAuthorities/;
36 use C4::Acquisition;
37 use C4::Biblio;
38 use C4::Items;
39 use C4::Koha;
40 use C4::Budgets;
41 use C4::Acquisition;
42 use C4::Bookseller qw/GetBookSellerFromId/;
43 use C4::Dates;
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             # 2nd add authorities if applicable
183             if (C4::Context->preference("BiblioAddsAuthorities")){
184                 my ($countlinked,$countcreated)=BiblioAddAuthorities($marcrecord, $cgiparams->{'frameworkcode'});
185             }
186         } else {
187             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
188         }
189         # 3rd add order
190         my $patron = C4::Members->GetMember( borrowernumber => $loggedinuser );
191         my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
192         my ($invoice);
193         # get quantity in the MARC record (1 if none)
194         my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
195         my %orderinfo = (
196             "biblionumber", $biblionumber, "basketno", $cgiparams->{'basketno'},
197             "quantity", $quantity, "branchcode", $branch, 
198             "booksellerinvoicenumber", $invoice, 
199             "budget_id", $budget_id, "uncertainprice", 1,
200             "sort1", $cgiparams->{'sort1'},"sort2", $cgiparams->{'sort2'},
201             "notes", $cgiparams->{'notes'}, "budget_id", $cgiparams->{'budget_id'},
202             "currency",$cgiparams->{'currency'},
203         );
204         # get the price if there is one.
205         # filter by storing only the 1st number
206         # we suppose the currency is correct, as we have no possibilities to get it.
207         my $price= GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
208         if ($price){
209             $price = $num->unformat_number($price);
210         }
211         if ($price){
212             $orderinfo{'listprice'} = $price;
213             eval "use C4::Acquisition qw/GetBasket/;";
214             eval "use C4::Bookseller qw/GetBookSellerFromId/;";
215             my $basket     = GetBasket( $orderinfo{basketno} );
216             my $bookseller = GetBookSellerFromId( $basket->{booksellerid} );
217             my $gst        = $bookseller->{gstrate} || C4::Context->preference("gist") || 0;
218             $orderinfo{'unitprice'} = $orderinfo{listprice} - ( $orderinfo{listprice} * ( $bookseller->{discount} / 100 ) );
219             $orderinfo{'ecost'} = $orderinfo{unitprice};
220         } else {
221             $orderinfo{'listprice'} = 0;
222         }
223         $orderinfo{'rrp'} = $orderinfo{'listprice'};
224
225         # remove uncertainprice flag if we have found a price in the MARC record
226         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
227         my $basketno;
228         ( $basketno, $ordernumber ) = NewOrder( \%orderinfo );
229
230         # 4th, add items if applicable
231         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
232         # this is not optimised, but it's working !
233         if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
234             my @tags         = $input->param('tag');
235             my @subfields    = $input->param('subfield');
236             my @field_values = $input->param('field_value');
237             my @serials      = $input->param('serial');
238             my @ind_tag   = $input->param('ind_tag');
239             my @indicator = $input->param('indicator');
240             my $item;
241             push @{ $item->{tags} },         $tags[0];
242             push @{ $item->{subfields} },    $subfields[0];
243             push @{ $item->{field_values} }, $field_values[0];
244             push @{ $item->{ind_tag} },      $ind_tag[0];
245             push @{ $item->{indicator} },    $indicator[0];
246             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
247             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
248             for (my $qtyloop=1;$qtyloop <=$quantity;$qtyloop++) {
249                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
250                 NewOrderItem( $itemnumber, $ordernumber );
251             }
252         }
253     }
254     # go to basket page
255     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
256     exit;
257 }
258
259 my $budgets = GetBudgets();
260 my $budget_id = @$budgets[0]->{'budget_id'};
261 # build bookfund list
262 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
263 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
264 my $budget = GetBudget($budget_id);
265
266 # build budget list
267 my $budget_loop = [];
268 my $budgets = GetBudgetHierarchy( q{}, $borrower->{branchcode}, $borrower->{borrowernumber} );
269 foreach my $r ( @{$budgets} ) {
270     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
271         next;
272     }
273     push @{$budget_loop},
274       { b_id  => $r->{budget_id},
275         b_txt => $r->{budget_name},
276         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
277       };
278 }
279 $template->param( budget_loop    => $budget_loop,);
280
281 my $CGIsort1;
282 if ($budget) {    # its a mod ..
283     if ( defined $budget->{'sort1_authcat'} ) {    # with custom  Asort* planning values
284         $CGIsort1 = GetAuthvalueDropbox( 'sort1', $budget->{'sort1_authcat'}, $data->{'sort1'} );
285     }
286 } elsif ( scalar(@$budgets) ) {
287     $CGIsort1 = GetAuthvalueDropbox( 'sort1', @$budgets[0]->{'sort1_authcat'}, '' );
288 } else {
289     $CGIsort1 = GetAuthvalueDropbox( 'sort1', '', '' );
290 }
291
292 # if CGIsort is successfully fetched, the use it
293 # else - failback to plain input-field
294 if ($CGIsort1) {
295     $template->param( CGIsort1 => $CGIsort1 );
296 } else {
297     $template->param( sort1 => $data->{'sort1'} );
298 }
299
300 my $CGIsort2;
301 if ($budget) {
302     if ( defined $budget->{'sort2_authcat'} ) {
303         $CGIsort2 = GetAuthvalueDropbox( 'sort2', $budget->{'sort2_authcat'}, $data->{'sort2'} );
304     }
305 } elsif ( scalar(@$budgets) ) {
306     $CGIsort2 = GetAuthvalueDropbox( 'sort2', @$budgets[0]->{sort2_authcat}, '' );
307 } else {
308     $CGIsort2 = GetAuthvalueDropbox( 'sort2', '', '' );
309 }
310
311 if ($CGIsort2) {
312     $template->param( CGIsort2 => $CGIsort2 );
313 } else {
314     $template->param( sort2 => $data->{'sort2'} );
315 }
316
317 output_html_with_http_headers $input, $cookie, $template->output;
318
319
320 sub import_batches_list {
321     my ($template) = @_;
322     my $batches = GetImportBatchRangeDesc();
323
324     my @list = ();
325     foreach my $batch (@$batches) {
326         if ($batch->{'import_status'} eq "staged") {
327         push @list, {
328                 import_batch_id => $batch->{'import_batch_id'},
329                 num_biblios => $batch->{'num_biblios'},
330                 num_items => $batch->{'num_items'},
331                 upload_timestamp => $batch->{'upload_timestamp'},
332                 import_status => $batch->{'import_status'},
333                 file_name => $batch->{'file_name'},
334                 comments => $batch->{'comments'},
335             };
336         }
337     }
338     $template->param(batch_list => \@list); 
339     my $num_batches = GetNumberOfNonZ3950ImportBatches();
340     $template->param(num_results => $num_batches);
341 }
342
343 sub import_biblios_list {
344     my ($template, $import_batch_id) = @_;
345     my $batch = GetImportBatch($import_batch_id,'staged');
346     my $biblios = GetImportBibliosRange($import_batch_id,'','','staged');
347     my @list = ();
348
349     foreach my $biblio (@$biblios) {
350         my $citation = $biblio->{'title'};
351         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
352         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
353         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
354         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
355         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
356         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
357         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
358         my %cellrecord = (
359             import_record_id => $biblio->{'import_record_id'},
360             citation => $citation,
361             import  => 1,
362             status => $biblio->{'status'},
363             record_sequence => $biblio->{'record_sequence'},
364             overlay_status => $biblio->{'overlay_status'},
365             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
366             match_citation => $#$match > -1 ? $match->[0]->{'title'} . ' ' . $match->[0]->{'author'} : '',
367             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
368         );
369         push @list, \%cellrecord;
370     }
371     my $num_biblios = $batch->{'num_biblios'};
372     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
373     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
374     my $item_action = GetImportBatchItemAction($import_batch_id);
375     $template->param(biblio_list => \@list,
376                         num_results => $num_biblios,
377                         import_batch_id => $import_batch_id,
378                         "overlay_action_${overlay_action}" => 1,
379                         overlay_action => $overlay_action,
380                         "nomatch_action_${nomatch_action}" => 1,
381                         nomatch_action => $nomatch_action,
382                         "item_action_${item_action}" => 1,
383                         item_action => $item_action
384                     );
385     batch_info($template, $batch);
386 }
387
388 sub batch_info {
389     my ($template, $batch) = @_;
390     $template->param(batch_info => 1,
391                                       file_name => $batch->{'file_name'},
392                                           comments => $batch->{'comments'},
393                                           import_status => $batch->{'import_status'},
394                                           upload_timestamp => $batch->{'upload_timestamp'},
395                                           num_biblios => $batch->{'num_biblios'},
396                                           num_items => $batch->{'num_biblios'});
397     if ($batch->{'num_biblios'} > 0) {
398         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
399             $template->param(can_commit => 1);
400         }
401         if ($batch->{'import_status'} eq 'imported') {
402             $template->param(can_revert => 1);
403         }
404     }
405     if (defined $batch->{'matcher_id'}) {
406         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
407         if (defined $matcher) {
408             $template->param('current_matcher_id' => $batch->{'matcher_id'},
409                                               'current_matcher_code' => $matcher->code(),
410                                               'current_matcher_description' => $matcher->description());
411         }
412     }
413     add_matcher_list($batch->{'matcher_id'});
414 }
415
416 sub add_matcher_list {
417     my $current_matcher_id = shift;
418     my @matchers = C4::Matcher::GetMatcherList();
419     if (defined $current_matcher_id) {
420         for (my $i = 0; $i <= $#matchers; $i++) {
421             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
422                 $matchers[$i]->{'selected'} = 1;
423             }
424         }
425     }
426     $template->param(available_matchers => \@matchers);
427 }