Merge remote branch 'kc/new/bug_5240' into kcmaster
[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 #written by john.soros@biblibre.com 01/12/2008
7
8 # Copyright 2008 - 2009 BibLibre SARL
9 #
10 # This file is part of Koha.
11 #
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
16 #
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along
22 # with Koha; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25 use strict;
26 use warnings;
27 use CGI;
28 use C4::Context;
29 use C4::Auth;
30 use C4::Input;
31 use C4::Output;
32 use C4::ImportBatch qw/GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches GetImportRecordMatches GetImportBibliosRange GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction GetImportRecordMarc GetImportBatch/;
33 use C4::Matcher;
34 use C4::Search qw/FindDuplicate BiblioAddAuthorities/;
35 use C4::Acquisition qw/NewOrder/;
36 use C4::Biblio;
37 use C4::Items;
38 use C4::Koha qw/GetItemTypes/;
39 use C4::Budgets qw/GetBudgets/;
40 use C4::Acquisition qw/NewOrderItem/;
41 use C4::Bookseller qw/GetBookSellerFromId/;
42
43 my $input = new CGI;
44 my ($template, $loggedinuser, $cookie) = get_template_and_user({
45                                         template_name => "acqui/addorderiso2709.tmpl",
46                                         query => $input,
47                                         type => "intranet",
48                                         authnotrequired => 0,
49                                         flagsrequired   => { acquisition => 'order_manage' },
50                                         debug => 1,
51                                         });
52 my $cgiparams = $input->Vars;
53 my $op = $cgiparams->{'op'};
54 my $booksellerid  = $input->param('booksellerid');
55 my $bookseller = GetBookSellerFromId($booksellerid);
56
57 $template->param(scriptname => "/cgi-bin/koha/acqui/addorderiso2709.pl",
58                 booksellerid => $booksellerid,
59                 booksellername => $bookseller->{name},
60                 );
61 my $ordernumber;
62
63 if ($cgiparams->{'import_batch_id'} && $op eq ""){
64     $op = "batch_details";
65 }
66
67 #Needed parameters:
68 if (! $cgiparams->{'basketno'}){
69     die "Basketnumber required to order from iso2709 file import";
70 }
71
72 if ($op eq ""){
73     $template->param("basketno" => $cgiparams->{'basketno'});
74 #display batches
75     import_batches_list($template);
76 } elsif ($op eq "batch_details"){
77 #display lines inside the selected batch
78     $template->param("batch_details" => 1,
79                      "basketno"      => $cgiparams->{'basketno'});
80     import_biblios_list($template, $cgiparams->{'import_batch_id'});
81     
82 } elsif ($op eq 'import_records'){
83 #import selected lines
84     $template->param('basketno' => $cgiparams->{'basketno'});
85 # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards
86     my $budgets = GetBudgets();
87     if (scalar @$budgets == 0){
88         die "No budgets defined, can't continue";
89     }
90     my $budget_id = @$budgets[0]->{'budget_id'};
91 #get all records from a batch, and check their import status to see if they are checked.
92 #(default values: quantity 1, uncertainprice yes, first budget)
93
94     # retrieve the file you want to import
95     my $import_batch_id = $cgiparams->{'import_batch_id'};
96     my $biblios = GetImportBibliosRange($import_batch_id);
97     for my $biblio (@$biblios){
98         if($cgiparams->{'order-'.$biblio->{'import_record_id'}}){
99             my ($marcblob, $encoding) = GetImportRecordMarc($biblio->{'import_record_id'});
100             my $marcrecord = MARC::Record->new_from_usmarc($marcblob) || die "couldn't translate marc information";
101             my ($duplicatetitle, $biblionumber);
102             if(!(($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord))){
103 #FIXME: missing: marc21 support (should be same with different field)
104                 if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) {
105                     my $itemtypeid = "itemtype-" . $biblio->{'import_record_id'};
106                     $marcrecord->field(200)->update("b" => $cgiparams->{$itemtypeid});
107                 }
108                 # add the biblio
109                 my $bibitemnum;
110                 # remove ISBN -
111                 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
112                 if ( $marcrecord->field($isbnfield) ) {
113                     foreach my $field ( $marcrecord->field($isbnfield) ) {
114                         foreach my $subfield ( $field->subfield($isbnsubfield) ) {
115                             my $newisbn = $field->subfield($isbnsubfield);
116                             $newisbn =~ s/-//g;
117                             $field->update( $isbnsubfield => $newisbn );
118                         }
119                     }
120                 }
121
122                 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $cgiparams->{'frameworkcode'} || '' );
123             } else {
124                 warn("Duplicate item found: ", $biblionumber, "; Duplicate: ", $duplicatetitle);
125             }
126             if (C4::Context->preference("BiblioAddsAuthorities")){
127                 my ($countlinked,$countcreated)=BiblioAddAuthorities($marcrecord, $cgiparams->{'frameworkcode'});
128             }
129             my $patron = C4::Members->GetMember(borrowernumber => $loggedinuser);
130             my $branch = C4::Branch->GetBranchDetail($patron->{branchcode});
131             my ($invoice);
132             my %orderinfo = ("biblionumber", $biblionumber,
133                             "basketno", $cgiparams->{'basketno'},
134                             "quantity", $cgiparams->{'quantityrec-' . $biblio->{'import_record_id'}},
135                             "branchcode", $branch,
136                             "booksellerinvoicenumber", $invoice,
137                             "budget_id", $budget_id,
138                             "uncertainprice", 1,
139                             );
140             # get the price if there is one.
141             # filter by storing only the 1st number
142             # we suppose the currency is correct, as we have no possibilities to get it.
143             if ($marcrecord->subfield("345","d")) {
144               $orderinfo{'listprice'} = $marcrecord->subfield("345","d");
145               if ($orderinfo{'listprice'} =~ /^([\d\.,]*)/) {
146                   $orderinfo{'listprice'} = $1;
147                   $orderinfo{'listprice'} =~ s/,/\./;
148                   eval "use C4::Acquisition qw/GetBasket/;";
149                   eval "use C4::Bookseller qw/GetBookSellerFromId/;";
150                   my $basket = GetBasket($orderinfo{basketno});
151                   my $bookseller = GetBookSellerFromId($basket->{booksellerid});
152                   # '//' is like '||' but tests for defined, rather than true
153                   my $gst = $bookseller->{gstrate} // C4::Context->preference("gist") // 0;
154                   $orderinfo{'unitprice'} = $orderinfo{listprice} - ($orderinfo{listprice} * ($bookseller->{discount} / 100));
155                   $orderinfo{'ecost'} = $orderinfo{unitprice};
156               } else {
157                   $orderinfo{'listprice'} = 0;
158               }
159               $orderinfo{'rrp'} = $orderinfo{'listprice'};
160             }
161             elsif ($marcrecord->subfield("010","d")) {
162               $orderinfo{'listprice'} = $marcrecord->subfield("010","d");
163               if ($orderinfo{'listprice'} =~ /^([\d\.,]*)/) {
164                   $orderinfo{'listprice'} = $1;
165                   $orderinfo{'listprice'} =~ s/,/\./;
166                   eval "use C4::Acquisition qw/GetBasket/;";
167                   eval "use C4::Bookseller qw/GetBookSellerFromId/;";
168                   my $basket = GetBasket($orderinfo{basketno});
169                   my $bookseller = GetBookSellerFromId($basket->{booksellerid});
170                   my $gst = $bookseller->{gstrate} // C4::Context->preference("gist") // 0;
171                   $orderinfo{'unitprice'} = $orderinfo{listprice} - ($orderinfo{listprice} * ($bookseller->{discount} / 100));
172                   $orderinfo{'ecost'} = $orderinfo{unitprice};
173               } else {
174                   $orderinfo{'listprice'} = 0;
175               }
176               $orderinfo{'rrp'} = $orderinfo{'listprice'};
177             }
178             # remove uncertainprice flag if we have found a price in the MARC record
179             $orderinfo{uncertainprice} = 0 if $orderinfo{listprice};
180             my $basketno;
181             ( $basketno, $ordernumber ) = NewOrder(\%orderinfo);
182
183             # now, add items if applicable
184             # parse all items sent by the form, and create an item just for the import_record_id we are dealing with
185             # this is not optimised, but it's working !
186             if (C4::Context->preference('AcqCreateItem') eq 'ordering') {
187                 my @tags         = $input->param('tag');
188                 my @subfields    = $input->param('subfield');
189                 my @field_values = $input->param('field_value');
190                 my @serials      = $input->param('serial');
191                 my @itemids       = $input->param('itemid'); # hint : in iso2709, the itemid contains the import_record_id, not an item id. It is used to get the right item, as we have X biblios.
192                 my @ind_tag      = $input->param('ind_tag');
193                 my @indicator    = $input->param('indicator');
194                 #Rebuilding ALL the data for items into a hash
195                 # parting them on $itemid.
196                 my %itemhash;
197                 my $range=scalar(@itemids);
198                 
199                 my $i = 0;
200                 my @items;
201                 for my $itemid (@itemids){
202                     my $realitemid;     #javascript generated random itemids, in the form itemid-randomnumber, $realitemid is the itemid, while $itemid is the itemide parsed from the html
203                     if ($itemid =~ m/(\d+)-.*/){
204                         my @splits = split(/-/, $itemid);
205                         $realitemid = $splits[0];
206                     }
207                     if ( ( $realitemid && $cgiparams->{'order-'. $realitemid} && $realitemid eq $biblio->{import_record_id}) || ($itemid && $cgiparams->{'order-'. $itemid} && $itemid eq $biblio->{import_record_id}) ){
208                         my ($item, $found);
209                         for my $tmpitem (@items){
210                             if ($tmpitem->{itemid} eq $itemid){
211                                 $item = $tmpitem;
212                                 $found = 1;
213                             }
214                         }
215                         push @{$item->{tags}}, $tags[$i];
216                         push @{$item->{subfields}}, $subfields[$i];
217                         push @{$item->{field_values}}, $field_values[$i];
218                         push @{$item->{ind_tag}}, $ind_tag[$i];
219                         push @{$item->{indicator}}, $indicator[$i];
220                         $item->{itemid} = $itemid;
221                         if (! $found){
222                              push @items, $item;
223                         }
224                     }
225                     ++$i
226                 }
227                 foreach my $item (@items){
228                         my $xml = TransformHtmlToXml( $item->{'tags'},
229                                                 $item->{'subfields'},
230                                                 $item->{'field_values'},
231                                                 $item->{'ind_tag'},
232                                                 $item->{'indicator'});
233                         my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
234                         my ($biblionumber,$bibitemnum,$itemnumber) = AddItemFromMarc($record,$biblionumber);
235                         NewOrderItem( $itemnumber, $ordernumber);
236                 }
237             }
238         }
239     }
240     # go to basket page
241     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=".$cgiparams->{'basketno'});
242     exit;
243 }
244 output_html_with_http_headers $input, $cookie, $template->output;
245
246
247 sub import_batches_list {
248     my ($template) = @_;
249     my $batches = GetImportBatchRangeDesc();
250
251     my @list = ();
252     foreach my $batch (@$batches) {
253         if ($batch->{'import_status'} eq "staged") {
254         push @list, {
255                 import_batch_id => $batch->{'import_batch_id'},
256                 num_biblios => $batch->{'num_biblios'},
257                 num_items => $batch->{'num_items'},
258                 upload_timestamp => $batch->{'upload_timestamp'},
259                 import_status => $batch->{'import_status'},
260                 file_name => $batch->{'file_name'},
261                 comments => $batch->{'comments'},
262             };
263         }
264     }
265     $template->param(batch_list => \@list); 
266     my $num_batches = GetNumberOfNonZ3950ImportBatches();
267     $template->param(num_results => $num_batches);
268 }
269
270 sub import_biblios_list {
271     my ($template, $import_batch_id) = @_;
272     my $batch = GetImportBatch($import_batch_id,'staged');
273     my $biblios = GetImportBibliosRange($import_batch_id,'','','staged');
274     my @list = ();
275 # # Itemtype is mandatory for adding a biblioitem, we just add a default, the user needs to modify this aftewards
276 #     my $itemtypehash = GetItemTypes();
277 #     my @itemtypes;
278 #     for my $key (sort { $itemtypehash->{$a}->{description} cmp $itemtypehash->{$b}->{description} } keys %$itemtypehash) {
279 #         push(@itemtypes, $itemtypehash->{$key});
280 #     }
281     foreach my $biblio (@$biblios) {
282         my $citation = $biblio->{'title'};
283         $citation .= " $biblio->{'author'}" if $biblio->{'author'};
284         $citation .= " (" if $biblio->{'issn'} or $biblio->{'isbn'};
285         $citation .= $biblio->{'isbn'} if $biblio->{'isbn'};
286         $citation .= ", " if $biblio->{'issn'} and $biblio->{'isbn'};
287         $citation .= $biblio->{'issn'} if $biblio->{'issn'};
288         $citation .= ")" if $biblio->{'issn'} or $biblio->{'isbn'};
289         my $match = GetImportRecordMatches($biblio->{'import_record_id'}, 1);
290         my %cellrecord = (
291             import_record_id => $biblio->{'import_record_id'},
292             citation => $citation,
293             import  => 1,
294             status => $biblio->{'status'},
295             record_sequence => $biblio->{'record_sequence'},
296             overlay_status => $biblio->{'overlay_status'},
297             match_biblionumber => $#$match > -1 ? $match->[0]->{'biblionumber'} : 0,
298             match_citation => $#$match > -1 ? $match->[0]->{'title'} . ' ' . $match->[0]->{'author'} : '',
299             match_score => $#$match > -1 ? $match->[0]->{'score'} : 0,
300 #             itemtypes => \@itemtypes,
301         );
302 #         if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
303 #             # prepare empty item form
304 #             my $cell = PrepareItemrecordDisplay();
305 #             my @itemloop;
306 #             push @itemloop,$cell;
307 #             $cellrecord{'items'} = \@itemloop;
308 #         }
309         push @list, \%cellrecord;
310
311
312     }
313     my $num_biblios = $batch->{'num_biblios'};
314     my $overlay_action = GetImportBatchOverlayAction($import_batch_id);
315     my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id);
316     my $item_action = GetImportBatchItemAction($import_batch_id);
317     $template->param(biblio_list => \@list,
318                         num_results => $num_biblios,
319                         import_batch_id => $import_batch_id,
320                         "overlay_action_${overlay_action}" => 1,
321                         overlay_action => $overlay_action,
322                         "nomatch_action_${nomatch_action}" => 1,
323                         nomatch_action => $nomatch_action,
324                         "item_action_${item_action}" => 1,
325                         item_action => $item_action
326                     );
327     batch_info($template, $batch);
328 }
329
330 sub batch_info {
331     my ($template, $batch) = @_;
332     $template->param(batch_info => 1,
333                                       file_name => $batch->{'file_name'},
334                                           comments => $batch->{'comments'},
335                                           import_status => $batch->{'import_status'},
336                                           upload_timestamp => $batch->{'upload_timestamp'},
337                                           num_biblios => $batch->{'num_biblios'},
338                                           num_items => $batch->{'num_biblios'});
339     if ($batch->{'num_biblios'} > 0) {
340         if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') {
341             $template->param(can_commit => 1);
342         }
343         if ($batch->{'import_status'} eq 'imported') {
344             $template->param(can_revert => 1);
345         }
346     }
347     if (defined $batch->{'matcher_id'}) {
348         my $matcher = C4::Matcher->fetch($batch->{'matcher_id'});
349         if (defined $matcher) {
350             $template->param('current_matcher_id' => $batch->{'matcher_id'},
351                                               'current_matcher_code' => $matcher->code(),
352                                               'current_matcher_description' => $matcher->description());
353         }
354     }
355     add_matcher_list($batch->{'matcher_id'});
356 }
357
358 sub add_matcher_list {
359     my $current_matcher_id = shift;
360     my @matchers = C4::Matcher::GetMatcherList();
361     if (defined $current_matcher_id) {
362         for (my $i = 0; $i <= $#matchers; $i++) {
363             if ($matchers[$i]->{'matcher_id'} == $current_matcher_id) {
364                 $matchers[$i]->{'selected'} = 1;
365             }
366         }
367     }
368     $template->param(available_matchers => \@matchers);
369 }