Bug 7772 - reports/bor_issues_top.pl: we need to exit(0) for plack
[koha.git] / acqui / neworderempty.pl
blobd48255443b943779b8f5e9dff6db4d3007bcc02c
1 #!/usr/bin/perl
3 #script to show display basket of orders
4 #written by chris@katipo.co.nz 24/2/2000
6 # Copyright 2000-2002 Katipo Communications
8 # This file is part of Koha.
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.
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.
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.
24 =head1 NAME
26 neworderempty.pl
28 =head1 DESCRIPTION
30 this script allows to create a new record to order it. This record shouldn't exist
31 on database.
33 =head1 CGI PARAMETERS
35 =over 4
37 =item booksellerid
38 the bookseller the librarian has to buy a new book.
40 =item title
41 the title of this new record.
43 =item author
44 the author of this new record.
46 =item publication year
47 the publication year of this new record.
49 =item ordernumber
50 the number of this order.
52 =item biblio
54 =item basketno
55 the basket number for this new order.
57 =item suggestionid
58 if this order comes from a suggestion.
60 =item breedingid
61 the item's id in the breeding reservoir
63 =item close
65 =back
67 =cut
69 use warnings;
70 use strict;
71 use CGI;
72 use C4::Context;
73 use C4::Input;
75 use C4::Auth;
76 use C4::Budgets;
77 use C4::Input;
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/;
91 #needed for z3950 import:
92 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
94 my $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 my $biblionumber = $input->param('biblionumber');
103 my $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';
111 my $budget_name;
113 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
115 template_name => "acqui/neworderempty.tmpl",
116 query => $input,
117 type => "intranet",
118 authnotrequired => 0,
119 flagsrequired => { acquisition => 'order_manage' },
120 debug => 1,
124 my $marcflavour = C4::Context->preference('marcflavour');
126 if(!$basketno) {
127 my $order = GetOrder($ordernumber);
128 $basketno = $order->{'basketno'};
131 my $basket = GetBasket($basketno);
132 my $contract = &GetContract($basket->{contractnumber});
134 #simple parameters reading (all in one :-)
135 my $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;
142 # Remove all the items (952) from the imported record
143 foreach my $item ($marcrecord->field('952')) {
144 $marcrecord->delete_field($item);
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;
156 #from this point: add a new record
157 if (C4::Context->preference("BiblioAddsAuthorities")){
158 my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
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');
170 if ( $ordernumber eq '' ) { # create order
171 $new = 'yes';
173 # $ordernumber=newordernum;
174 if ( $biblionumber && !$suggestionid ) {
175 $data = GetBiblioData($biblionumber);
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);
184 else { #modify order
185 $data = GetOrder($ordernumber);
186 $biblionumber = $data->{'biblionumber'};
187 $budget_id = $data->{'budget_id'};
189 #get basketno and supplierno. too!
190 my $data2 = GetBasket( $data->{'basketno'} );
191 $basketno = $data2->{'basketno'};
192 $booksellerid = $data2->{'booksellerid'};
195 my $suggestion;
196 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
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};
205 else {
206 $default_currency = $active_currency->{currency};
210 my @rates = GetCurrencies();
212 # ## @rates
214 my @loop_currency = ();
215 for my $curr ( @rates ) {
216 my $selected;
217 if ($data->{currency} ) {
218 $selected = $curr->{currency} eq $data->{currency};
220 else {
221 $selected = $curr->{currency} eq $default_currency;
223 push @loop_currency, {
224 currcode => $curr->{currency},
225 rate => $curr->{rate},
226 selected => $selected,
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'},
242 $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
243 push @branchloop, \%row;
245 $template->param( branchloop => \@branchloop );
247 # build bookfund list
248 my $borrower= GetMember('borrowernumber' => $loggedinuser);
249 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
251 my $budget = GetBudget($budget_id);
252 # build budget list
253 my $budget_loop = [];
254 my $budgets = GetBudgetHierarchy(q{},$borrower->{branchcode},$borrower->{borrowernumber});
255 foreach my $r (@{$budgets}) {
256 if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
257 next;
259 push @{$budget_loop}, {
260 b_id => $r->{budget_id},
261 b_txt => $r->{budget_name},
262 b_active => $r->{budget_period_active},
263 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
268 if ($close) {
269 $budget_id = $data->{'budget_id'};
270 $budget_name = $budget->{'budget_name'};
274 my $CGIsort1;
275 if ($budget) { # its a mod ..
276 if ( defined $budget->{'sort1_authcat'} ) { # with custom Asort* planning values
277 $CGIsort1 = GetAuthvalueDropbox( $budget->{'sort1_authcat'}, $data->{'sort1'} );
279 } elsif(@{$budgets}){
280 $CGIsort1 = GetAuthvalueDropbox( @$budgets[0]->{'sort1_authcat'}, '' );
281 }else{
282 $CGIsort1 = GetAuthvalueDropbox( '', '' );
285 # if CGIsort is successfully fetched, the use it
286 # else - failback to plain input-field
287 if ($CGIsort1) {
288 $template->param( CGIsort1 => $CGIsort1 );
289 } else {
290 $template->param( sort1 => $data->{'sort1'} );
293 my $CGIsort2;
294 if ($budget) {
295 if ( defined $budget->{'sort2_authcat'} ) {
296 $CGIsort2 = GetAuthvalueDropbox( $budget->{'sort2_authcat'}, $data->{'sort2'} );
298 } elsif(@{$budgets}) {
299 $CGIsort2 = GetAuthvalueDropbox( @$budgets[0]->{sort2_authcat}, '' );
300 }else{
301 $CGIsort2 = GetAuthvalueDropbox( '', '' );
304 if ($CGIsort2) {
305 $template->param( CGIsort2 => $CGIsort2 );
306 } else {
307 $template->param( sort2 => $data->{'sort2'} );
310 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
311 # Check if ACQ framework exists
312 my $marc = GetMarcStructure(1, 'ACQ');
313 unless($marc) {
314 $template->param('NoACQframework' => 1);
316 $template->param(
317 AcqCreateItemOrdering => 1,
318 UniqueItemFields => C4::Context->preference('UniqueItemFields'),
321 # 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
322 my @itemtypes;
323 @itemtypes = C4::ItemType->all unless C4::Context->preference('item-level_itypes');
325 # Find the items.barcode subfield for barcode validations
326 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
328 # fill template
329 $template->param(
330 close => $close,
331 budget_id => $budget_id,
332 budget_name => $budget_name
333 ) if ($close);
335 $template->param(
336 existing => $biblionumber,
337 ordernumber => $ordernumber,
338 # basket informations
339 basketno => $basketno,
340 basketname => $basket->{'basketname'},
341 basketnote => $basket->{'note'},
342 booksellerid => $basket->{'booksellerid'},
343 basketbooksellernote => $basket->{booksellernote},
344 basketcontractno => $basket->{contractnumber},
345 basketcontractname => $contract->{contractname},
346 creationdate => $basket->{creationdate},
347 authorisedby => $basket->{'authorisedby'},
348 authorisedbyname => $basket->{'authorisedbyname'},
349 closedate => $basket->{'closedate'},
350 # order details
351 suggestionid => $suggestion->{suggestionid},
352 surnamesuggestedby => $suggestion->{surnamesuggestedby},
353 firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
354 biblionumber => $biblionumber,
355 uncertainprice => $data->{'uncertainprice'},
356 authorisedbyname => $borrower->{'firstname'} . " " . $borrower->{'surname'},
357 biblioitemnumber => $data->{'biblioitemnumber'},
358 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'}) , # for display
359 discount => $bookseller->{'discount'},
360 listincgst => $bookseller->{'listincgst'},
361 invoiceincgst => $bookseller->{'invoiceincgst'},
362 name => $bookseller->{'name'},
363 cur_active_sym => $active_currency->{'symbol'},
364 cur_active => $active_currency->{'currency'},
365 loop_currencies => \@loop_currency,
366 orderexists => ( $new eq 'yes' ) ? 0 : 1,
367 title => $data->{'title'},
368 author => $data->{'author'},
369 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
370 editionstatement => $data->{'editionstatement'},
371 budget_loop => $budget_loop,
372 isbn => $data->{'isbn'},
373 seriestitle => $data->{'seriestitle'},
374 itemtypeloop => \@itemtypes,
375 quantity => $data->{'quantity'},
376 quantityrec => $data->{'quantity'},
377 rrp => $data->{'rrp'},
378 listprice => sprintf("%.2f", $data->{'listprice'}||$data->{'price'}||$listprice),
379 total => sprintf("%.2f", ($data->{'ecost'}||0)*($data->{'quantity'}||0) ),
380 ecost => $data->{'ecost'},
381 unitprice => sprintf("%.2f", $data->{'unitprice'}),
382 notes => $data->{'notes'},
383 publishercode => $data->{'publishercode'},
384 barcode_subfield => $barcode_subfield,
386 import_batch_id => $import_batch_id,
388 # CHECKME: gst-stuff needs verifing, mason.
389 gstrate => $bookseller->{'gstrate'} // C4::Context->preference("gist") // 0,
390 gstreg => $bookseller->{'gstreg'},
393 output_html_with_http_headers $input, $cookie, $template->output;
396 =head2 MARCfindbreeding
398 $record = MARCfindbreeding($breedingid);
400 Look up the import record repository for the record with
401 record with id $breedingid. If found, returns the decoded
402 MARC::Record; otherwise, -1 is returned (FIXME).
403 Returns as second parameter the character encoding.
405 =cut
407 sub MARCfindbreeding {
408 my ( $id ) = @_;
409 my ($marc, $encoding) = GetImportRecordMarc($id);
410 # remove the - in isbn, koha store isbn without any -
411 if ($marc) {
412 my $record = MARC::Record->new_from_usmarc($marc);
413 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
414 if ( $record->field($isbnfield) ) {
415 foreach my $field ( $record->field($isbnfield) ) {
416 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
417 my $newisbn = $field->subfield($isbnsubfield);
418 $newisbn =~ s/-//g;
419 $field->update( $isbnsubfield => $newisbn );
423 # fix the unimarc 100 coded field (with unicode information)
424 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
425 my $f100a=$record->subfield(100,'a');
426 my $f100 = $record->field(100);
427 my $f100temp = $f100->as_string;
428 $record->delete_field($f100);
429 if ( length($f100temp) > 28 ) {
430 substr( $f100temp, 26, 2, "50" );
431 $f100->update( 'a' => $f100temp );
432 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
433 $record->insert_fields_ordered($f100);
437 if ( !defined(ref($record)) ) {
438 return -1;
440 else {
441 # normalize author : probably UNIMARC specific...
442 if ( C4::Context->preference("z3950NormalizeAuthor")
443 and C4::Context->preference("z3950AuthorAuthFields") )
445 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author");
447 # my $summary = C4::Context->preference("z3950authortemplate");
448 my $auth_fields =
449 C4::Context->preference("z3950AuthorAuthFields");
450 my @auth_fields = split /,/, $auth_fields;
451 my $field;
453 if ( $record->field($tag) ) {
454 foreach my $tmpfield ( $record->field($tag)->subfields ) {
456 # foreach my $subfieldcode ($tmpfield->subfields){
457 my $subfieldcode = shift @$tmpfield;
458 my $subfieldvalue = shift @$tmpfield;
459 if ($field) {
460 $field->add_subfields(
461 "$subfieldcode" => $subfieldvalue )
462 if ( $subfieldcode ne $subfield );
464 else {
465 $field =
466 MARC::Field->new( $tag, "", "",
467 $subfieldcode => $subfieldvalue )
468 if ( $subfieldcode ne $subfield );
472 $record->delete_field( $record->field($tag) );
473 foreach my $fieldtag (@auth_fields) {
474 next unless ( $record->field($fieldtag) );
475 my $lastname = $record->field($fieldtag)->subfield('a');
476 my $firstname = $record->field($fieldtag)->subfield('b');
477 my $title = $record->field($fieldtag)->subfield('c');
478 my $number = $record->field($fieldtag)->subfield('d');
479 if ($title) {
481 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
482 $field->add_subfields(
483 "$subfield" => ucfirst($title) . " "
484 . ucfirst($firstname) . " "
485 . $number );
487 else {
489 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
490 $field->add_subfields(
491 "$subfield" => ucfirst($firstname) . ", "
492 . ucfirst($lastname) );
495 $record->insert_fields_ordered($field);
497 return $record, $encoding;
500 return -1;
503 sub Load_Duplicate {
504 my ($duplicatetitle)= @_;
505 ($template, $loggedinuser, $cookie) = get_template_and_user(
507 template_name => "acqui/neworderempty_duplicate.tmpl",
508 query => $input,
509 type => "intranet",
510 authnotrequired => 0,
511 flagsrequired => { acquisition => 'order_manage' },
512 # debug => 1,
516 $template->param(
517 biblionumber => $biblionumber,
518 basketno => $basketno,
519 booksellerid => $basket->{'booksellerid'},
520 breedingid => $params->{'breedingid'},
521 duplicatetitle => $duplicatetitle,
524 output_html_with_http_headers $input, $cookie, $template->output;