Bug 13042 - Move budget action links into menu
[koha.git] / acqui / neworderempty.pl
blob256175a3fb68ca9cde4440faf5af59ef6120a957
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::Contract;
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/;
92 #needed for z3950 import:
93 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
95 our $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 $ordernumber = $input->param('ordernumber') || '';
102 our $biblionumber = $input->param('biblionumber');
103 our $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 $subscriptionid = $input->param('subscriptionid');
109 my $data;
110 my $new = 'no';
112 my $budget_name;
114 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
116 template_name => "acqui/neworderempty.tt",
117 query => $input,
118 type => "intranet",
119 authnotrequired => 0,
120 flagsrequired => { acquisition => 'order_manage' },
121 debug => 1,
125 our $marcflavour = C4::Context->preference('marcflavour');
127 if(!$basketno) {
128 my $order = GetOrder($ordernumber);
129 $basketno = $order->{'basketno'};
132 our $basket = GetBasket($basketno);
133 $booksellerid = $basket->{booksellerid} unless $booksellerid;
134 my $bookseller = GetBookSellerFromId($booksellerid);
136 my $contract = GetContract({
137 contractnumber => $basket->{contractnumber}
140 #simple parameters reading (all in one :-)
141 our $params = $input->Vars;
142 my $listprice=0; # the price, that can be in MARC record if we have one
143 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
144 #we want to import from the breeding reservoir (from a z3950 search)
145 my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
146 die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
148 # Remove all the items (952) from the imported record
149 foreach my $item ($marcrecord->field('952')) {
150 $marcrecord->delete_field($item);
153 my $duplicatetitle;
154 #look for duplicates
155 ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
156 if($biblionumber && !$input->param('use_external_source')) {
157 #if duplicate record found and user did not decide yet, first warn user
158 #and let him choose between using new record or existing record
159 Load_Duplicate($duplicatetitle);
160 exit;
162 #from this point: add a new record
163 if (C4::Context->preference("BiblioAddsAuthorities")){
164 my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
166 my $bibitemnum;
167 $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
168 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
169 # get the price if there is one.
170 $listprice = GetMarcPrice($marcrecord, $marcflavour);
171 SetImportRecordStatus($params->{'breedingid'}, 'imported');
176 if ( $ordernumber eq '' ) { # create order
177 $new = 'yes';
179 # $ordernumber=newordernum;
180 if ( $biblionumber && !$suggestionid ) {
181 $data = GetBiblioData($biblionumber);
184 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
185 # otherwise, retrieve suggestion information.
186 if ($suggestionid) {
187 $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
188 $budget_id ||= $data->{'budgetid'} // 0;
191 else { #modify order
192 $data = GetOrder($ordernumber);
193 $biblionumber = $data->{'biblionumber'};
194 $budget_id = $data->{'budget_id'};
196 $basket = GetBasket( $data->{'basketno'} );
197 $basketno = $basket->{'basketno'};
200 my $suggestion;
201 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
203 # get currencies (for change rates calcs if needed)
204 my $active_currency = GetCurrency();
205 my $default_currency;
206 if (! $data->{currency} ) { # New order no currency set
207 if ( $bookseller->{listprice} ) {
208 $default_currency = $bookseller->{listprice};
210 else {
211 $default_currency = $active_currency->{currency};
215 my @rates = GetCurrencies();
217 # ## @rates
219 my @loop_currency = ();
220 for my $curr ( @rates ) {
221 my $selected;
222 if ($data->{currency} ) {
223 $selected = $curr->{currency} eq $data->{currency};
225 else {
226 $selected = $curr->{currency} eq $default_currency;
228 push @loop_currency, {
229 currcode => $curr->{currency},
230 rate => $curr->{rate},
231 selected => $selected,
235 # build branches list
236 my $onlymine =
237 C4::Context->preference('IndependentBranches')
238 && C4::Context->userenv
239 && !C4::Context->IsSuperLibrarian()
240 && C4::Context->userenv->{branch};
241 my $branches = GetBranches($onlymine);
242 my @branchloop;
243 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
244 my %row = (
245 value => $thisbranch,
246 branchname => $branches->{$thisbranch}->{'branchname'},
248 $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
249 push @branchloop, \%row;
251 $template->param( branchloop => \@branchloop );
253 # build bookfund list
254 my $borrower= GetMember('borrowernumber' => $loggedinuser);
255 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
257 my $budget = GetBudget($budget_id);
258 # build budget list
259 my $budget_loop = [];
260 my $budgets = GetBudgetHierarchy;
261 foreach my $r (@{$budgets}) {
262 next unless (CanUserUseBudget($borrower, $r, $userflags));
263 if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
264 next;
266 push @{$budget_loop}, {
267 b_id => $r->{budget_id},
268 b_txt => $r->{budget_name},
269 b_sort1_authcat => $r->{'sort1_authcat'},
270 b_sort2_authcat => $r->{'sort2_authcat'},
271 b_active => $r->{budget_period_active},
272 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
276 @{$budget_loop} =
277 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
279 if ($close) {
280 $budget_id = $data->{'budget_id'};
281 $budget_name = $budget->{'budget_name'};
285 $template->param( sort1 => $data->{'sort1'} );
286 $template->param( sort2 => $data->{'sort2'} );
288 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
289 # Check if ACQ framework exists
290 my $marc = GetMarcStructure(1, 'ACQ');
291 unless($marc) {
292 $template->param('NoACQframework' => 1);
294 $template->param(
295 AcqCreateItemOrdering => 1,
296 UniqueItemFields => C4::Context->preference('UniqueItemFields'),
299 # 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
300 my @itemtypes;
301 @itemtypes = C4::ItemType->all unless C4::Context->preference('item-level_itypes');
303 if ( defined $subscriptionid ) {
304 my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
305 if ( defined $lastOrderReceived ) {
306 $budget_id = $lastOrderReceived->{budgetid};
307 $data->{listprice} = $lastOrderReceived->{listprice};
308 $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
309 $data->{gstrate} = $lastOrderReceived->{gstrate};
310 $data->{discount} = $lastOrderReceived->{discount};
311 $data->{rrp} = $lastOrderReceived->{rrp};
312 $data->{ecost} = $lastOrderReceived->{ecost};
313 $data->{quantity} = $lastOrderReceived->{quantity};
314 $data->{unitprice} = $lastOrderReceived->{unitprice};
315 $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
316 $data->{order_vendornote} = $lastOrderReceived->{order_vendornote};
317 $data->{sort1} = $lastOrderReceived->{sort1};
318 $data->{sort2} = $lastOrderReceived->{sort2};
320 $basket = GetBasket( $input->param('basketno') );
324 # Find the items.barcode subfield for barcode validations
325 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
327 # fill template
328 $template->param(
329 close => $close,
330 budget_id => $budget_id,
331 budget_name => $budget_name
332 ) if ($close);
334 # get option values for gist syspref
335 my @gst_values = map {
336 option => $_ + 0.0
337 }, split( '\|', C4::Context->preference("gist") );
339 my $quantity = $input->param('rr_quantity_to_order') ?
340 $input->param('rr_quantity_to_order') :
341 $data->{'quantity'};
342 $quantity //= 0;
344 $template->param(
345 existing => $biblionumber,
346 ordernumber => $ordernumber,
347 # basket informations
348 basketno => $basketno,
349 basketname => $basket->{'basketname'},
350 basketnote => $basket->{'note'},
351 booksellerid => $basket->{'booksellerid'},
352 basketbooksellernote => $basket->{booksellernote},
353 basketcontractno => $basket->{contractnumber},
354 basketcontractname => $contract->{contractname},
355 creationdate => $basket->{creationdate},
356 authorisedby => $basket->{'authorisedby'},
357 authorisedbyname => $basket->{'authorisedbyname'},
358 closedate => $basket->{'closedate'},
359 # order details
360 suggestionid => $suggestion->{suggestionid},
361 surnamesuggestedby => $suggestion->{surnamesuggestedby},
362 firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
363 biblionumber => $biblionumber,
364 uncertainprice => $data->{'uncertainprice'},
365 authorisedbyname => $borrower->{'firstname'} . " " . $borrower->{'surname'},
366 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
367 discount => $bookseller->{'discount'},
368 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
369 orderdiscount => $data->{'discount'},
370 order_internalnote => $data->{'order_internalnote'},
371 order_vendornote => $data->{'order_vendornote'},
372 listincgst => $bookseller->{'listincgst'},
373 invoiceincgst => $bookseller->{'invoiceincgst'},
374 name => $bookseller->{'name'},
375 cur_active_sym => $active_currency->{'symbol'},
376 cur_active => $active_currency->{'currency'},
377 loop_currencies => \@loop_currency,
378 orderexists => ( $new eq 'yes' ) ? 0 : 1,
379 title => $data->{'title'},
380 author => $data->{'author'},
381 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
382 editionstatement => $data->{'editionstatement'},
383 budget_loop => $budget_loop,
384 isbn => $data->{'isbn'},
385 ean => $data->{'ean'},
386 seriestitle => $data->{'seriestitle'},
387 itemtypeloop => \@itemtypes,
388 quantity => $quantity,
389 quantityrec => $quantity,
390 rrp => $data->{'rrp'},
391 gst_values => \@gst_values,
392 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
393 gstreg => $bookseller->{'gstreg'},
394 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
395 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
396 ecost => sprintf( "%.2f", $data->{ecost} || 0),
397 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
398 publishercode => $data->{'publishercode'},
399 barcode_subfield => $barcode_subfield,
400 import_batch_id => $import_batch_id,
401 subscriptionid => $subscriptionid,
402 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
403 (uc(C4::Context->preference("marcflavour"))) => 1
406 output_html_with_http_headers $input, $cookie, $template->output;
409 =head2 MARCfindbreeding
411 $record = MARCfindbreeding($breedingid);
413 Look up the import record repository for the record with
414 record with id $breedingid. If found, returns the decoded
415 MARC::Record; otherwise, -1 is returned (FIXME).
416 Returns as second parameter the character encoding.
418 =cut
420 sub MARCfindbreeding {
421 my ( $id ) = @_;
422 my ($marc, $encoding) = GetImportRecordMarc($id);
423 # remove the - in isbn, koha store isbn without any -
424 if ($marc) {
425 my $record = MARC::Record->new_from_usmarc($marc);
426 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
427 if ( $record->field($isbnfield) ) {
428 foreach my $field ( $record->field($isbnfield) ) {
429 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
430 my $newisbn = $field->subfield($isbnsubfield);
431 $newisbn =~ s/-//g;
432 $field->update( $isbnsubfield => $newisbn );
436 # fix the unimarc 100 coded field (with unicode information)
437 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
438 my $f100a=$record->subfield(100,'a');
439 my $f100 = $record->field(100);
440 my $f100temp = $f100->as_string;
441 $record->delete_field($f100);
442 if ( length($f100temp) > 28 ) {
443 substr( $f100temp, 26, 2, "50" );
444 $f100->update( 'a' => $f100temp );
445 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
446 $record->insert_fields_ordered($f100);
450 if ( !defined(ref($record)) ) {
451 return -1;
453 else {
454 # normalize author : probably UNIMARC specific...
455 if ( C4::Context->preference("z3950NormalizeAuthor")
456 and C4::Context->preference("z3950AuthorAuthFields") )
458 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
460 # my $summary = C4::Context->preference("z3950authortemplate");
461 my $auth_fields =
462 C4::Context->preference("z3950AuthorAuthFields");
463 my @auth_fields = split /,/, $auth_fields;
464 my $field;
466 if ( $record->field($tag) ) {
467 foreach my $tmpfield ( $record->field($tag)->subfields ) {
469 # foreach my $subfieldcode ($tmpfield->subfields){
470 my $subfieldcode = shift @$tmpfield;
471 my $subfieldvalue = shift @$tmpfield;
472 if ($field) {
473 $field->add_subfields(
474 "$subfieldcode" => $subfieldvalue )
475 if ( $subfieldcode ne $subfield );
477 else {
478 $field =
479 MARC::Field->new( $tag, "", "",
480 $subfieldcode => $subfieldvalue )
481 if ( $subfieldcode ne $subfield );
485 $record->delete_field( $record->field($tag) );
486 foreach my $fieldtag (@auth_fields) {
487 next unless ( $record->field($fieldtag) );
488 my $lastname = $record->field($fieldtag)->subfield('a');
489 my $firstname = $record->field($fieldtag)->subfield('b');
490 my $title = $record->field($fieldtag)->subfield('c');
491 my $number = $record->field($fieldtag)->subfield('d');
492 if ($title) {
494 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
495 $field->add_subfields(
496 "$subfield" => ucfirst($title) . " "
497 . ucfirst($firstname) . " "
498 . $number );
500 else {
502 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
503 $field->add_subfields(
504 "$subfield" => ucfirst($firstname) . ", "
505 . ucfirst($lastname) );
508 $record->insert_fields_ordered($field);
510 return $record, $encoding;
513 return -1;
516 sub Load_Duplicate {
517 my ($duplicatetitle)= @_;
518 ($template, $loggedinuser, $cookie) = get_template_and_user(
520 template_name => "acqui/neworderempty_duplicate.tt",
521 query => $input,
522 type => "intranet",
523 authnotrequired => 0,
524 flagsrequired => { acquisition => 'order_manage' },
525 # debug => 1,
529 $template->param(
530 biblionumber => $biblionumber,
531 basketno => $basketno,
532 booksellerid => $basket->{'booksellerid'},
533 breedingid => $params->{'breedingid'},
534 duplicatetitle => $duplicatetitle,
535 (uc(C4::Context->preference("marcflavour"))) => 1
538 output_html_with_http_headers $input, $cookie, $template->output;