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