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