Bug 7180: QA followup
[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 Modern::Perl;
25 use CGI;
26 use Carp;
27 use Number::Format qw(:all);
28 use YAML qw/Load/;
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, $userflags) = 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
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
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' ) {
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 = GetImportRecordsRange($import_batch_id);
159     my @import_record_id_selected = $input->param("import_record_id");
160     my @quantities = $input->param('quantity');
161     my @prices = $input->param('price');
162     my @budgets_id = $input->param('budget_id');
163     my @rrp = $input->param('rrp');
164     my @discount = $input->param('discount');
165     my @sort1 = $input->param('sort1');
166     my @sort2 = $input->param('sort2');
167     my $cur = GetCurrency();
168     for my $biblio (@$biblios){
169         # Check if this import_record_id was selected
170         next if not grep { $_ eq $$biblio{import_record_id} } @import_record_id_selected;
171         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
172         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
173         my $match = GetImportRecordMatches( $biblio->{'import_record_id'}, 1 );
174         my $biblionumber=$#$match > -1?$match->[0]->{'biblionumber'}:0;
175         my $c_quantity = shift( @quantities ) || GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour') ) || 1;
176         my $c_budget_id = shift( @budgets_id ) || $input->param('all_budget_id') || $budget_id;
177         my $c_rrp = shift( @rrp ); # rrp include tax
178         my $c_discount = shift ( @discount);
179         $c_discount = $c_discount / 100 if $c_discount > 100;
180         my $c_sort1 = shift( @sort1 ) || $input->param('all_sort1') || '';
181         my $c_sort2 = shift( @sort2 ) || $input->param('all_sort2') || '';
182
183         # 1st insert the biblio, or find it through matcher
184         unless ( $biblionumber ) {
185             # add the biblio
186             my $bibitemnum;
187
188             # remove ISBN -
189             my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField( 'biblioitems.isbn', '' );
190             if ( $marcrecord->field($isbnfield) ) {
191                 foreach my $field ( $marcrecord->field($isbnfield) ) {
192                     foreach my $subfield ( $field->subfield($isbnsubfield) ) {
193                         my $newisbn = $field->subfield($isbnsubfield);
194                         $newisbn =~ s/-//g;
195                         $field->update( $isbnsubfield => $newisbn );
196                     }
197                 }
198             }
199             ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
200             # 2nd add authorities if applicable
201             if (C4::Context->preference("BiblioAddsAuthorities")){
202                 my $headings_linked =BiblioAutoLink($marcrecord, $cgiparams->{'frameworkcode'});
203             }
204         } else {
205             SetImportRecordStatus( $biblio->{'import_record_id'}, 'imported' );
206         }
207         # 3rd add order
208         my $patron = C4::Members::GetMember( borrowernumber => $loggedinuser );
209         my $branch = C4::Branch->GetBranchDetail( $patron->{branchcode} );
210         # get quantity in the MARC record (1 if none)
211         my $quantity = GetMarcQuantity($marcrecord, C4::Context->preference('marcflavour')) || 1;
212         my %orderinfo = (
213             biblionumber       => $biblionumber,
214             basketno           => $cgiparams->{'basketno'},
215             quantity           => $c_quantity,
216             branchcode         => $patron->{branchcode},
217             budget_id          => $c_budget_id,
218             uncertainprice     => 1,
219             sort1              => $c_sort1,
220             sort2              => $c_sort2,
221             order_internalnote => $cgiparams->{'all_order_internalnote'},
222             order_vendornote   => $cgiparams->{'all_order_vendornote'},
223             currency           => $cgiparams->{'all_currency'},
224         );
225         # get the price if there is one.
226         my $price= shift( @prices ) || GetMarcPrice($marcrecord, C4::Context->preference('marcflavour'));
227         if ($price){
228             # in France, the cents separator is the , but sometimes, ppl use a .
229             # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation
230             $price =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR";
231             $price = $num->unformat_number($price);
232             $orderinfo{gstrate} = $bookseller->{gstrate};
233             my $c = $c_discount ? $c_discount / 100 : $bookseller->{discount} / 100;
234             if ( $bookseller->{listincgst} ) {
235                 if ( $c_discount ) {
236                     $orderinfo{ecost} = $price;
237                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
238                 } else {
239                     $orderinfo{ecost} = $price * ( 1 - $c );
240                     $orderinfo{rrp}   = $price;
241                 }
242             } else {
243                 if ( $c_discount ) {
244                     $orderinfo{ecost} = $price / ( 1 + $orderinfo{gstrate} );
245                     $orderinfo{rrp}   = $orderinfo{ecost} / ( 1 - $c );
246                 } else {
247                     $orderinfo{rrp}   = $price / ( 1 + $orderinfo{gstrate} );
248                     $orderinfo{ecost} = $orderinfo{rrp} * ( 1 - $c );
249                 }
250             }
251             $orderinfo{listprice} = $orderinfo{rrp} / $cur->{rate};
252             $orderinfo{unitprice} = $orderinfo{ecost};
253             $orderinfo{total} = $orderinfo{ecost} * $c_quantity;
254         } else {
255             $orderinfo{listprice} = 0;
256         }
257
258         # remove uncertainprice flag if we have found a price in the MARC record
259         $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
260         my ( $basketno, $ordernumber ) = NewOrder( \%orderinfo );
261
262         # 4th, add items if applicable
263         # parse the item sent by the form, and create an item just for the import_record_id we are dealing with
264         # this is not optimised, but it's working !
265         if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) {
266             my @tags         = $input->param('tag');
267             my @subfields    = $input->param('subfield');
268             my @field_values = $input->param('field_value');
269             my @serials      = $input->param('serial');
270             my @ind_tag   = $input->param('ind_tag');
271             my @indicator = $input->param('indicator');
272             my $item;
273             push @{ $item->{tags} },         $tags[0];
274             push @{ $item->{subfields} },    $subfields[0];
275             push @{ $item->{field_values} }, $field_values[0];
276             push @{ $item->{ind_tag} },      $ind_tag[0];
277             push @{ $item->{indicator} },    $indicator[0];
278             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values, \@ind_tag, \@indicator );
279             my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' );
280             for (my $qtyloop=1;$qtyloop <= $c_quantity;$qtyloop++) {
281                 my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber );
282                 NewOrderItem( $itemnumber, $ordernumber );
283             }
284         }
285     }
286     # go to basket page
287     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
288     exit;
289 }
290
291 my $budgets = GetBudgets();
292 my $budget_id = @$budgets[0]->{'budget_id'};
293 # build bookfund list
294 my $borrower = GetMember( 'borrowernumber' => $loggedinuser );
295 my ( $flags, $homebranch ) = ( $borrower->{'flags'}, $borrower->{'branchcode'} );
296 my $budget = GetBudget($budget_id);
297
298 # build budget list
299 my $budget_loop = [];
300 my $budgets_hierarchy = GetBudgetHierarchy;
301 foreach my $r ( @{$budgets_hierarchy} ) {
302     next unless (CanUserUseBudget($borrower, $r, $userflags));
303     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
304         next;
305     }
306     push @{$budget_loop},
307       { b_id  => $r->{budget_id},
308         b_txt => $r->{budget_name},
309         b_sort1_authcat => $r->{'sort1_authcat'},
310         b_sort2_authcat => $r->{'sort2_authcat'},
311         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
312       };
313 }
314 $template->param( budget_loop    => $budget_loop,);
315
316 my $CGIsort1;
317 if ($budget) {    # its a mod ..
318     if ( defined $budget->{'sort1_authcat'} ) {    # with custom  Asort* planning values
319         $CGIsort1 = GetAuthvalueDropbox(  $budget->{'sort1_authcat'}, $data->{'sort1'} );
320     }
321 } elsif ( scalar(@$budgets) ) {
322 } elsif ( scalar(@$budgets_hierarchy) ) {
323     $CGIsort1 = GetAuthvalueDropbox( @$budgets_hierarchy[0]->{'sort1_authcat'}, '' );
324 }
325 # if CGIsort is successfully fetched, the use it
326 # else - failback to plain input-field
327 if ($CGIsort1) {
328     $template->param( CGIsort1 => $CGIsort1 );
329 } else {
330     $template->param( sort1 => $data->{'sort1'} );
331 }
332
333 my $CGIsort2;
334 if ($budget) {
335     if ( defined $budget->{'sort2_authcat'} ) {
336         $CGIsort2 = GetAuthvalueDropbox(  $budget->{'sort2_authcat'}, $data->{'sort2'} );
337     }
338 } elsif ( scalar(@$budgets_hierarchy) ) {
339     $CGIsort2 = GetAuthvalueDropbox( @$budgets_hierarchy[0]->{sort2_authcat}, '' );
340 }
341 if ($CGIsort2) {
342     $template->param( CGIsort2 => $CGIsort2 );
343 } else {
344     $template->param( sort2 => $data->{'sort2'} );
345 }
346
347 output_html_with_http_headers $input, $cookie, $template->output;
348
349
350 sub import_batches_list {
351     my ($template) = @_;
352     my $batches = GetImportBatchRangeDesc();
353
354     my @list = ();
355     foreach my $batch (@$batches) {
356         if ( $batch->{'import_status'} =~ /^staged$|^reverted$/ ) {
357             # check if there is at least 1 line still staged
358             my $stagedList=GetImportRecordsRange($batch->{'import_batch_id'}, undef, undef, $batch->{import_status});
359             if (scalar @$stagedList) {
360                 push @list, {
361                         import_batch_id => $batch->{'import_batch_id'},
362                         num_biblios => $batch->{'num_biblios'},
363                         num_items => $batch->{'num_items'},
364                         staged_date => $batch->{'upload_timestamp'},
365                         import_status => $batch->{'import_status'},
366                         file_name => $batch->{'file_name'},
367                         comments => $batch->{'comments'},
368                 };
369             } else {
370                 # if there are no more line to includes, set the status to imported
371                 SetImportBatchStatus( $batch->{'import_batch_id'}, 'imported' );
372             }
373         }
374     }
375     $template->param(batch_list => \@list); 
376     my $num_batches = GetNumberOfNonZ3950ImportBatches();
377     $template->param(num_results => $num_batches);
378 }
379
380 sub import_biblios_list {
381     my ($template, $import_batch_id) = @_;
382     my $batch = GetImportBatch($import_batch_id,'staged');
383     return () unless $batch and $batch->{import_status} =~ /^staged$|^reverted$/;
384     my $biblios = GetImportRecordsRange($import_batch_id,'','',$batch->{import_status});
385     my @list = ();
386
387     foreach my $biblio (@$biblios) {
388         my $citation = $biblio->{'title'};
389         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
390         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
391         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
392         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
393         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
394         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
395         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
396         my %cellrecord = (
397             import_record_id => $biblio->{'import_record_id'},
398             citation => $citation,
399             import  => 1,
400             status => $biblio->{'status'},
401             record_sequence => $biblio->{'record_sequence'},
402             overlay_status => $biblio->{'overlay_status'},
403             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
404             match_citation     => $#$match > -1 ? $match->[0]->{'title'} || '' . ' ' . $match->[0]->{'author'} || '': '',
405             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
406         );
407         my ( $marcblob, $encoding ) = GetImportRecordMarc( $biblio->{'import_record_id'} );
408         my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
409         my $infos = get_infos_syspref($marcrecord, ['price', 'quantity', 'budget_code', 'rrp', 'discount', 'sort1', 'sort2']);
410         my $price = $infos->{price};
411         my $quantity = $infos->{quantity};
412         my $budget_code = $infos->{budget_code};
413         my $rrp = $infos->{rrp};
414         my $discount = $infos->{discount};
415         my $sort1 = $infos->{sort1};
416         my $sort2 = $infos->{sort2};
417         my $budget_id;
418         if($budget_code) {
419             my $biblio_budget = GetBudgetByCode($budget_code);
420             if($biblio_budget) {
421                 $budget_id = $biblio_budget->{budget_id};
422             }
423         }
424         $cellrecord{price} = $price || '';
425         $cellrecord{quantity} = $quantity || '';
426         $cellrecord{budget_id} = $budget_id || '';
427         $cellrecord{rrp} = $rrp || '';
428         $cellrecord{discount} = $discount || '';
429         $cellrecord{sort1} = $sort1 || '';
430         $cellrecord{sort2} = $sort2 || '';
431
432         push @list, \%cellrecord;
433     }
434     my $num_biblios = $batch->{'num_biblios'};
435     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
436     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
437     my $item_action = GetImportBatchItemAction($import_batch_id);
438     $template->param(biblio_list => \@list,
439                         num_results => $num_biblios,
440                         import_batch_id => $import_batch_id,
441                         "overlay_action_${overlay_action}" => 1,
442                         overlay_action => $overlay_action,
443                         "nomatch_action_${nomatch_action}" => 1,
444                         nomatch_action => $nomatch_action,
445                         "item_action_${item_action}" => 1,
446                         item_action => $item_action
447                     );
448     batch_info($template, $batch);
449 }
450
451 sub batch_info {
452     my ($template, $batch) = @_;
453     $template->param(batch_info => 1,
454                                       file_name => $batch->{'file_name'},
455                                           comments => $batch->{'comments'},
456                                           import_status => $batch->{'import_status'},
457                                           upload_timestamp => $batch->{'upload_timestamp'},
458                                           num_biblios => $batch->{'num_biblios'},
459                                           num_items => $batch->{'num_biblios'});
460     if ($batch->{'num_biblios'} > 0) {
461         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
462             $template->param(can_commit => 1);
463         }
464         if ($batch->{'import_status'} eq 'imported') {
465             $template->param(can_revert => 1);
466         }
467     }
468     if (defined $batch->{'matcher_id'}) {
469         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
470         if (defined $matcher) {
471             $template->param('current_matcher_id' => $batch->{'matcher_id'},
472                                               'current_matcher_code' => $matcher->code(),
473                                               'current_matcher_description' => $matcher->description());
474         }
475     }
476     add_matcher_list($batch->{'matcher_id'}, $template);
477 }
478
479 sub add_matcher_list {
480     my ($current_matcher_id, $template) = @_;
481     my @matchers = C4::Matcher::GetMatcherList();
482     if (defined $current_matcher_id) {
483         for (my $i = 0; $i <= $#matchers; $i++) {
484             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
485                 $matchers[$i]->{'selected'} = 1;
486             }
487         }
488     }
489     $template->param(available_matchers => \@matchers);
490 }
491
492 sub get_infos_syspref {
493     my ($record, $field_list) = @_;
494     my $syspref = C4::Context->preference('MarcFieldsToOrder');
495     $syspref = "$syspref\n\n"; # YAML is anal on ending \n. Surplus does not hurt
496     my $yaml = eval {
497         YAML::Load($syspref);
498     };
499     if ( $@ ) {
500         warn "Unable to parse MarcFieldsToOrder syspref : $@";
501         return ();
502     }
503     my $r;
504     for my $field_name ( @$field_list ) {
505         next unless exists $yaml->{$field_name};
506         my @fields = split /\|/, $yaml->{$field_name};
507         for my $field ( @fields ) {
508             my ( $f, $sf ) = split /\$/, $field;
509             next unless $f and $sf;
510             if ( my $v = $record->subfield( $f, $sf ) ) {
511                 $r->{$field_name} = $v;
512             }
513             last if $yaml->{$field};
514         }
515     }
516     return $r;
517 }