Bug 11665: (follow-up) simplify code
[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 under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
13 # version.
14 #
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along
20 # with Koha; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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;
72 use C4::Context;
73 use C4::Input;
74
75 use C4::Auth;
76 use C4::Budgets;
77 use C4::Input;
78
79 use C4::Bookseller  qw/ GetBookSellerFromId /;
80 use C4::Acquisition;
81 use C4::Suggestions;    # GetSuggestion
82 use C4::Biblio;                 # GetBiblioData GetMarcPrice
83 use C4::Items; #PrepareItemRecord
84 use C4::Output;
85 use C4::Input;
86 use C4::Koha;
87 use C4::Branch;                 # GetBranches
88 use C4::Members;
89 use C4::Search qw/FindDuplicate/;
90
91 #needed for z3950 import:
92 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
93
94 our $input           = new CGI;
95 my $booksellerid    = $input->param('booksellerid');    # FIXME: else ERROR!
96 my $budget_id       = $input->param('budget_id') || 0;
97 my $title           = $input->param('title');
98 my $author          = $input->param('author');
99 my $publicationyear = $input->param('publicationyear');
100 my $ordernumber          = $input->param('ordernumber') || '';
101 our $biblionumber    = $input->param('biblionumber');
102 our $basketno        = $input->param('basketno');
103 my $suggestionid    = $input->param('suggestionid');
104 my $close           = $input->param('close');
105 my $uncertainprice  = $input->param('uncertainprice');
106 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 !
107 my $subscriptionid  = $input->param('subscriptionid');
108 my $data;
109 my $new = 'no';
110
111 my $budget_name;
112
113 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
114     {
115         template_name   => "acqui/neworderempty.tmpl",
116         query           => $input,
117         type            => "intranet",
118         authnotrequired => 0,
119         flagsrequired   => { acquisition => 'order_manage' },
120         debug           => 1,
121     }
122 );
123
124 our $marcflavour = C4::Context->preference('marcflavour');
125
126 if(!$basketno) {
127     my $order = GetOrder($ordernumber);
128     $basketno = $order->{'basketno'};
129 }
130
131 our $basket = GetBasket($basketno);
132 $booksellerid = $basket->{booksellerid} unless $booksellerid;
133 my $bookseller = GetBookSellerFromId($booksellerid);
134
135 my $contract = &GetContract($basket->{contractnumber});
136
137 #simple parameters reading (all in one :-)
138 our $params = $input->Vars;
139 my $listprice=0; # the price, that can be in MARC record if we have one
140 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
141 #we want to import from the breeding reservoir (from a z3950 search)
142     my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
143     die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
144
145     # Remove all the items (952) from the imported record
146     foreach my $item ($marcrecord->field('952')) {
147         $marcrecord->delete_field($item);
148     }
149
150     my $duplicatetitle;
151 #look for duplicates
152     ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
153     if($biblionumber && !$input->param('use_external_source')) {
154         #if duplicate record found and user did not decide yet, first warn user
155         #and let him choose between using new record or existing record
156         Load_Duplicate($duplicatetitle);
157         exit;
158     }
159     #from this point: add a new record
160         if (C4::Context->preference("BiblioAddsAuthorities")){
161             my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
162         }
163         my $bibitemnum;
164         $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
165         ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
166         # get the price if there is one.
167         $listprice = GetMarcPrice($marcrecord, $marcflavour);
168         SetImportRecordStatus($params->{'breedingid'}, 'imported');
169 }
170
171
172
173 if ( $ordernumber eq '' ) {    # create order
174     $new = 'yes';
175
176     #   $ordernumber=newordernum;
177     if ( $biblionumber && !$suggestionid ) {
178         $data = GetBiblioData($biblionumber);
179     }
180
181 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
182 # otherwise, retrieve suggestion information.
183     if ($suggestionid) {
184         $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
185         $budget_id ||= $data->{'budgetid'} // 0;
186     }
187 }
188 else {    #modify order
189     $data   = GetOrder($ordernumber);
190     $biblionumber = $data->{'biblionumber'};
191     $budget_id = $data->{'budget_id'};
192
193     $basket   = GetBasket( $data->{'basketno'} );
194     $basketno = $basket->{'basketno'};
195 }
196
197 my $suggestion;
198 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
199
200 # get currencies (for change rates calcs if needed)
201 my $active_currency = GetCurrency();
202 my $default_currency;
203 if (! $data->{currency} ) { # New order no currency set
204     if ( $bookseller->{listprice} ) {
205         $default_currency = $bookseller->{listprice};
206     }
207     else {
208         $default_currency = $active_currency->{currency};
209     }
210 }
211
212 my @rates = GetCurrencies();
213
214 # ## @rates
215
216 my @loop_currency = ();
217 for my $curr ( @rates ) {
218     my $selected;
219     if ($data->{currency} ) {
220         $selected = $curr->{currency} eq $data->{currency};
221     }
222     else {
223         $selected = $curr->{currency} eq $default_currency;
224     }
225     push @loop_currency, {
226         currcode => $curr->{currency},
227         rate     => $curr->{rate},
228         selected => $selected,
229     }
230 }
231
232 # build branches list
233 my $onlymine =
234      C4::Context->preference('IndependentBranches')
235   && C4::Context->userenv
236   && !C4::Context->IsSuperLibrarian()
237   && C4::Context->userenv->{branch};
238 my $branches = GetBranches($onlymine);
239 my @branchloop;
240 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
241     my %row = (
242         value      => $thisbranch,
243         branchname => $branches->{$thisbranch}->{'branchname'},
244     );
245     $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
246     push @branchloop, \%row;
247 }
248 $template->param( branchloop => \@branchloop );
249
250 # build bookfund list
251 my $borrower= GetMember('borrowernumber' => $loggedinuser);
252 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
253
254 my $budget =  GetBudget($budget_id);
255 # build budget list
256 my $budget_loop = [];
257 my $budgets = GetBudgetHierarchy;
258 foreach my $r (@{$budgets}) {
259     next unless (CanUserUseBudget($borrower, $r, $userflags));
260     if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
261         next;
262     }
263     push @{$budget_loop}, {
264         b_id  => $r->{budget_id},
265         b_txt => $r->{budget_name},
266         b_active => $r->{budget_period_active},
267         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
268     };
269 }
270
271 @{$budget_loop} =
272   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
273
274 if ($close) {
275     $budget_id      =  $data->{'budget_id'};
276     $budget_name    =   $budget->{'budget_name'};
277
278 }
279
280 my $CGIsort1;
281 if ($budget) {    # its a mod ..
282     if ( defined $budget->{'sort1_authcat'} ) {    # with custom  Asort* planning values
283         $CGIsort1 = GetAuthvalueDropbox( $budget->{'sort1_authcat'}, $data->{'sort1'} );
284     }
285 } elsif(@{$budgets}){
286     $CGIsort1 = GetAuthvalueDropbox(  @$budgets[0]->{'sort1_authcat'}, '' );
287 }
288
289 # if CGIsort is successfully fetched, the use it
290 # else - failback to plain input-field
291 if ($CGIsort1) {
292     $template->param( CGIsort1 => $CGIsort1 );
293 } else {
294     $template->param( sort1 => $data->{'sort1'} );
295 }
296
297 my $CGIsort2;
298 if ($budget) {
299     if ( defined $budget->{'sort2_authcat'} ) {
300         $CGIsort2 = GetAuthvalueDropbox(  $budget->{'sort2_authcat'}, $data->{'sort2'} );
301     }
302 } elsif(@{$budgets}) {
303     $CGIsort2 = GetAuthvalueDropbox(  @$budgets[0]->{sort2_authcat}, '' );
304 }
305
306 if ($CGIsort2) {
307     $template->param( CGIsort2 => $CGIsort2 );
308 } else {
309     $template->param( sort2 => $data->{'sort2'} );
310 }
311
312 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
313     # Check if ACQ framework exists
314     my $marc = GetMarcStructure(1, 'ACQ');
315     unless($marc) {
316         $template->param('NoACQframework' => 1);
317     }
318     $template->param(
319         AcqCreateItemOrdering => 1,
320         UniqueItemFields => C4::Context->preference('UniqueItemFields'),
321     );
322 }
323 # 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
324 my @itemtypes;
325 @itemtypes = C4::ItemType->all unless C4::Context->preference('item-level_itypes');
326
327 if ( defined $subscriptionid ) {
328     my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
329     if ( defined $lastOrderReceived ) {
330         $budget_id              = $lastOrderReceived->{budgetid};
331         $data->{listprice}      = $lastOrderReceived->{listprice};
332         $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
333         $data->{gstrate}        = $lastOrderReceived->{gstrate};
334         $data->{discount}       = $lastOrderReceived->{discount};
335         $data->{rrp}            = $lastOrderReceived->{rrp};
336         $data->{ecost}          = $lastOrderReceived->{ecost};
337         $data->{quantity}       = $lastOrderReceived->{quantity};
338         $data->{unitprice}      = $lastOrderReceived->{unitprice};
339         $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
340         $data->{order_vendornote}   = $lastOrderReceived->{order_vendornote};
341         $data->{sort1}          = $lastOrderReceived->{sort1};
342         $data->{sort2}          = $lastOrderReceived->{sort2};
343
344         $basket = GetBasket( $input->param('basketno') );
345     }
346 }
347
348 # Find the items.barcode subfield for barcode validations
349 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
350
351 # fill template
352 $template->param(
353     close        => $close,
354     budget_id    => $budget_id,
355     budget_name  => $budget_name
356 ) if ($close);
357
358 # get option values for gist syspref
359 my @gst_values = map {
360     option => $_ + 0.0
361 }, split( '\|', C4::Context->preference("gist") );
362
363 my $quantity = $input->param('rr_quantity_to_order') ?
364       $input->param('rr_quantity_to_order') :
365       $data->{'quantity'};
366 $quantity //= 0;
367
368 $template->param(
369     existing         => $biblionumber,
370     ordernumber           => $ordernumber,
371     # basket informations
372     basketno             => $basketno,
373     basketname           => $basket->{'basketname'},
374     basketnote           => $basket->{'note'},
375     booksellerid         => $basket->{'booksellerid'},
376     basketbooksellernote => $basket->{booksellernote},
377     basketcontractno     => $basket->{contractnumber},
378     basketcontractname   => $contract->{contractname},
379     creationdate         => $basket->{creationdate},
380     authorisedby         => $basket->{'authorisedby'},
381     authorisedbyname     => $basket->{'authorisedbyname'},
382     closedate            => $basket->{'closedate'},
383     # order details
384     suggestionid         => $suggestion->{suggestionid},
385     surnamesuggestedby   => $suggestion->{surnamesuggestedby},
386     firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
387     biblionumber         => $biblionumber,
388     uncertainprice       => $data->{'uncertainprice'},
389     authorisedbyname     => $borrower->{'firstname'} . " " . $borrower->{'surname'},
390     discount_2dp         => sprintf( "%.2f",  $bookseller->{'discount'} ) ,   # for display
391     discount             => $bookseller->{'discount'},
392     orderdiscount_2dp    => sprintf( "%.2f", $data->{'discount'} || 0 ),
393     orderdiscount        => $data->{'discount'},
394     order_internalnote   => $data->{'order_internalnote'},
395     order_vendornote     => $data->{'order_vendornote'},
396     listincgst       => $bookseller->{'listincgst'},
397     invoiceincgst    => $bookseller->{'invoiceincgst'},
398     name             => $bookseller->{'name'},
399     cur_active_sym   => $active_currency->{'symbol'},
400     cur_active       => $active_currency->{'currency'},
401     loop_currencies  => \@loop_currency,
402     orderexists      => ( $new eq 'yes' ) ? 0 : 1,
403     title            => $data->{'title'},
404     author           => $data->{'author'},
405     publicationyear  => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
406     editionstatement => $data->{'editionstatement'},
407     budget_loop      => $budget_loop,
408     isbn             => $data->{'isbn'},
409     ean              => $data->{'ean'},
410     seriestitle      => $data->{'seriestitle'},
411     itemtypeloop     => \@itemtypes,
412     quantity         => $quantity,
413     quantityrec      => $quantity,
414     rrp              => $data->{'rrp'},
415     gst_values       => \@gst_values,
416     gstrate          => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
417     gstreg           => $bookseller->{'gstreg'},
418     listprice        => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
419     total            => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
420     ecost            => sprintf( "%.2f", $data->{ecost} || 0),
421     unitprice        => sprintf( "%.2f", $data->{unitprice} || 0),
422     publishercode    => $data->{'publishercode'},
423     barcode_subfield => $barcode_subfield,
424     import_batch_id  => $import_batch_id,
425     subscriptionid   => $subscriptionid,
426     acqcreate        => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
427     (uc(C4::Context->preference("marcflavour"))) => 1
428 );
429
430 output_html_with_http_headers $input, $cookie, $template->output;
431
432
433 =head2 MARCfindbreeding
434
435   $record = MARCfindbreeding($breedingid);
436
437 Look up the import record repository for the record with
438 record with id $breedingid.  If found, returns the decoded
439 MARC::Record; otherwise, -1 is returned (FIXME).
440 Returns as second parameter the character encoding.
441
442 =cut
443
444 sub MARCfindbreeding {
445     my ( $id ) = @_;
446     my ($marc, $encoding) = GetImportRecordMarc($id);
447     # remove the - in isbn, koha store isbn without any -
448     if ($marc) {
449         my $record = MARC::Record->new_from_usmarc($marc);
450         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
451         if ( $record->field($isbnfield) ) {
452             foreach my $field ( $record->field($isbnfield) ) {
453                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
454                     my $newisbn = $field->subfield($isbnsubfield);
455                     $newisbn =~ s/-//g;
456                     $field->update( $isbnsubfield => $newisbn );
457                 }
458             }
459         }
460         # fix the unimarc 100 coded field (with unicode information)
461         if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
462             my $f100a=$record->subfield(100,'a');
463             my $f100 = $record->field(100);
464             my $f100temp = $f100->as_string;
465             $record->delete_field($f100);
466             if ( length($f100temp) > 28 ) {
467                 substr( $f100temp, 26, 2, "50" );
468                 $f100->update( 'a' => $f100temp );
469                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
470                 $record->insert_fields_ordered($f100);
471             }
472         }
473         
474         if ( !defined(ref($record)) ) {
475             return -1;
476         }
477         else {
478             # normalize author : probably UNIMARC specific...
479             if (    C4::Context->preference("z3950NormalizeAuthor")
480                 and C4::Context->preference("z3950AuthorAuthFields") )
481             {
482                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
483
484 #                 my $summary = C4::Context->preference("z3950authortemplate");
485                 my $auth_fields =
486                 C4::Context->preference("z3950AuthorAuthFields");
487                 my @auth_fields = split /,/, $auth_fields;
488                 my $field;
489
490                 if ( $record->field($tag) ) {
491                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
492
493     #                        foreach my $subfieldcode ($tmpfield->subfields){
494                         my $subfieldcode  = shift @$tmpfield;
495                         my $subfieldvalue = shift @$tmpfield;
496                         if ($field) {
497                             $field->add_subfields(
498                                 "$subfieldcode" => $subfieldvalue )
499                             if ( $subfieldcode ne $subfield );
500                         }
501                         else {
502                             $field =
503                             MARC::Field->new( $tag, "", "",
504                                 $subfieldcode => $subfieldvalue )
505                             if ( $subfieldcode ne $subfield );
506                         }
507                     }
508                 }
509                 $record->delete_field( $record->field($tag) );
510                 foreach my $fieldtag (@auth_fields) {
511                     next unless ( $record->field($fieldtag) );
512                     my $lastname  = $record->field($fieldtag)->subfield('a');
513                     my $firstname = $record->field($fieldtag)->subfield('b');
514                     my $title     = $record->field($fieldtag)->subfield('c');
515                     my $number    = $record->field($fieldtag)->subfield('d');
516                     if ($title) {
517
518 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
519                         $field->add_subfields(
520                                 "$subfield" => ucfirst($title) . " "
521                             . ucfirst($firstname) . " "
522                             . $number );
523                     }
524                     else {
525
526 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
527                         $field->add_subfields(
528                             "$subfield" => ucfirst($firstname) . ", "
529                             . ucfirst($lastname) );
530                     }
531                 }
532                 $record->insert_fields_ordered($field);
533             }
534             return $record, $encoding;
535         }
536     }
537     return -1;
538 }
539
540 sub Load_Duplicate {
541   my ($duplicatetitle)= @_;
542   ($template, $loggedinuser, $cookie) = get_template_and_user(
543     {
544         template_name   => "acqui/neworderempty_duplicate.tmpl",
545         query           => $input,
546         type            => "intranet",
547         authnotrequired => 0,
548         flagsrequired   => { acquisition => 'order_manage' },
549 #        debug           => 1,
550     }
551   );
552
553   $template->param(
554     biblionumber        => $biblionumber,
555     basketno            => $basketno,
556     booksellerid        => $basket->{'booksellerid'},
557     breedingid          => $params->{'breedingid'},
558     duplicatetitle      => $duplicatetitle,
559     (uc(C4::Context->preference("marcflavour"))) => 1
560   );
561
562   output_html_with_http_headers $input, $cookie, $template->output;
563 }