Bug 15758: Koha::Libraries - Remove GetBranchesLoop
[koha.git] / acqui / neworderempty.pl
1 #!/usr/bin/perl
2
3 #script to show display basket of orders
4 #written by chris@katipo.co.nz 24/2/2000
5
6 # Copyright 2000-2002 Katipo Communications
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22
23
24 =head1 NAME
25
26 neworderempty.pl
27
28 =head1 DESCRIPTION
29
30 this script allows to create a new record to order it. This record shouldn't exist
31 on database.
32
33 =head1 CGI PARAMETERS
34
35 =over 4
36
37 =item booksellerid
38 the bookseller the librarian has to buy a new book.
39
40 =item title
41 the title of this new record.
42
43 =item author
44 the author of this new record.
45
46 =item publication year
47 the publication year of this new record.
48
49 =item ordernumber
50 the number of this order.
51
52 =item biblio
53
54 =item basketno
55 the basket number for this new order.
56
57 =item suggestionid
58 if this order comes from a suggestion.
59
60 =item breedingid
61 the item's id in the breeding reservoir
62
63 =item close
64
65 =back
66
67 =cut
68
69 use warnings;
70 use strict;
71 use CGI qw ( -utf8 );
72 use C4::Context;
73
74 use C4::Auth;
75 use C4::Budgets;
76
77 use C4::Acquisition;
78 use C4::Contract;
79 use C4::Suggestions;    # GetSuggestion
80 use C4::Biblio;                 # GetBiblioData GetMarcPrice
81 use C4::Items; #PrepareItemRecord
82 use C4::Output;
83 use C4::Koha;
84 use C4::Branch;                 # GetBranches
85 use C4::Members;
86 use C4::Search qw/FindDuplicate/;
87
88 #needed for z3950 import:
89 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
90
91 use Koha::Acquisition::Bookseller;
92 use Koha::Acquisition::Currencies;
93 use Koha::ItemTypes;
94
95 our $input           = new CGI;
96 my $booksellerid    = $input->param('booksellerid');    # FIXME: else ERROR!
97 my $budget_id       = $input->param('budget_id') || 0;
98 my $title           = $input->param('title');
99 my $author          = $input->param('author');
100 my $publicationyear = $input->param('publicationyear');
101 my $ordernumber          = $input->param('ordernumber') || '';
102 our $biblionumber    = $input->param('biblionumber');
103 our $basketno        = $input->param('basketno');
104 my $suggestionid    = $input->param('suggestionid');
105 my $close           = $input->param('close');
106 my $uncertainprice  = $input->param('uncertainprice');
107 my $import_batch_id = $input->param('import_batch_id'); # if this is filled, we come from a staged file, and we will return here after saving the order !
108 my $subscriptionid  = $input->param('subscriptionid');
109 my $data;
110 my $new = 'no';
111
112 my $budget_name;
113
114 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
115     {
116         template_name   => "acqui/neworderempty.tt",
117         query           => $input,
118         type            => "intranet",
119         authnotrequired => 0,
120         flagsrequired   => { acquisition => 'order_manage' },
121         debug           => 1,
122     }
123 );
124
125 our $marcflavour = C4::Context->preference('marcflavour');
126
127 if(!$basketno) {
128     my $order = GetOrder($ordernumber);
129     $basketno = $order->{'basketno'};
130 }
131
132 our $basket = GetBasket($basketno);
133 $booksellerid = $basket->{booksellerid} unless $booksellerid;
134 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
135
136 my $contract = GetContract({
137     contractnumber => $basket->{contractnumber}
138 });
139
140 #simple parameters reading (all in one :-)
141 our $params = $input->Vars;
142 my $listprice=0; # the price, that can be in MARC record if we have one
143 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
144 #we want to import from the breeding reservoir (from a z3950 search)
145     my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
146     die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
147
148     # Remove all the items (952) from the imported record
149     foreach my $item ($marcrecord->field('952')) {
150         $marcrecord->delete_field($item);
151     }
152
153     my $duplicatetitle;
154 #look for duplicates
155     ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
156     if($biblionumber && !$input->param('use_external_source')) {
157         #if duplicate record found and user did not decide yet, first warn user
158         #and let him choose between using new record or existing record
159         Load_Duplicate($duplicatetitle);
160         exit;
161     }
162     #from this point: add a new record
163         if (C4::Context->preference("BiblioAddsAuthorities")){
164             my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
165         }
166         my $bibitemnum;
167         $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
168         ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
169         # get the price if there is one.
170         $listprice = GetMarcPrice($marcrecord, $marcflavour);
171         SetImportRecordStatus($params->{'breedingid'}, 'imported');
172 }
173
174
175
176 my ( @order_user_ids, @order_users );
177 if ( $ordernumber eq '' ) {    # create order
178     $new = 'yes';
179
180     #   $ordernumber=newordernum;
181     if ( $biblionumber && !$suggestionid ) {
182         $data = GetBiblioData($biblionumber);
183     }
184
185 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
186 # otherwise, retrieve suggestion information.
187     if ($suggestionid) {
188         $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
189         $budget_id ||= $data->{'budgetid'} // 0;
190     }
191 }
192 else {    #modify order
193     $data   = GetOrder($ordernumber);
194     $biblionumber = $data->{'biblionumber'};
195     $budget_id = $data->{'budget_id'};
196
197     $basket   = GetBasket( $data->{'basketno'} );
198     $basketno = $basket->{'basketno'};
199
200     @order_user_ids = GetOrderUsers($ordernumber);
201     foreach my $order_user_id (@order_user_ids) {
202         my $order_user = GetMember(borrowernumber => $order_user_id);
203         push @order_users, $order_user if $order_user;
204     }
205 }
206
207 my $suggestion;
208 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
209
210 my @currencies = Koha::Acquisition::Currencies->search;
211 my $active_currency = Koha::Acquisition::Currencies->get_active;
212
213 # build bookfund list
214 my $borrower= GetMember('borrowernumber' => $loggedinuser);
215 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
216
217 my $budget =  GetBudget($budget_id);
218 # build budget list
219 my $budget_loop = [];
220 my $budgets = GetBudgetHierarchy;
221 foreach my $r (@{$budgets}) {
222     next unless (CanUserUseBudget($borrower, $r, $userflags));
223     if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
224         next;
225     }
226     push @{$budget_loop}, {
227         b_id  => $r->{budget_id},
228         b_txt => $r->{budget_name},
229         b_sort1_authcat => $r->{'sort1_authcat'},
230         b_sort2_authcat => $r->{'sort2_authcat'},
231         b_active => $r->{budget_period_active},
232         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
233     };
234 }
235
236 @{$budget_loop} =
237   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
238
239 if ($close) {
240     $budget_id      =  $data->{'budget_id'};
241     $budget_name    =   $budget->{'budget_name'};
242
243 }
244
245 $template->param( sort1 => $data->{'sort1'} );
246 $template->param( sort2 => $data->{'sort2'} );
247
248 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
249     # Check if ACQ framework exists
250     my $marc = GetMarcStructure(1, 'ACQ');
251     unless($marc) {
252         $template->param('NoACQframework' => 1);
253     }
254     $template->param(
255         AcqCreateItemOrdering => 1,
256         UniqueItemFields => C4::Context->preference('UniqueItemFields'),
257     );
258 }
259 # Get the item types list, but only if item_level_itype is YES. Otherwise, it will be in the item, no need to display it in the biblio
260 my @itemtypes;
261 @itemtypes = Koha::ItemTypes->search unless C4::Context->preference('item-level_itypes');
262
263 if ( defined $subscriptionid ) {
264     my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
265     if ( defined $lastOrderReceived ) {
266         $budget_id              = $lastOrderReceived->{budgetid};
267         $data->{listprice}      = $lastOrderReceived->{listprice};
268         $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
269         $data->{gstrate}        = $lastOrderReceived->{gstrate};
270         $data->{discount}       = $lastOrderReceived->{discount};
271         $data->{rrp}            = $lastOrderReceived->{rrp};
272         $data->{ecost}          = $lastOrderReceived->{ecost};
273         $data->{quantity}       = $lastOrderReceived->{quantity};
274         $data->{unitprice}      = $lastOrderReceived->{unitprice};
275         $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
276         $data->{order_vendornote}   = $lastOrderReceived->{order_vendornote};
277         $data->{sort1}          = $lastOrderReceived->{sort1};
278         $data->{sort2}          = $lastOrderReceived->{sort2};
279
280         $basket = GetBasket( $input->param('basketno') );
281     }
282 }
283
284 # Find the items.barcode subfield for barcode validations
285 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
286
287 # fill template
288 $template->param(
289     close        => $close,
290     budget_id    => $budget_id,
291     budget_name  => $budget_name
292 ) if ($close);
293
294 # get option values for gist syspref
295 my @gst_values = map {
296     option => $_ + 0.0
297 }, split( '\|', C4::Context->preference("gist") );
298
299 my $quantity = $input->param('rr_quantity_to_order') ?
300       $input->param('rr_quantity_to_order') :
301       $data->{'quantity'};
302 $quantity //= 0;
303
304 $template->param(
305     existing         => $biblionumber,
306     ordernumber           => $ordernumber,
307     # basket informations
308     basketno             => $basketno,
309     basket               => $basket,
310     basketname           => $basket->{'basketname'},
311     basketnote           => $basket->{'note'},
312     booksellerid         => $basket->{'booksellerid'},
313     basketbooksellernote => $basket->{booksellernote},
314     basketcontractno     => $basket->{contractnumber},
315     basketcontractname   => $contract->{contractname},
316     creationdate         => $basket->{creationdate},
317     authorisedby         => $basket->{'authorisedby'},
318     authorisedbyname     => $basket->{'authorisedbyname'},
319     closedate            => $basket->{'closedate'},
320     # order details
321     suggestionid         => $suggestion->{suggestionid},
322     surnamesuggestedby   => $suggestion->{surnamesuggestedby},
323     firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
324     biblionumber         => $biblionumber,
325     uncertainprice       => $data->{'uncertainprice'},
326     discount_2dp         => sprintf( "%.2f",  $bookseller->{'discount'} ) ,   # for display
327     discount             => $bookseller->{'discount'},
328     orderdiscount_2dp    => sprintf( "%.2f", $data->{'discount'} || 0 ),
329     orderdiscount        => $data->{'discount'},
330     order_internalnote   => $data->{'order_internalnote'},
331     order_vendornote     => $data->{'order_vendornote'},
332     listincgst       => $bookseller->{'listincgst'},
333     invoiceincgst    => $bookseller->{'invoiceincgst'},
334     name             => $bookseller->{'name'},
335     cur_active_sym   => $active_currency->symbol,
336     cur_active       => $active_currency->currency,
337     currencies       => \@currencies,
338     currency         => $data->{currency},
339     vendor_currency  => $bookseller->{listprice},
340     orderexists      => ( $new eq 'yes' ) ? 0 : 1,
341     title            => $data->{'title'},
342     author           => $data->{'author'},
343     publicationyear  => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
344     editionstatement => $data->{'editionstatement'},
345     budget_loop      => $budget_loop,
346     isbn             => $data->{'isbn'},
347     ean              => $data->{'ean'},
348     seriestitle      => $data->{'seriestitle'},
349     itemtypeloop     => \@itemtypes,
350     quantity         => $quantity,
351     quantityrec      => $quantity,
352     rrp              => $data->{'rrp'},
353     gst_values       => \@gst_values,
354     gstrate          => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
355     listprice        => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
356     total            => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
357     ecost            => sprintf( "%.2f", $data->{ecost} || 0),
358     unitprice        => sprintf( "%.2f", $data->{unitprice} || 0),
359     publishercode    => $data->{'publishercode'},
360     barcode_subfield => $barcode_subfield,
361     import_batch_id  => $import_batch_id,
362     subscriptionid   => $subscriptionid,
363     acqcreate        => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
364     users_ids        => join(':', @order_user_ids),
365     users            => \@order_users,
366     (uc(C4::Context->preference("marcflavour"))) => 1
367 );
368
369 output_html_with_http_headers $input, $cookie, $template->output;
370
371
372 =head2 MARCfindbreeding
373
374   $record = MARCfindbreeding($breedingid);
375
376 Look up the import record repository for the record with
377 record with id $breedingid.  If found, returns the decoded
378 MARC::Record; otherwise, -1 is returned (FIXME).
379 Returns as second parameter the character encoding.
380
381 =cut
382
383 sub MARCfindbreeding {
384     my ( $id ) = @_;
385     my ($marc, $encoding) = GetImportRecordMarc($id);
386     # remove the - in isbn, koha store isbn without any -
387     if ($marc) {
388         my $record = MARC::Record->new_from_usmarc($marc);
389         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
390         if ( $record->field($isbnfield) ) {
391             foreach my $field ( $record->field($isbnfield) ) {
392                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
393                     my $newisbn = $field->subfield($isbnsubfield);
394                     $newisbn =~ s/-//g;
395                     $field->update( $isbnsubfield => $newisbn );
396                 }
397             }
398         }
399         # fix the unimarc 100 coded field (with unicode information)
400         if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
401             my $f100a=$record->subfield(100,'a');
402             my $f100 = $record->field(100);
403             my $f100temp = $f100->as_string;
404             $record->delete_field($f100);
405             if ( length($f100temp) > 28 ) {
406                 substr( $f100temp, 26, 2, "50" );
407                 $f100->update( 'a' => $f100temp );
408                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
409                 $record->insert_fields_ordered($f100);
410             }
411         }
412         
413         if ( !defined(ref($record)) ) {
414             return -1;
415         }
416         else {
417             # normalize author : probably UNIMARC specific...
418             if (    C4::Context->preference("z3950NormalizeAuthor")
419                 and C4::Context->preference("z3950AuthorAuthFields") )
420             {
421                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
422
423 #                 my $summary = C4::Context->preference("z3950authortemplate");
424                 my $auth_fields =
425                 C4::Context->preference("z3950AuthorAuthFields");
426                 my @auth_fields = split /,/, $auth_fields;
427                 my $field;
428
429                 if ( $record->field($tag) ) {
430                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
431
432     #                        foreach my $subfieldcode ($tmpfield->subfields){
433                         my $subfieldcode  = shift @$tmpfield;
434                         my $subfieldvalue = shift @$tmpfield;
435                         if ($field) {
436                             $field->add_subfields(
437                                 "$subfieldcode" => $subfieldvalue )
438                             if ( $subfieldcode ne $subfield );
439                         }
440                         else {
441                             $field =
442                             MARC::Field->new( $tag, "", "",
443                                 $subfieldcode => $subfieldvalue )
444                             if ( $subfieldcode ne $subfield );
445                         }
446                     }
447                 }
448                 $record->delete_field( $record->field($tag) );
449                 foreach my $fieldtag (@auth_fields) {
450                     next unless ( $record->field($fieldtag) );
451                     my $lastname  = $record->field($fieldtag)->subfield('a');
452                     my $firstname = $record->field($fieldtag)->subfield('b');
453                     my $title     = $record->field($fieldtag)->subfield('c');
454                     my $number    = $record->field($fieldtag)->subfield('d');
455                     if ($title) {
456
457 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
458                         $field->add_subfields(
459                                 "$subfield" => ucfirst($title) . " "
460                             . ucfirst($firstname) . " "
461                             . $number );
462                     }
463                     else {
464
465 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
466                         $field->add_subfields(
467                             "$subfield" => ucfirst($firstname) . ", "
468                             . ucfirst($lastname) );
469                     }
470                 }
471                 $record->insert_fields_ordered($field);
472             }
473             return $record, $encoding;
474         }
475     }
476     return -1;
477 }
478
479 sub Load_Duplicate {
480   my ($duplicatetitle)= @_;
481   ($template, $loggedinuser, $cookie) = get_template_and_user(
482     {
483         template_name   => "acqui/neworderempty_duplicate.tt",
484         query           => $input,
485         type            => "intranet",
486         authnotrequired => 0,
487         flagsrequired   => { acquisition => 'order_manage' },
488 #        debug           => 1,
489     }
490   );
491
492   $template->param(
493     biblionumber        => $biblionumber,
494     basketno            => $basketno,
495     booksellerid        => $basket->{'booksellerid'},
496     breedingid          => $params->{'breedingid'},
497     duplicatetitle      => $duplicatetitle,
498     (uc(C4::Context->preference("marcflavour"))) => 1
499   );
500
501   output_html_with_http_headers $input, $cookie, $template->output;
502 }