Bug 7843: Followup - fix broken url
[koha.git] / acqui / neworderempty.pl
blob020c91f7246b0c2837dbc5f314daf55ca8fda2fb
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
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.
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.
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>.
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 qw ( -utf8 );
72 use C4::Context;
73 use C4::Input;
75 use C4::Auth;
76 use C4::Budgets;
77 use C4::Input;
79 use C4::Acquisition;
80 use C4::Contract;
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 use Koha::Acquisition::Bookseller;
96 our $input = new CGI;
97 my $booksellerid = $input->param('booksellerid'); # FIXME: else ERROR!
98 my $budget_id = $input->param('budget_id') || 0;
99 my $title = $input->param('title');
100 my $author = $input->param('author');
101 my $publicationyear = $input->param('publicationyear');
102 my $ordernumber = $input->param('ordernumber') || '';
103 our $biblionumber = $input->param('biblionumber');
104 our $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 $subscriptionid = $input->param('subscriptionid');
110 my $data;
111 my $new = 'no';
113 my $budget_name;
115 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
117 template_name => "acqui/neworderempty.tt",
118 query => $input,
119 type => "intranet",
120 authnotrequired => 0,
121 flagsrequired => { acquisition => 'order_manage' },
122 debug => 1,
126 our $marcflavour = C4::Context->preference('marcflavour');
128 if(!$basketno) {
129 my $order = GetOrder($ordernumber);
130 $basketno = $order->{'basketno'};
133 our $basket = GetBasket($basketno);
134 $booksellerid = $basket->{booksellerid} unless $booksellerid;
135 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
137 my $contract = GetContract({
138 contractnumber => $basket->{contractnumber}
141 #simple parameters reading (all in one :-)
142 our $params = $input->Vars;
143 my $listprice=0; # the price, that can be in MARC record if we have one
144 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
145 #we want to import from the breeding reservoir (from a z3950 search)
146 my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
147 die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
149 # Remove all the items (952) from the imported record
150 foreach my $item ($marcrecord->field('952')) {
151 $marcrecord->delete_field($item);
154 my $duplicatetitle;
155 #look for duplicates
156 ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
157 if($biblionumber && !$input->param('use_external_source')) {
158 #if duplicate record found and user did not decide yet, first warn user
159 #and let him choose between using new record or existing record
160 Load_Duplicate($duplicatetitle);
161 exit;
163 #from this point: add a new record
164 if (C4::Context->preference("BiblioAddsAuthorities")){
165 my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
167 my $bibitemnum;
168 $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
169 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
170 # get the price if there is one.
171 $listprice = GetMarcPrice($marcrecord, $marcflavour);
172 SetImportRecordStatus($params->{'breedingid'}, 'imported');
177 my ( @order_user_ids, @order_users );
178 if ( $ordernumber eq '' ) { # create order
179 $new = 'yes';
181 # $ordernumber=newordernum;
182 if ( $biblionumber && !$suggestionid ) {
183 $data = GetBiblioData($biblionumber);
186 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
187 # otherwise, retrieve suggestion information.
188 if ($suggestionid) {
189 $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
190 $budget_id ||= $data->{'budgetid'} // 0;
193 else { #modify order
194 $data = GetOrder($ordernumber);
195 $biblionumber = $data->{'biblionumber'};
196 $budget_id = $data->{'budget_id'};
198 $basket = GetBasket( $data->{'basketno'} );
199 $basketno = $basket->{'basketno'};
201 @order_user_ids = GetOrderUsers($ordernumber);
202 foreach my $order_user_id (@order_user_ids) {
203 my $order_user = GetMember(borrowernumber => $order_user_id);
204 push @order_users, $order_user if $order_user;
208 my $suggestion;
209 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
211 # get currencies (for change rates calcs if needed)
212 my $active_currency = GetCurrency();
213 my $default_currency;
214 if (! $data->{currency} ) { # New order no currency set
215 if ( $bookseller->{listprice} ) {
216 $default_currency = $bookseller->{listprice};
218 else {
219 $default_currency = $active_currency->{currency};
223 my @rates = GetCurrencies();
225 # ## @rates
227 my @loop_currency = ();
228 for my $curr ( @rates ) {
229 my $selected;
230 if ($data->{currency} ) {
231 $selected = $curr->{currency} eq $data->{currency};
233 else {
234 $selected = $curr->{currency} eq $default_currency;
236 push @loop_currency, {
237 currcode => $curr->{currency},
238 rate => $curr->{rate},
239 selected => $selected,
243 # build branches list
244 my $onlymine =
245 C4::Context->preference('IndependentBranches')
246 && C4::Context->userenv
247 && !C4::Context->IsSuperLibrarian()
248 && C4::Context->userenv->{branch};
249 my $branches = GetBranches($onlymine);
250 my @branchloop;
251 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
252 my %row = (
253 value => $thisbranch,
254 branchname => $branches->{$thisbranch}->{'branchname'},
256 $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
257 push @branchloop, \%row;
259 $template->param( branchloop => \@branchloop );
261 # build bookfund list
262 my $borrower= GetMember('borrowernumber' => $loggedinuser);
263 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
265 my $budget = GetBudget($budget_id);
266 # build budget list
267 my $budget_loop = [];
268 my $budgets = GetBudgetHierarchy;
269 foreach my $r (@{$budgets}) {
270 next unless (CanUserUseBudget($borrower, $r, $userflags));
271 if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
272 next;
274 push @{$budget_loop}, {
275 b_id => $r->{budget_id},
276 b_txt => $r->{budget_name},
277 b_sort1_authcat => $r->{'sort1_authcat'},
278 b_sort2_authcat => $r->{'sort2_authcat'},
279 b_active => $r->{budget_period_active},
280 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
284 @{$budget_loop} =
285 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
287 if ($close) {
288 $budget_id = $data->{'budget_id'};
289 $budget_name = $budget->{'budget_name'};
293 $template->param( sort1 => $data->{'sort1'} );
294 $template->param( sort2 => $data->{'sort2'} );
296 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
297 # Check if ACQ framework exists
298 my $marc = GetMarcStructure(1, 'ACQ');
299 unless($marc) {
300 $template->param('NoACQframework' => 1);
302 $template->param(
303 AcqCreateItemOrdering => 1,
304 UniqueItemFields => C4::Context->preference('UniqueItemFields'),
307 # 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
308 my @itemtypes;
309 @itemtypes = C4::ItemType->all unless C4::Context->preference('item-level_itypes');
311 if ( defined $subscriptionid ) {
312 my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
313 if ( defined $lastOrderReceived ) {
314 $budget_id = $lastOrderReceived->{budgetid};
315 $data->{listprice} = $lastOrderReceived->{listprice};
316 $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
317 $data->{gstrate} = $lastOrderReceived->{gstrate};
318 $data->{discount} = $lastOrderReceived->{discount};
319 $data->{rrp} = $lastOrderReceived->{rrp};
320 $data->{ecost} = $lastOrderReceived->{ecost};
321 $data->{quantity} = $lastOrderReceived->{quantity};
322 $data->{unitprice} = $lastOrderReceived->{unitprice};
323 $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
324 $data->{order_vendornote} = $lastOrderReceived->{order_vendornote};
325 $data->{sort1} = $lastOrderReceived->{sort1};
326 $data->{sort2} = $lastOrderReceived->{sort2};
328 $basket = GetBasket( $input->param('basketno') );
332 # Find the items.barcode subfield for barcode validations
333 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
335 # fill template
336 $template->param(
337 close => $close,
338 budget_id => $budget_id,
339 budget_name => $budget_name
340 ) if ($close);
342 # get option values for gist syspref
343 my @gst_values = map {
344 option => $_ + 0.0
345 }, split( '\|', C4::Context->preference("gist") );
347 my $quantity = $input->param('rr_quantity_to_order') ?
348 $input->param('rr_quantity_to_order') :
349 $data->{'quantity'};
350 $quantity //= 0;
352 $template->param(
353 existing => $biblionumber,
354 ordernumber => $ordernumber,
355 # basket informations
356 basketno => $basketno,
357 basketname => $basket->{'basketname'},
358 basketnote => $basket->{'note'},
359 booksellerid => $basket->{'booksellerid'},
360 basketbooksellernote => $basket->{booksellernote},
361 basketcontractno => $basket->{contractnumber},
362 basketcontractname => $contract->{contractname},
363 creationdate => $basket->{creationdate},
364 authorisedby => $basket->{'authorisedby'},
365 authorisedbyname => $basket->{'authorisedbyname'},
366 closedate => $basket->{'closedate'},
367 # order details
368 suggestionid => $suggestion->{suggestionid},
369 surnamesuggestedby => $suggestion->{surnamesuggestedby},
370 firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
371 biblionumber => $biblionumber,
372 uncertainprice => $data->{'uncertainprice'},
373 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
374 discount => $bookseller->{'discount'},
375 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
376 orderdiscount => $data->{'discount'},
377 order_internalnote => $data->{'order_internalnote'},
378 order_vendornote => $data->{'order_vendornote'},
379 listincgst => $bookseller->{'listincgst'},
380 invoiceincgst => $bookseller->{'invoiceincgst'},
381 name => $bookseller->{'name'},
382 cur_active_sym => $active_currency->{'symbol'},
383 cur_active => $active_currency->{'currency'},
384 loop_currencies => \@loop_currency,
385 orderexists => ( $new eq 'yes' ) ? 0 : 1,
386 title => $data->{'title'},
387 author => $data->{'author'},
388 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
389 editionstatement => $data->{'editionstatement'},
390 budget_loop => $budget_loop,
391 isbn => $data->{'isbn'},
392 ean => $data->{'ean'},
393 seriestitle => $data->{'seriestitle'},
394 itemtypeloop => \@itemtypes,
395 quantity => $quantity,
396 quantityrec => $quantity,
397 rrp => $data->{'rrp'},
398 gst_values => \@gst_values,
399 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
400 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
401 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
402 ecost => sprintf( "%.2f", $data->{ecost} || 0),
403 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
404 publishercode => $data->{'publishercode'},
405 barcode_subfield => $barcode_subfield,
406 import_batch_id => $import_batch_id,
407 subscriptionid => $subscriptionid,
408 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
409 users_ids => join(':', @order_user_ids),
410 users => \@order_users,
411 (uc(C4::Context->preference("marcflavour"))) => 1
414 output_html_with_http_headers $input, $cookie, $template->output;
417 =head2 MARCfindbreeding
419 $record = MARCfindbreeding($breedingid);
421 Look up the import record repository for the record with
422 record with id $breedingid. If found, returns the decoded
423 MARC::Record; otherwise, -1 is returned (FIXME).
424 Returns as second parameter the character encoding.
426 =cut
428 sub MARCfindbreeding {
429 my ( $id ) = @_;
430 my ($marc, $encoding) = GetImportRecordMarc($id);
431 # remove the - in isbn, koha store isbn without any -
432 if ($marc) {
433 my $record = MARC::Record->new_from_usmarc($marc);
434 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
435 if ( $record->field($isbnfield) ) {
436 foreach my $field ( $record->field($isbnfield) ) {
437 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
438 my $newisbn = $field->subfield($isbnsubfield);
439 $newisbn =~ s/-//g;
440 $field->update( $isbnsubfield => $newisbn );
444 # fix the unimarc 100 coded field (with unicode information)
445 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
446 my $f100a=$record->subfield(100,'a');
447 my $f100 = $record->field(100);
448 my $f100temp = $f100->as_string;
449 $record->delete_field($f100);
450 if ( length($f100temp) > 28 ) {
451 substr( $f100temp, 26, 2, "50" );
452 $f100->update( 'a' => $f100temp );
453 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
454 $record->insert_fields_ordered($f100);
458 if ( !defined(ref($record)) ) {
459 return -1;
461 else {
462 # normalize author : probably UNIMARC specific...
463 if ( C4::Context->preference("z3950NormalizeAuthor")
464 and C4::Context->preference("z3950AuthorAuthFields") )
466 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
468 # my $summary = C4::Context->preference("z3950authortemplate");
469 my $auth_fields =
470 C4::Context->preference("z3950AuthorAuthFields");
471 my @auth_fields = split /,/, $auth_fields;
472 my $field;
474 if ( $record->field($tag) ) {
475 foreach my $tmpfield ( $record->field($tag)->subfields ) {
477 # foreach my $subfieldcode ($tmpfield->subfields){
478 my $subfieldcode = shift @$tmpfield;
479 my $subfieldvalue = shift @$tmpfield;
480 if ($field) {
481 $field->add_subfields(
482 "$subfieldcode" => $subfieldvalue )
483 if ( $subfieldcode ne $subfield );
485 else {
486 $field =
487 MARC::Field->new( $tag, "", "",
488 $subfieldcode => $subfieldvalue )
489 if ( $subfieldcode ne $subfield );
493 $record->delete_field( $record->field($tag) );
494 foreach my $fieldtag (@auth_fields) {
495 next unless ( $record->field($fieldtag) );
496 my $lastname = $record->field($fieldtag)->subfield('a');
497 my $firstname = $record->field($fieldtag)->subfield('b');
498 my $title = $record->field($fieldtag)->subfield('c');
499 my $number = $record->field($fieldtag)->subfield('d');
500 if ($title) {
502 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
503 $field->add_subfields(
504 "$subfield" => ucfirst($title) . " "
505 . ucfirst($firstname) . " "
506 . $number );
508 else {
510 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
511 $field->add_subfields(
512 "$subfield" => ucfirst($firstname) . ", "
513 . ucfirst($lastname) );
516 $record->insert_fields_ordered($field);
518 return $record, $encoding;
521 return -1;
524 sub Load_Duplicate {
525 my ($duplicatetitle)= @_;
526 ($template, $loggedinuser, $cookie) = get_template_and_user(
528 template_name => "acqui/neworderempty_duplicate.tt",
529 query => $input,
530 type => "intranet",
531 authnotrequired => 0,
532 flagsrequired => { acquisition => 'order_manage' },
533 # debug => 1,
537 $template->param(
538 biblionumber => $biblionumber,
539 basketno => $basketno,
540 booksellerid => $basket->{'booksellerid'},
541 breedingid => $params->{'breedingid'},
542 duplicatetitle => $duplicatetitle,
543 (uc(C4::Context->preference("marcflavour"))) => 1
546 output_html_with_http_headers $input, $cookie, $template->output;