Bug 15411: DBrev 3.23.000.019
[koha.git] / acqui / neworderempty.pl
blobefd6648057c0d33e6c393aa5e8453fc001e04707
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;
92 use Koha::ItemTypes;
94 our $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 $ordernumber = $input->param('ordernumber') || '';
101 our $biblionumber = $input->param('biblionumber');
102 our $basketno = $input->param('basketno');
103 my $suggestionid = $input->param('suggestionid');
104 my $close = $input->param('close');
105 my $uncertainprice = $input->param('uncertainprice');
106 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 !
107 my $subscriptionid = $input->param('subscriptionid');
108 my $data;
109 my $new = 'no';
111 my $budget_name;
113 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
115 template_name => "acqui/neworderempty.tt",
116 query => $input,
117 type => "intranet",
118 authnotrequired => 0,
119 flagsrequired => { acquisition => 'order_manage' },
120 debug => 1,
124 our $marcflavour = C4::Context->preference('marcflavour');
126 if(!$basketno) {
127 my $order = GetOrder($ordernumber);
128 $basketno = $order->{'basketno'};
131 our $basket = GetBasket($basketno);
132 $booksellerid = $basket->{booksellerid} unless $booksellerid;
133 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
135 my $contract = GetContract({
136 contractnumber => $basket->{contractnumber}
139 #simple parameters reading (all in one :-)
140 our $params = $input->Vars;
141 my $listprice=0; # the price, that can be in MARC record if we have one
142 if ( $ordernumber eq '' and defined $params->{'breedingid'}){
143 #we want to import from the breeding reservoir (from a z3950 search)
144 my ($marcrecord, $encoding) = MARCfindbreeding($params->{'breedingid'});
145 die("Could not find the selected record in the reservoir, bailing") unless $marcrecord;
147 # Remove all the items (952) from the imported record
148 foreach my $item ($marcrecord->field('952')) {
149 $marcrecord->delete_field($item);
152 my $duplicatetitle;
153 #look for duplicates
154 ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord);
155 if($biblionumber && !$input->param('use_external_source')) {
156 #if duplicate record found and user did not decide yet, first warn user
157 #and let him choose between using new record or existing record
158 Load_Duplicate($duplicatetitle);
159 exit;
161 #from this point: add a new record
162 if (C4::Context->preference("BiblioAddsAuthorities")){
163 my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
165 my $bibitemnum;
166 $params->{'frameworkcode'} or $params->{'frameworkcode'} = "";
167 ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $params->{'frameworkcode'} );
168 # get the price if there is one.
169 $listprice = GetMarcPrice($marcrecord, $marcflavour);
170 SetImportRecordStatus($params->{'breedingid'}, 'imported');
175 my ( @order_user_ids, @order_users );
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'};
199 @order_user_ids = GetOrderUsers($ordernumber);
200 foreach my $order_user_id (@order_user_ids) {
201 my $order_user = GetMember(borrowernumber => $order_user_id);
202 push @order_users, $order_user if $order_user;
206 my $suggestion;
207 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
209 # get currencies (for change rates calcs if needed)
210 my $active_currency = GetCurrency();
211 my $default_currency;
212 if (! $data->{currency} ) { # New order no currency set
213 if ( $bookseller->{listprice} ) {
214 $default_currency = $bookseller->{listprice};
216 else {
217 $default_currency = $active_currency->{currency};
221 my @rates = GetCurrencies();
223 # ## @rates
225 my @loop_currency = ();
226 for my $curr ( @rates ) {
227 my $selected;
228 if ($data->{currency} ) {
229 $selected = $curr->{currency} eq $data->{currency};
231 else {
232 $selected = $curr->{currency} eq $default_currency;
234 push @loop_currency, {
235 currcode => $curr->{currency},
236 rate => $curr->{rate},
237 selected => $selected,
241 # build branches list
242 my $onlymine =
243 C4::Context->preference('IndependentBranches')
244 && C4::Context->userenv
245 && !C4::Context->IsSuperLibrarian()
246 && C4::Context->userenv->{branch};
247 my $branches = GetBranches($onlymine);
248 my @branchloop;
249 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
250 my %row = (
251 value => $thisbranch,
252 branchname => $branches->{$thisbranch}->{'branchname'},
254 $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
255 push @branchloop, \%row;
257 $template->param( branchloop => \@branchloop );
259 # build bookfund list
260 my $borrower= GetMember('borrowernumber' => $loggedinuser);
261 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
263 my $budget = GetBudget($budget_id);
264 # build budget list
265 my $budget_loop = [];
266 my $budgets = GetBudgetHierarchy;
267 foreach my $r (@{$budgets}) {
268 next unless (CanUserUseBudget($borrower, $r, $userflags));
269 if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
270 next;
272 push @{$budget_loop}, {
273 b_id => $r->{budget_id},
274 b_txt => $r->{budget_name},
275 b_sort1_authcat => $r->{'sort1_authcat'},
276 b_sort2_authcat => $r->{'sort2_authcat'},
277 b_active => $r->{budget_period_active},
278 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
282 @{$budget_loop} =
283 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
285 if ($close) {
286 $budget_id = $data->{'budget_id'};
287 $budget_name = $budget->{'budget_name'};
291 $template->param( sort1 => $data->{'sort1'} );
292 $template->param( sort2 => $data->{'sort2'} );
294 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
295 # Check if ACQ framework exists
296 my $marc = GetMarcStructure(1, 'ACQ');
297 unless($marc) {
298 $template->param('NoACQframework' => 1);
300 $template->param(
301 AcqCreateItemOrdering => 1,
302 UniqueItemFields => C4::Context->preference('UniqueItemFields'),
305 # 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
306 my @itemtypes;
307 @itemtypes = Koha::ItemTypes->search unless C4::Context->preference('item-level_itypes');
309 if ( defined $subscriptionid ) {
310 my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
311 if ( defined $lastOrderReceived ) {
312 $budget_id = $lastOrderReceived->{budgetid};
313 $data->{listprice} = $lastOrderReceived->{listprice};
314 $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
315 $data->{gstrate} = $lastOrderReceived->{gstrate};
316 $data->{discount} = $lastOrderReceived->{discount};
317 $data->{rrp} = $lastOrderReceived->{rrp};
318 $data->{ecost} = $lastOrderReceived->{ecost};
319 $data->{quantity} = $lastOrderReceived->{quantity};
320 $data->{unitprice} = $lastOrderReceived->{unitprice};
321 $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
322 $data->{order_vendornote} = $lastOrderReceived->{order_vendornote};
323 $data->{sort1} = $lastOrderReceived->{sort1};
324 $data->{sort2} = $lastOrderReceived->{sort2};
326 $basket = GetBasket( $input->param('basketno') );
330 # Find the items.barcode subfield for barcode validations
331 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
333 # fill template
334 $template->param(
335 close => $close,
336 budget_id => $budget_id,
337 budget_name => $budget_name
338 ) if ($close);
340 # get option values for gist syspref
341 my @gst_values = map {
342 option => $_ + 0.0
343 }, split( '\|', C4::Context->preference("gist") );
345 my $quantity = $input->param('rr_quantity_to_order') ?
346 $input->param('rr_quantity_to_order') :
347 $data->{'quantity'};
348 $quantity //= 0;
350 $template->param(
351 existing => $biblionumber,
352 ordernumber => $ordernumber,
353 # basket informations
354 basketno => $basketno,
355 basketname => $basket->{'basketname'},
356 basketnote => $basket->{'note'},
357 booksellerid => $basket->{'booksellerid'},
358 basketbooksellernote => $basket->{booksellernote},
359 basketcontractno => $basket->{contractnumber},
360 basketcontractname => $contract->{contractname},
361 creationdate => $basket->{creationdate},
362 authorisedby => $basket->{'authorisedby'},
363 authorisedbyname => $basket->{'authorisedbyname'},
364 closedate => $basket->{'closedate'},
365 # order details
366 suggestionid => $suggestion->{suggestionid},
367 surnamesuggestedby => $suggestion->{surnamesuggestedby},
368 firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
369 biblionumber => $biblionumber,
370 uncertainprice => $data->{'uncertainprice'},
371 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
372 discount => $bookseller->{'discount'},
373 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
374 orderdiscount => $data->{'discount'},
375 order_internalnote => $data->{'order_internalnote'},
376 order_vendornote => $data->{'order_vendornote'},
377 listincgst => $bookseller->{'listincgst'},
378 invoiceincgst => $bookseller->{'invoiceincgst'},
379 name => $bookseller->{'name'},
380 cur_active_sym => $active_currency->{'symbol'},
381 cur_active => $active_currency->{'currency'},
382 loop_currencies => \@loop_currency,
383 orderexists => ( $new eq 'yes' ) ? 0 : 1,
384 title => $data->{'title'},
385 author => $data->{'author'},
386 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
387 editionstatement => $data->{'editionstatement'},
388 budget_loop => $budget_loop,
389 isbn => $data->{'isbn'},
390 ean => $data->{'ean'},
391 seriestitle => $data->{'seriestitle'},
392 itemtypeloop => \@itemtypes,
393 quantity => $quantity,
394 quantityrec => $quantity,
395 rrp => $data->{'rrp'},
396 gst_values => \@gst_values,
397 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
398 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
399 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
400 ecost => sprintf( "%.2f", $data->{ecost} || 0),
401 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
402 publishercode => $data->{'publishercode'},
403 barcode_subfield => $barcode_subfield,
404 import_batch_id => $import_batch_id,
405 subscriptionid => $subscriptionid,
406 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
407 users_ids => join(':', @order_user_ids),
408 users => \@order_users,
409 (uc(C4::Context->preference("marcflavour"))) => 1
412 output_html_with_http_headers $input, $cookie, $template->output;
415 =head2 MARCfindbreeding
417 $record = MARCfindbreeding($breedingid);
419 Look up the import record repository for the record with
420 record with id $breedingid. If found, returns the decoded
421 MARC::Record; otherwise, -1 is returned (FIXME).
422 Returns as second parameter the character encoding.
424 =cut
426 sub MARCfindbreeding {
427 my ( $id ) = @_;
428 my ($marc, $encoding) = GetImportRecordMarc($id);
429 # remove the - in isbn, koha store isbn without any -
430 if ($marc) {
431 my $record = MARC::Record->new_from_usmarc($marc);
432 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
433 if ( $record->field($isbnfield) ) {
434 foreach my $field ( $record->field($isbnfield) ) {
435 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
436 my $newisbn = $field->subfield($isbnsubfield);
437 $newisbn =~ s/-//g;
438 $field->update( $isbnsubfield => $newisbn );
442 # fix the unimarc 100 coded field (with unicode information)
443 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
444 my $f100a=$record->subfield(100,'a');
445 my $f100 = $record->field(100);
446 my $f100temp = $f100->as_string;
447 $record->delete_field($f100);
448 if ( length($f100temp) > 28 ) {
449 substr( $f100temp, 26, 2, "50" );
450 $f100->update( 'a' => $f100temp );
451 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
452 $record->insert_fields_ordered($f100);
456 if ( !defined(ref($record)) ) {
457 return -1;
459 else {
460 # normalize author : probably UNIMARC specific...
461 if ( C4::Context->preference("z3950NormalizeAuthor")
462 and C4::Context->preference("z3950AuthorAuthFields") )
464 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
466 # my $summary = C4::Context->preference("z3950authortemplate");
467 my $auth_fields =
468 C4::Context->preference("z3950AuthorAuthFields");
469 my @auth_fields = split /,/, $auth_fields;
470 my $field;
472 if ( $record->field($tag) ) {
473 foreach my $tmpfield ( $record->field($tag)->subfields ) {
475 # foreach my $subfieldcode ($tmpfield->subfields){
476 my $subfieldcode = shift @$tmpfield;
477 my $subfieldvalue = shift @$tmpfield;
478 if ($field) {
479 $field->add_subfields(
480 "$subfieldcode" => $subfieldvalue )
481 if ( $subfieldcode ne $subfield );
483 else {
484 $field =
485 MARC::Field->new( $tag, "", "",
486 $subfieldcode => $subfieldvalue )
487 if ( $subfieldcode ne $subfield );
491 $record->delete_field( $record->field($tag) );
492 foreach my $fieldtag (@auth_fields) {
493 next unless ( $record->field($fieldtag) );
494 my $lastname = $record->field($fieldtag)->subfield('a');
495 my $firstname = $record->field($fieldtag)->subfield('b');
496 my $title = $record->field($fieldtag)->subfield('c');
497 my $number = $record->field($fieldtag)->subfield('d');
498 if ($title) {
500 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
501 $field->add_subfields(
502 "$subfield" => ucfirst($title) . " "
503 . ucfirst($firstname) . " "
504 . $number );
506 else {
508 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
509 $field->add_subfields(
510 "$subfield" => ucfirst($firstname) . ", "
511 . ucfirst($lastname) );
514 $record->insert_fields_ordered($field);
516 return $record, $encoding;
519 return -1;
522 sub Load_Duplicate {
523 my ($duplicatetitle)= @_;
524 ($template, $loggedinuser, $cookie) = get_template_and_user(
526 template_name => "acqui/neworderempty_duplicate.tt",
527 query => $input,
528 type => "intranet",
529 authnotrequired => 0,
530 flagsrequired => { acquisition => 'order_manage' },
531 # debug => 1,
535 $template->param(
536 biblionumber => $biblionumber,
537 basketno => $basketno,
538 booksellerid => $basket->{'booksellerid'},
539 breedingid => $params->{'breedingid'},
540 duplicatetitle => $duplicatetitle,
541 (uc(C4::Context->preference("marcflavour"))) => 1
544 output_html_with_http_headers $input, $cookie, $template->output;