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