Bumping version number for release
[koha.git] / acqui / neworderempty.pl
blobacf96951ba1cd6331f2d05563090242e8dcdb6d3
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;
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 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
366 discount => $bookseller->{'discount'},
367 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
368 orderdiscount => $data->{'discount'},
369 order_internalnote => $data->{'order_internalnote'},
370 order_vendornote => $data->{'order_vendornote'},
371 listincgst => $bookseller->{'listincgst'},
372 invoiceincgst => $bookseller->{'invoiceincgst'},
373 name => $bookseller->{'name'},
374 cur_active_sym => $active_currency->{'symbol'},
375 cur_active => $active_currency->{'currency'},
376 loop_currencies => \@loop_currency,
377 orderexists => ( $new eq 'yes' ) ? 0 : 1,
378 title => $data->{'title'},
379 author => $data->{'author'},
380 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
381 editionstatement => $data->{'editionstatement'},
382 budget_loop => $budget_loop,
383 isbn => $data->{'isbn'},
384 ean => $data->{'ean'},
385 seriestitle => $data->{'seriestitle'},
386 itemtypeloop => \@itemtypes,
387 quantity => $quantity,
388 quantityrec => $quantity,
389 rrp => $data->{'rrp'},
390 gst_values => \@gst_values,
391 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
392 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
393 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
394 ecost => sprintf( "%.2f", $data->{ecost} || 0),
395 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
396 publishercode => $data->{'publishercode'},
397 barcode_subfield => $barcode_subfield,
398 import_batch_id => $import_batch_id,
399 subscriptionid => $subscriptionid,
400 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
401 (uc(C4::Context->preference("marcflavour"))) => 1
404 output_html_with_http_headers $input, $cookie, $template->output;
407 =head2 MARCfindbreeding
409 $record = MARCfindbreeding($breedingid);
411 Look up the import record repository for the record with
412 record with id $breedingid. If found, returns the decoded
413 MARC::Record; otherwise, -1 is returned (FIXME).
414 Returns as second parameter the character encoding.
416 =cut
418 sub MARCfindbreeding {
419 my ( $id ) = @_;
420 my ($marc, $encoding) = GetImportRecordMarc($id);
421 # remove the - in isbn, koha store isbn without any -
422 if ($marc) {
423 my $record = MARC::Record->new_from_usmarc($marc);
424 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
425 if ( $record->field($isbnfield) ) {
426 foreach my $field ( $record->field($isbnfield) ) {
427 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
428 my $newisbn = $field->subfield($isbnsubfield);
429 $newisbn =~ s/-//g;
430 $field->update( $isbnsubfield => $newisbn );
434 # fix the unimarc 100 coded field (with unicode information)
435 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
436 my $f100a=$record->subfield(100,'a');
437 my $f100 = $record->field(100);
438 my $f100temp = $f100->as_string;
439 $record->delete_field($f100);
440 if ( length($f100temp) > 28 ) {
441 substr( $f100temp, 26, 2, "50" );
442 $f100->update( 'a' => $f100temp );
443 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
444 $record->insert_fields_ordered($f100);
448 if ( !defined(ref($record)) ) {
449 return -1;
451 else {
452 # normalize author : probably UNIMARC specific...
453 if ( C4::Context->preference("z3950NormalizeAuthor")
454 and C4::Context->preference("z3950AuthorAuthFields") )
456 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
458 # my $summary = C4::Context->preference("z3950authortemplate");
459 my $auth_fields =
460 C4::Context->preference("z3950AuthorAuthFields");
461 my @auth_fields = split /,/, $auth_fields;
462 my $field;
464 if ( $record->field($tag) ) {
465 foreach my $tmpfield ( $record->field($tag)->subfields ) {
467 # foreach my $subfieldcode ($tmpfield->subfields){
468 my $subfieldcode = shift @$tmpfield;
469 my $subfieldvalue = shift @$tmpfield;
470 if ($field) {
471 $field->add_subfields(
472 "$subfieldcode" => $subfieldvalue )
473 if ( $subfieldcode ne $subfield );
475 else {
476 $field =
477 MARC::Field->new( $tag, "", "",
478 $subfieldcode => $subfieldvalue )
479 if ( $subfieldcode ne $subfield );
483 $record->delete_field( $record->field($tag) );
484 foreach my $fieldtag (@auth_fields) {
485 next unless ( $record->field($fieldtag) );
486 my $lastname = $record->field($fieldtag)->subfield('a');
487 my $firstname = $record->field($fieldtag)->subfield('b');
488 my $title = $record->field($fieldtag)->subfield('c');
489 my $number = $record->field($fieldtag)->subfield('d');
490 if ($title) {
492 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
493 $field->add_subfields(
494 "$subfield" => ucfirst($title) . " "
495 . ucfirst($firstname) . " "
496 . $number );
498 else {
500 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
501 $field->add_subfields(
502 "$subfield" => ucfirst($firstname) . ", "
503 . ucfirst($lastname) );
506 $record->insert_fields_ordered($field);
508 return $record, $encoding;
511 return -1;
514 sub Load_Duplicate {
515 my ($duplicatetitle)= @_;
516 ($template, $loggedinuser, $cookie) = get_template_and_user(
518 template_name => "acqui/neworderempty_duplicate.tt",
519 query => $input,
520 type => "intranet",
521 authnotrequired => 0,
522 flagsrequired => { acquisition => 'order_manage' },
523 # debug => 1,
527 $template->param(
528 biblionumber => $biblionumber,
529 basketno => $basketno,
530 booksellerid => $basket->{'booksellerid'},
531 breedingid => $params->{'breedingid'},
532 duplicatetitle => $duplicatetitle,
533 (uc(C4::Context->preference("marcflavour"))) => 1
536 output_html_with_http_headers $input, $cookie, $template->output;