Bug 11081: (followup) Add license information
[koha.git] / acqui / neworderempty.pl
blob4a378157baf26d01132145e9d41316a3adc5060b
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;
74 use C4::Auth;
75 use C4::Budgets;
77 use C4::Acquisition;
78 use C4::Contract;
79 use C4::Suggestions; # GetSuggestion
80 use C4::Biblio; # GetBiblioData GetMarcPrice
81 use C4::Items; #PrepareItemRecord
82 use C4::Output;
83 use C4::Koha;
84 use C4::Branch; # GetBranches
85 use C4::Members;
86 use C4::Search qw/FindDuplicate/;
88 #needed for z3950 import:
89 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
91 use Koha::Acquisition::Bookseller;
93 our $input = new CGI;
94 my $booksellerid = $input->param('booksellerid'); # FIXME: else ERROR!
95 my $budget_id = $input->param('budget_id') || 0;
96 my $title = $input->param('title');
97 my $author = $input->param('author');
98 my $publicationyear = $input->param('publicationyear');
99 my $ordernumber = $input->param('ordernumber') || '';
100 our $biblionumber = $input->param('biblionumber');
101 our $basketno = $input->param('basketno');
102 my $suggestionid = $input->param('suggestionid');
103 my $close = $input->param('close');
104 my $uncertainprice = $input->param('uncertainprice');
105 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 !
106 my $subscriptionid = $input->param('subscriptionid');
107 my $data;
108 my $new = 'no';
110 my $budget_name;
112 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
114 template_name => "acqui/neworderempty.tt",
115 query => $input,
116 type => "intranet",
117 authnotrequired => 0,
118 flagsrequired => { acquisition => 'order_manage' },
119 debug => 1,
123 our $marcflavour = C4::Context->preference('marcflavour');
125 if(!$basketno) {
126 my $order = GetOrder($ordernumber);
127 $basketno = $order->{'basketno'};
130 our $basket = GetBasket($basketno);
131 $booksellerid = $basket->{booksellerid} unless $booksellerid;
132 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
134 my $contract = GetContract({
135 contractnumber => $basket->{contractnumber}
138 #simple parameters reading (all in one :-)
139 our $params = $input->Vars;
140 my $listprice=0; # the price, that can be in MARC record if we have one
141 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
142 #we want to import from the breeding reservoir (from a z3950 search)
143 my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
144 die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
146 # Remove all the items (952) from the imported record
147 foreach my $item ($marcrecord->field('952')) {
148 $marcrecord->delete_field($item);
151 my $duplicatetitle;
152 #look for duplicates
153 ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
154 if($biblionumber && !$input->param('use_external_source')) {
155 #if duplicate record found and user did not decide yet, first warn user
156 #and let him choose between using new record or existing record
157 Load_Duplicate($duplicatetitle);
158 exit;
160 #from this point: add a new record
161 if (C4::Context->preference("BiblioAddsAuthorities")){
162 my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
164 my $bibitemnum;
165 $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
166 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
167 # get the price if there is one.
168 $listprice = GetMarcPrice($marcrecord, $marcflavour);
169 SetImportRecordStatus($params->{'breedingid'}, 'imported');
174 my ( @order_user_ids, @order_users );
175 if ( $ordernumber eq '' ) { # create order
176 $new = 'yes';
178 # $ordernumber=newordernum;
179 if ( $biblionumber && !$suggestionid ) {
180 $data = GetBiblioData($biblionumber);
183 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
184 # otherwise, retrieve suggestion information.
185 if ($suggestionid) {
186 $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
187 $budget_id ||= $data->{'budgetid'} // 0;
190 else { #modify order
191 $data = GetOrder($ordernumber);
192 $biblionumber = $data->{'biblionumber'};
193 $budget_id = $data->{'budget_id'};
195 $basket = GetBasket( $data->{'basketno'} );
196 $basketno = $basket->{'basketno'};
198 @order_user_ids = GetOrderUsers($ordernumber);
199 foreach my $order_user_id (@order_user_ids) {
200 my $order_user = GetMember(borrowernumber => $order_user_id);
201 push @order_users, $order_user if $order_user;
205 my $suggestion;
206 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
208 # get currencies (for change rates calcs if needed)
209 my $active_currency = GetCurrency();
210 my $default_currency;
211 if (! $data->{currency} ) { # New order no currency set
212 if ( $bookseller->{listprice} ) {
213 $default_currency = $bookseller->{listprice};
215 else {
216 $default_currency = $active_currency->{currency};
220 my @rates = GetCurrencies();
222 # ## @rates
224 my @loop_currency = ();
225 for my $curr ( @rates ) {
226 my $selected;
227 if ($data->{currency} ) {
228 $selected = $curr->{currency} eq $data->{currency};
230 else {
231 $selected = $curr->{currency} eq $default_currency;
233 push @loop_currency, {
234 currcode => $curr->{currency},
235 rate => $curr->{rate},
236 selected => $selected,
240 # build branches list
241 my $onlymine =
242 C4::Context->preference('IndependentBranches')
243 && C4::Context->userenv
244 && !C4::Context->IsSuperLibrarian()
245 && C4::Context->userenv->{branch};
246 my $branches = GetBranches($onlymine);
247 my @branchloop;
248 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
249 my %row = (
250 value => $thisbranch,
251 branchname => $branches->{$thisbranch}->{'branchname'},
253 $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
254 push @branchloop, \%row;
256 $template->param( branchloop => \@branchloop );
258 # build bookfund list
259 my $borrower= GetMember('borrowernumber' => $loggedinuser);
260 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
262 my $budget = GetBudget($budget_id);
263 # build budget list
264 my $budget_loop = [];
265 my $budgets = GetBudgetHierarchy;
266 foreach my $r (@{$budgets}) {
267 next unless (CanUserUseBudget($borrower, $r, $userflags));
268 if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
269 next;
271 push @{$budget_loop}, {
272 b_id => $r->{budget_id},
273 b_txt => $r->{budget_name},
274 b_sort1_authcat => $r->{'sort1_authcat'},
275 b_sort2_authcat => $r->{'sort2_authcat'},
276 b_active => $r->{budget_period_active},
277 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
281 @{$budget_loop} =
282 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
284 if ($close) {
285 $budget_id = $data->{'budget_id'};
286 $budget_name = $budget->{'budget_name'};
290 $template->param( sort1 => $data->{'sort1'} );
291 $template->param( sort2 => $data->{'sort2'} );
293 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
294 # Check if ACQ framework exists
295 my $marc = GetMarcStructure(1, 'ACQ');
296 unless($marc) {
297 $template->param('NoACQframework' => 1);
299 $template->param(
300 AcqCreateItemOrdering => 1,
301 UniqueItemFields => C4::Context->preference('UniqueItemFields'),
304 # 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
305 my @itemtypes;
306 @itemtypes = C4::ItemType->all unless C4::Context->preference('item-level_itypes');
308 if ( defined $subscriptionid ) {
309 my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
310 if ( defined $lastOrderReceived ) {
311 $budget_id = $lastOrderReceived->{budgetid};
312 $data->{listprice} = $lastOrderReceived->{listprice};
313 $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
314 $data->{gstrate} = $lastOrderReceived->{gstrate};
315 $data->{discount} = $lastOrderReceived->{discount};
316 $data->{rrp} = $lastOrderReceived->{rrp};
317 $data->{ecost} = $lastOrderReceived->{ecost};
318 $data->{quantity} = $lastOrderReceived->{quantity};
319 $data->{unitprice} = $lastOrderReceived->{unitprice};
320 $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
321 $data->{order_vendornote} = $lastOrderReceived->{order_vendornote};
322 $data->{sort1} = $lastOrderReceived->{sort1};
323 $data->{sort2} = $lastOrderReceived->{sort2};
325 $basket = GetBasket( $input->param('basketno') );
329 # Find the items.barcode subfield for barcode validations
330 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
332 # fill template
333 $template->param(
334 close => $close,
335 budget_id => $budget_id,
336 budget_name => $budget_name
337 ) if ($close);
339 # get option values for gist syspref
340 my @gst_values = map {
341 option => $_ + 0.0
342 }, split( '\|', C4::Context->preference("gist") );
344 my $quantity = $input->param('rr_quantity_to_order') ?
345 $input->param('rr_quantity_to_order') :
346 $data->{'quantity'};
347 $quantity //= 0;
349 $template->param(
350 existing => $biblionumber,
351 ordernumber => $ordernumber,
352 # basket informations
353 basketno => $basketno,
354 basketname => $basket->{'basketname'},
355 basketnote => $basket->{'note'},
356 booksellerid => $basket->{'booksellerid'},
357 basketbooksellernote => $basket->{booksellernote},
358 basketcontractno => $basket->{contractnumber},
359 basketcontractname => $contract->{contractname},
360 creationdate => $basket->{creationdate},
361 authorisedby => $basket->{'authorisedby'},
362 authorisedbyname => $basket->{'authorisedbyname'},
363 closedate => $basket->{'closedate'},
364 # order details
365 suggestionid => $suggestion->{suggestionid},
366 surnamesuggestedby => $suggestion->{surnamesuggestedby},
367 firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
368 biblionumber => $biblionumber,
369 uncertainprice => $data->{'uncertainprice'},
370 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
371 discount => $bookseller->{'discount'},
372 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
373 orderdiscount => $data->{'discount'},
374 order_internalnote => $data->{'order_internalnote'},
375 order_vendornote => $data->{'order_vendornote'},
376 listincgst => $bookseller->{'listincgst'},
377 invoiceincgst => $bookseller->{'invoiceincgst'},
378 name => $bookseller->{'name'},
379 cur_active_sym => $active_currency->{'symbol'},
380 cur_active => $active_currency->{'currency'},
381 loop_currencies => \@loop_currency,
382 orderexists => ( $new eq 'yes' ) ? 0 : 1,
383 title => $data->{'title'},
384 author => $data->{'author'},
385 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
386 editionstatement => $data->{'editionstatement'},
387 budget_loop => $budget_loop,
388 isbn => $data->{'isbn'},
389 ean => $data->{'ean'},
390 seriestitle => $data->{'seriestitle'},
391 itemtypeloop => \@itemtypes,
392 quantity => $quantity,
393 quantityrec => $quantity,
394 rrp => $data->{'rrp'},
395 gst_values => \@gst_values,
396 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
397 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
398 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
399 ecost => sprintf( "%.2f", $data->{ecost} || 0),
400 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
401 publishercode => $data->{'publishercode'},
402 barcode_subfield => $barcode_subfield,
403 import_batch_id => $import_batch_id,
404 subscriptionid => $subscriptionid,
405 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
406 users_ids => join(':', @order_user_ids),
407 users => \@order_users,
408 (uc(C4::Context->preference("marcflavour"))) => 1
411 output_html_with_http_headers $input, $cookie, $template->output;
414 =head2 MARCfindbreeding
416 $record = MARCfindbreeding($breedingid);
418 Look up the import record repository for the record with
419 record with id $breedingid. If found, returns the decoded
420 MARC::Record; otherwise, -1 is returned (FIXME).
421 Returns as second parameter the character encoding.
423 =cut
425 sub MARCfindbreeding {
426 my ( $id ) = @_;
427 my ($marc, $encoding) = GetImportRecordMarc($id);
428 # remove the - in isbn, koha store isbn without any -
429 if ($marc) {
430 my $record = MARC::Record->new_from_usmarc($marc);
431 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
432 if ( $record->field($isbnfield) ) {
433 foreach my $field ( $record->field($isbnfield) ) {
434 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
435 my $newisbn = $field->subfield($isbnsubfield);
436 $newisbn =~ s/-//g;
437 $field->update( $isbnsubfield => $newisbn );
441 # fix the unimarc 100 coded field (with unicode information)
442 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
443 my $f100a=$record->subfield(100,'a');
444 my $f100 = $record->field(100);
445 my $f100temp = $f100->as_string;
446 $record->delete_field($f100);
447 if ( length($f100temp) > 28 ) {
448 substr( $f100temp, 26, 2, "50" );
449 $f100->update( 'a' => $f100temp );
450 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
451 $record->insert_fields_ordered($f100);
455 if ( !defined(ref($record)) ) {
456 return -1;
458 else {
459 # normalize author : probably UNIMARC specific...
460 if ( C4::Context->preference("z3950NormalizeAuthor")
461 and C4::Context->preference("z3950AuthorAuthFields") )
463 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
465 # my $summary = C4::Context->preference("z3950authortemplate");
466 my $auth_fields =
467 C4::Context->preference("z3950AuthorAuthFields");
468 my @auth_fields = split /,/, $auth_fields;
469 my $field;
471 if ( $record->field($tag) ) {
472 foreach my $tmpfield ( $record->field($tag)->subfields ) {
474 # foreach my $subfieldcode ($tmpfield->subfields){
475 my $subfieldcode = shift @$tmpfield;
476 my $subfieldvalue = shift @$tmpfield;
477 if ($field) {
478 $field->add_subfields(
479 "$subfieldcode" => $subfieldvalue )
480 if ( $subfieldcode ne $subfield );
482 else {
483 $field =
484 MARC::Field->new( $tag, "", "",
485 $subfieldcode => $subfieldvalue )
486 if ( $subfieldcode ne $subfield );
490 $record->delete_field( $record->field($tag) );
491 foreach my $fieldtag (@auth_fields) {
492 next unless ( $record->field($fieldtag) );
493 my $lastname = $record->field($fieldtag)->subfield('a');
494 my $firstname = $record->field($fieldtag)->subfield('b');
495 my $title = $record->field($fieldtag)->subfield('c');
496 my $number = $record->field($fieldtag)->subfield('d');
497 if ($title) {
499 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
500 $field->add_subfields(
501 "$subfield" => ucfirst($title) . " "
502 . ucfirst($firstname) . " "
503 . $number );
505 else {
507 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
508 $field->add_subfields(
509 "$subfield" => ucfirst($firstname) . ", "
510 . ucfirst($lastname) );
513 $record->insert_fields_ordered($field);
515 return $record, $encoding;
518 return -1;
521 sub Load_Duplicate {
522 my ($duplicatetitle)= @_;
523 ($template, $loggedinuser, $cookie) = get_template_and_user(
525 template_name => "acqui/neworderempty_duplicate.tt",
526 query => $input,
527 type => "intranet",
528 authnotrequired => 0,
529 flagsrequired => { acquisition => 'order_manage' },
530 # debug => 1,
534 $template->param(
535 biblionumber => $biblionumber,
536 basketno => $basketno,
537 booksellerid => $basket->{'booksellerid'},
538 breedingid => $params->{'breedingid'},
539 duplicatetitle => $duplicatetitle,
540 (uc(C4::Context->preference("marcflavour"))) => 1
543 output_html_with_http_headers $input, $cookie, $template->output;