Bug 10773 - Add item-level descriptions for Label Printing
[koha.git] / acqui / neworderempty.pl
blob2966e8e77b485e14e9a3fb5af7f2ef5eecc3abbc
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 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 authorisedbyname => $borrower->{'firstname'} . " " . $borrower->{'surname'},
374 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
375 discount => $bookseller->{'discount'},
376 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
377 orderdiscount => $data->{'discount'},
378 order_internalnote => $data->{'order_internalnote'},
379 order_vendornote => $data->{'order_vendornote'},
380 listincgst => $bookseller->{'listincgst'},
381 invoiceincgst => $bookseller->{'invoiceincgst'},
382 name => $bookseller->{'name'},
383 cur_active_sym => $active_currency->{'symbol'},
384 cur_active => $active_currency->{'currency'},
385 loop_currencies => \@loop_currency,
386 orderexists => ( $new eq 'yes' ) ? 0 : 1,
387 title => $data->{'title'},
388 author => $data->{'author'},
389 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
390 editionstatement => $data->{'editionstatement'},
391 budget_loop => $budget_loop,
392 isbn => $data->{'isbn'},
393 ean => $data->{'ean'},
394 seriestitle => $data->{'seriestitle'},
395 itemtypeloop => \@itemtypes,
396 quantity => $quantity,
397 quantityrec => $quantity,
398 rrp => $data->{'rrp'},
399 gst_values => \@gst_values,
400 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
401 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
402 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
403 ecost => sprintf( "%.2f", $data->{ecost} || 0),
404 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
405 publishercode => $data->{'publishercode'},
406 barcode_subfield => $barcode_subfield,
407 import_batch_id => $import_batch_id,
408 subscriptionid => $subscriptionid,
409 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
410 users_ids => join(':', @order_user_ids),
411 users => \@order_users,
412 (uc(C4::Context->preference("marcflavour"))) => 1
415 output_html_with_http_headers $input, $cookie, $template->output;
418 =head2 MARCfindbreeding
420 $record = MARCfindbreeding($breedingid);
422 Look up the import record repository for the record with
423 record with id $breedingid. If found, returns the decoded
424 MARC::Record; otherwise, -1 is returned (FIXME).
425 Returns as second parameter the character encoding.
427 =cut
429 sub MARCfindbreeding {
430 my ( $id ) = @_;
431 my ($marc, $encoding) = GetImportRecordMarc($id);
432 # remove the - in isbn, koha store isbn without any -
433 if ($marc) {
434 my $record = MARC::Record->new_from_usmarc($marc);
435 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
436 if ( $record->field($isbnfield) ) {
437 foreach my $field ( $record->field($isbnfield) ) {
438 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
439 my $newisbn = $field->subfield($isbnsubfield);
440 $newisbn =~ s/-//g;
441 $field->update( $isbnsubfield => $newisbn );
445 # fix the unimarc 100 coded field (with unicode information)
446 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
447 my $f100a=$record->subfield(100,'a');
448 my $f100 = $record->field(100);
449 my $f100temp = $f100->as_string;
450 $record->delete_field($f100);
451 if ( length($f100temp) > 28 ) {
452 substr( $f100temp, 26, 2, "50" );
453 $f100->update( 'a' => $f100temp );
454 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
455 $record->insert_fields_ordered($f100);
459 if ( !defined(ref($record)) ) {
460 return -1;
462 else {
463 # normalize author : probably UNIMARC specific...
464 if ( C4::Context->preference("z3950NormalizeAuthor")
465 and C4::Context->preference("z3950AuthorAuthFields") )
467 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
469 # my $summary = C4::Context->preference("z3950authortemplate");
470 my $auth_fields =
471 C4::Context->preference("z3950AuthorAuthFields");
472 my @auth_fields = split /,/, $auth_fields;
473 my $field;
475 if ( $record->field($tag) ) {
476 foreach my $tmpfield ( $record->field($tag)->subfields ) {
478 # foreach my $subfieldcode ($tmpfield->subfields){
479 my $subfieldcode = shift @$tmpfield;
480 my $subfieldvalue = shift @$tmpfield;
481 if ($field) {
482 $field->add_subfields(
483 "$subfieldcode" => $subfieldvalue )
484 if ( $subfieldcode ne $subfield );
486 else {
487 $field =
488 MARC::Field->new( $tag, "", "",
489 $subfieldcode => $subfieldvalue )
490 if ( $subfieldcode ne $subfield );
494 $record->delete_field( $record->field($tag) );
495 foreach my $fieldtag (@auth_fields) {
496 next unless ( $record->field($fieldtag) );
497 my $lastname = $record->field($fieldtag)->subfield('a');
498 my $firstname = $record->field($fieldtag)->subfield('b');
499 my $title = $record->field($fieldtag)->subfield('c');
500 my $number = $record->field($fieldtag)->subfield('d');
501 if ($title) {
503 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
504 $field->add_subfields(
505 "$subfield" => ucfirst($title) . " "
506 . ucfirst($firstname) . " "
507 . $number );
509 else {
511 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
512 $field->add_subfields(
513 "$subfield" => ucfirst($firstname) . ", "
514 . ucfirst($lastname) );
517 $record->insert_fields_ordered($field);
519 return $record, $encoding;
522 return -1;
525 sub Load_Duplicate {
526 my ($duplicatetitle)= @_;
527 ($template, $loggedinuser, $cookie) = get_template_and_user(
529 template_name => "acqui/neworderempty_duplicate.tt",
530 query => $input,
531 type => "intranet",
532 authnotrequired => 0,
533 flagsrequired => { acquisition => 'order_manage' },
534 # debug => 1,
538 $template->param(
539 biblionumber => $biblionumber,
540 basketno => $basketno,
541 booksellerid => $basket->{'booksellerid'},
542 breedingid => $params->{'breedingid'},
543 duplicatetitle => $duplicatetitle,
544 (uc(C4::Context->preference("marcflavour"))) => 1
547 output_html_with_http_headers $input, $cookie, $template->output;