Bug 16493: [QA Followup] Restore title and author match as an option, make it the...
[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
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24 use Modern::Perl;
25 use CGI qw ( -utf8 );
26 use Carp;
27 use YAML qw/Load/;
28
29 use C4::Context;
30 use C4::Auth;
31 use C4::Output;
32 use C4::ImportBatch;
33 use C4::Matcher;
34 use C4::Search qw/FindDuplicate/;
35 use C4::Acquisition;
36 use C4::Biblio;
37 use C4::Items;
38 use C4::Koha;
39 use C4::Budgets;
40 use C4::Acquisition;
41 use C4::Suggestions;    # GetSuggestion
42 use C4::Branch;         # GetBranches
43 use C4::Members;
44
45 use Koha::Number::Price;
46 use Koha::Acquisition::Order;
47 use Koha::Acquisition::Bookseller;
48
49 my $input = new CGI;
50 my ($template, $loggedinuser, $cookie, $userflags) = get_template_and_user({
51     template_name => "acqui/addorderiso2709.tt",
52     query => $input,
53     type => "intranet",
54     authnotrequired => 0,
55     flagsrequired   => { acquisition => 'order_manage' },
56     debug => 1,
57 });
58
59 my $cgiparams = $input->Vars;
60 my $op = $cgiparams->{'op'} || '';
61 my $booksellerid  = $input->param('booksellerid');
62 my $allmatch = $input->param('allmatch');
63 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
64 my $data;
65
66 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
67                 booksellerid => $booksellerid,
68                 booksellername => $bookseller->{name},
69                 );
70
71 if ($cgiparams->{'import_batch_id'} && $op eq ""){
72     $op = "batch_details";
73 }
74
75 #Needed parameters:
76 if (! $cgiparams->{'basketno'}){
77     die "Basketnumber required to order from iso2709 file import";
78 }
79
80 #
81 # 1st step = choose the file to import into acquisition
82 #
83 if ($op eq ""){
84     $template->param("basketno" => $cgiparams->{'basketno'});
85 #display batches
86     import_batches_list($template);
87 #
88 # 2nd step = display the content of the chosen file
89 #
90 } elsif ($op eq "batch_details"){
91 #display lines inside the selected batch
92     # get currencies (for change rates calcs if needed)
93     my $active_currency = GetCurrency();
94     my $default_currency;
95     if (! $data->{currency} ) { # New order no currency set
96         if ( $bookseller->{listprice} ) {
97             $default_currency = $bookseller->{listprice};
98         }
99         else {
100             $default_currency = $active_currency->{currency};
101         }
102     }
103     my @rates = GetCurrencies();
104
105     # ## @rates
106
107     my @loop_currency = ();
108     for my $curr ( @rates ) {
109         my $selected;
110         if ($data->{currency} ) {
111             $selected = $curr->{currency} eq $data->{currency};
112         }
113         else {
114             $selected = $curr->{currency} eq $default_currency;
115         }
116         push @loop_currency, {
117             currcode => $curr->{currency},
118             rate     => $curr->{rate},
119             selected => $selected,
120         }
121     }
122
123     $template->param("batch_details" => 1,
124                      "basketno"      => $cgiparams->{'basketno'},
125                      loop_currencies  => \@loop_currency,
126                      "allmatch" => $allmatch,
127                      );
128     import_biblios_list($template, $cgiparams->{'import_batch_id'});
129     if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
130         # prepare empty item form
131         my $cell = PrepareItemrecordDisplay( '', '', '', 'ACQ' );
132
133         #     warn "==> ".Data::Dumper::Dumper($cell);
134         unless ($cell) {
135             $cell = PrepareItemrecordDisplay( '', '', '', '' );
136             $template->param( 'NoACQframework' => 1 );
137         }
138         my @itemloop;
139         push @itemloop, $cell;
140
141         $template->param( items => \@itemloop );
142     }
143 #
144 # 3rd step = import the records
145 #
146 } elsif ( $op eq 'import_records' ) {
147 #import selected lines
148     $template->param('basketno' => $cgiparams->{'basketno'});
149 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
150     my $budgets = GetBudgets();
151     if (scalar @$budgets == 0){
152         die "No budgets defined, can't continue";
153     }
154     my $budget_id = @$budgets[0]->{'budget_id'};
155 #get all records from a batch, and check their import status to see if they are checked.
156 #(default values: quantity 1, uncertainprice yes, first budget)
157
158     # retrieve the file you want to import
159     my $import_batch_id = $cgiparams->{'import_batch_id'};
160     my $biblios = GetImportRecordsRange($import_batch_id);
161     my $duplinbatch;
162     my $imported = 0;
163     my @import_record_id_selected = $input->multi_param("import_record_id");
164     my @quantities = $input->multi_param('quantity');
165     my @prices = $input->multi_param('price');
166     my @budgets_id = $input->multi_param('budget_id');
167     my @discount = $input->multi_param('discount');
168     my @sort1 = $input->multi_param('sort1');
169     my @sort2 = $input->multi_param('sort2');
170     my $matcher_id = $input->param('matcher_id');
171     my $cur = GetCurrency();
172     for my $biblio (@$biblios){
173         # Check if this import_record_id was selected
174         next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
175         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
176         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
177         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
178         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
179         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
180         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
181         my $c_discount = shift ( @discount);
182         $c_discount = $c_discount / 100 if $c_discount > 1;
183         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
184         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
185
186         # 1st insert the biblio, or find it through matcher
187         unless ( $biblionumber ) {
188             if ($matcher_id) {
189                 if ( $matcher_id eq '_TITLE_AUTHOR_' ) {
190                     $duplinbatch = $import_batch_id if FindDuplicate($marcrecord);
191                 }
192                 else {
193                     my $matcher = C4::Matcher->fetch($matcher_id);
194                     my @matches = $matcher->get_matches( $marcrecord, my $max_matches = 1 );
195                     $duplinbatch = $import_batch_id if @matches;
196                 }
197
198                 next if $duplinbatch;
199             }
200
201             # add the biblio
202             my $bibitemnum;
203
204             # remove ISBN -
205             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
206             if ( $marcrecord->field($isbnfield) ) {
207                 foreach my $field ( $marcrecord->field($isbnfield) ) {
208                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
209                         my $newisbn = $field->subfield($isbnsubfield);
210                         $newisbn =~ s/-//g;
211                         $field->update( $isbnsubfield => $newisbn );
212                     }
213                 }
214             }
215             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
216             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
217             # 2nd add authorities if applicable
218             if (C4::Context->preference("BiblioAddsAuthorities")){
219                 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
220             }
221         } else {
222             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
223         }
224         # 3rd add order
225         my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
226         my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
227         # get quantity in the MARC record (1 if none)
228         my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
229         my %orderinfo = (
230             biblionumber       => $biblionumber,
231             basketno           => $cgiparams->{'basketno'},
232             quantity           => $c_quantity,
233             branchcode         => $patron->{branchcode},
234             budget_id          => $c_budget_id,
235             uncertainprice     => 1,
236             sort1              => $c_sort1,
237             sort2              => $c_sort2,
238             order_internalnote => $cgiparams->{'all_order_internalnote'},
239             order_vendornote   => $cgiparams->{'all_order_vendornote'},
240             currency           => $cgiparams->{'all_currency'},
241         );
242         # get the price if there is one.
243         my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
244         if ($price){
245             # in France, the cents separator is the , but sometimes, ppl use a .
246             # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
247             $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
248             $price = Koha::Number::Price->new($price)->unformat;
249             $orderinfo{gstrate} = $bookseller->{gstrate};
250             my $c = $c_discount ? $c_discount : $bookseller->{discount} / 100;
251             if ( $bookseller->{listincgst} ) {
252                 if ( $c_discount ) {
253                     $orderinfo{ecost} = $price;
254                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
255                 } else {
256                     $orderinfo{ecost} = $price * ( 1 - $c );
257                     $orderinfo{rrp}   = $price;
258                 }
259             } else {
260                 if ( $c_discount ) {
261                     $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
262                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
263                 } else {
264                     $orderinfo{rrp}   = $price / ( 1 + $orderinfo{gstrate} );
265                     $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
266                 }
267             }
268             $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
269             $orderinfo{unitprice} = $orderinfo{ecost};
270             $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
271         } else {
272             $orderinfo{listprice} = 0;
273         }
274
275         # remove uncertainprice flag if we have found a price in the MARC record
276         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
277         my $order = Koha::Acquisition::Order->new( \%orderinfo )->insert;
278
279         # 4th, add items if applicable
280         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
281         # this is not optimised, but it's working !
282         if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
283             my @tags         = $input->multi_param('tag');
284             my @subfields    = $input->multi_param('subfield');
285             my @field_values = $input->multi_param('field_value');
286             my @serials      = $input->multi_param('serial');
287             my @ind_tag   = $input->multi_param('ind_tag');
288             my @indicator = $input->multi_param('indicator');
289             my $item;
290             push @{ $item->{tags} },         $tags[0];
291             push @{ $item->{subfields} },    $subfields[0];
292             push @{ $item->{field_values} }, $field_values[0];
293             push @{ $item->{ind_tag} },      $ind_tag[0];
294             push @{ $item->{indicator} },    $indicator[0];
295             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@indicator, \@ind_tag );
296             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
297             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
298                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
299                 $order->add_item( $itemnumber );
300             }
301         } else {
302             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
303         }
304         $imported++;
305     }
306     # go to basket page
307     if ( $imported ) {
308         print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'}."&amp;duplinbatch=$duplinbatch");
309     } else {
310         print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&amp;basketno=".$cgiparams->{'basketno'}."&amp;booksellerid=$booksellerid&amp;allmatch=1");
311     }
312     exit;
313 }
314
315 my $budgets = GetBudgets();
316 my $budget_id = @$budgets[0]->{'budget_id'};
317 # build bookfund list
318 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
319 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
320 my $budget = GetBudget($budget_id);
321
322 # build budget list
323 my $budget_loop = [];
324 my $budgets_hierarchy = GetBudgetHierarchy;
325 foreach my $r ( @{$budgets_hierarchy} ) {
326     next unless (CanUserUseBudget($borrower, $r, $userflags));
327     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
328         next;
329     }
330     push @{$budget_loop},
331       { b_id  => $r->{budget_id},
332         b_txt => $r->{budget_name},
333         b_sort1_authcat => $r->{'sort1_authcat'},
334         b_sort2_authcat => $r->{'sort2_authcat'},
335         b_active => $r->{budget_period_active},
336         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
337       };
338 }
339
340 @{$budget_loop} =
341   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
342
343 $template->param( budget_loop    => $budget_loop,);
344
345 output_html_with_http_headers $input, $cookie, $template->output;
346
347
348 sub import_batches_list {
349     my ($template) = @_;
350     my $batches = GetImportBatchRangeDesc();
351
352     my @list = ();
353     foreach my $batch (@$batches) {
354         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ && $batch->{'record_type'} eq 'biblio') {
355             # check if there is at least 1 line still staged
356             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, 1, $batch->{import_status}, { order_by_direction => 'ASC' });
357             if (scalar @$stagedList) {
358                 push @list, {
359                         import_batch_id => $batch->{'import_batch_id'},
360                         num_records => $batch->{'num_records'},
361                         num_items => $batch->{'num_items'},
362                         staged_date => $batch->{'upload_timestamp'},
363                         import_status => $batch->{'import_status'},
364                         file_name => $batch->{'file_name'},
365                         comments => $batch->{'comments'},
366                 };
367             } else {
368                 # if there are no more line to includes, set the status to imported
369                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
370             }
371         }
372     }
373     $template->param(batch_list => \@list); 
374     my $num_batches = GetNumberOfNonZ3950ImportBatches();
375     $template->param(num_results => $num_batches);
376 }
377
378 sub import_biblios_list {
379     my ($template, $import_batch_id) = @_;
380     my $batch = GetImportBatch($import_batch_id,'staged');
381     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
382     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
383     my @list = ();
384
385     foreach my $biblio (@$biblios) {
386         my $citation = $biblio->{'title'};
387         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
388         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
389         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
390         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
391         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
392         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
393         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
394         my %cellrecord = (
395             import_record_id => $biblio->{'import_record_id'},
396             citation => $citation,
397             import  => 1,
398             status => $biblio->{'status'},
399             record_sequence => $biblio->{'record_sequence'},
400             overlay_status => $biblio->{'overlay_status'},
401             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
402             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
403             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
404         );
405         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
406         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
407         my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'discount', 'sort1', 'sort2']);
408         my $price = $infos->{price};
409         my $quantity = $infos->{quantity};
410         my $budget_code = $infos->{budget_code};
411         my $discount = $infos->{discount};
412         my $sort1 = $infos->{sort1};
413         my $sort2 = $infos->{sort2};
414         my $budget_id;
415         if($budget_code) {
416             my $biblio_budget = GetBudgetByCode($budget_code);
417             if($biblio_budget) {
418                 $budget_id = $biblio_budget->{budget_id};
419             }
420         }
421         $cellrecord{price} = $price || '';
422         $cellrecord{quantity} = $quantity || '';
423         $cellrecord{budget_id} = $budget_id || '';
424         $cellrecord{discount} = $discount || '';
425         $cellrecord{sort1} = $sort1 || '';
426         $cellrecord{sort2} = $sort2 || '';
427
428         push @list, \%cellrecord;
429     }
430     my $num_records = $batch->{'num_records'};
431     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
432     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
433     my $item_action = GetImportBatchItemAction($import_batch_id);
434     $template->param(biblio_list => \@list,
435                         num_results => $num_records,
436                         import_batch_id => $import_batch_id,
437                         "overlay_action_${overlay_action}" => 1,
438                         overlay_action => $overlay_action,
439                         "nomatch_action_${nomatch_action}" => 1,
440                         nomatch_action => $nomatch_action,
441                         "item_action_${item_action}" => 1,
442                         item_action => $item_action
443                     );
444     batch_info($template, $batch);
445 }
446
447 sub batch_info {
448     my ($template, $batch) = @_;
449     $template->param(batch_info => 1,
450                                       file_name => $batch->{'file_name'},
451                                           comments => $batch->{'comments'},
452                                           import_status => $batch->{'import_status'},
453                                           upload_timestamp => $batch->{'upload_timestamp'},
454                                           num_records => $batch->{'num_records'},
455                                           num_items => $batch->{'num_items'});
456     if ($batch->{'num_records'} > 0) {
457         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
458             $template->param(can_commit => 1);
459         }
460         if ($batch->{'import_status'} eq 'imported') {
461             $template->param(can_revert => 1);
462         }
463     }
464     if (defined $batch->{'matcher_id'}) {
465         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
466         if (defined $matcher) {
467             $template->param('current_matcher_id' => $batch->{'matcher_id'},
468                                               'current_matcher_code' => $matcher->code(),
469                                               'current_matcher_description' => $matcher->description());
470         }
471     }
472     add_matcher_list($batch->{'matcher_id'}, $template);
473 }
474
475 sub add_matcher_list {
476     my ($current_matcher_id, $template) = @_;
477     my @matchers = C4::Matcher::GetMatcherList();
478     if (defined $current_matcher_id) {
479         for (my $i = 0; $i <= $#matchers; $i++) {
480             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
481                 $matchers[$i]->{'selected'} = 1;
482             }
483         }
484     }
485     $template->param(available_matchers => \@matchers);
486 }
487
488 sub get_infos_syspref {
489     my ($record, $field_list) = @_;
490     my $syspref = C4::Context->preference('MarcFieldsToOrder');
491     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
492     my $yaml = eval {
493         YAML::Load($syspref);
494     };
495     if ( $@ ) {
496         warn "Unable to parse MarcFieldsToOrder syspref : $@";
497         return ();
498     }
499     my $r;
500     for my $field_name ( @$field_list ) {
501         next unless exists $yaml->{$field_name};
502         my @fields = split /\|/, $yaml->{$field_name};
503         for my $field ( @fields ) {
504             my ( $f, $sf ) = split /\$/, $field;
505             next unless $f and $sf;
506             if ( my $v = $record->subfield( $f, $sf ) ) {
507                 $r->{$field_name} = $v;
508             }
509             last if $yaml->{$field};
510         }
511     }
512     return $r;
513 }