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