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