Bug 7677 - Remove atomic update
[koha.git] / acqui / neworderempty.pl
blob9045539d3b53af4035f1c4c1ef314f9a54f0fb15
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::Members;
85 use C4::Search qw/FindDuplicate/;
87 #needed for z3950 import:
88 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
90 use Koha::Acquisition::Bookseller;
91 use Koha::Acquisition::Currencies;
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 my @currencies = Koha::Acquisition::Currencies->search;
210 my $active_currency = Koha::Acquisition::Currencies->get_active;
212 # build bookfund list
213 my $borrower= GetMember('borrowernumber' => $loggedinuser);
214 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
216 my $budget = GetBudget($budget_id);
217 # build budget list
218 my $budget_loop = [];
219 my $budgets = GetBudgetHierarchy;
220 foreach my $r (@{$budgets}) {
221 next unless (CanUserUseBudget($borrower, $r, $userflags));
222 if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
223 next;
225 push @{$budget_loop}, {
226 b_id => $r->{budget_id},
227 b_txt => $r->{budget_name},
228 b_sort1_authcat => $r->{'sort1_authcat'},
229 b_sort2_authcat => $r->{'sort2_authcat'},
230 b_active => $r->{budget_period_active},
231 b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
235 @{$budget_loop} =
236 sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
238 if ($close) {
239 $budget_id = $data->{'budget_id'};
240 $budget_name = $budget->{'budget_name'};
244 $template->param( sort1 => $data->{'sort1'} );
245 $template->param( sort2 => $data->{'sort2'} );
247 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
248 # Check if ACQ framework exists
249 my $marc = GetMarcStructure(1, 'ACQ', { unsafe => 1 } );
250 unless($marc) {
251 $template->param('NoACQframework' => 1);
253 $template->param(
254 AcqCreateItemOrdering => 1,
255 UniqueItemFields => C4::Context->preference('UniqueItemFields'),
258 # 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
259 my @itemtypes;
260 @itemtypes = Koha::ItemTypes->search unless C4::Context->preference('item-level_itypes');
262 if ( defined $subscriptionid ) {
263 my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
264 if ( defined $lastOrderReceived ) {
265 $budget_id = $lastOrderReceived->{budgetid};
266 $data->{listprice} = $lastOrderReceived->{listprice};
267 $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
268 $data->{gstrate} = $lastOrderReceived->{gstrate};
269 $data->{discount} = $lastOrderReceived->{discount};
270 $data->{rrp} = $lastOrderReceived->{rrp};
271 $data->{ecost} = $lastOrderReceived->{ecost};
272 $data->{quantity} = $lastOrderReceived->{quantity};
273 $data->{unitprice} = $lastOrderReceived->{unitprice};
274 $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
275 $data->{order_vendornote} = $lastOrderReceived->{order_vendornote};
276 $data->{sort1} = $lastOrderReceived->{sort1};
277 $data->{sort2} = $lastOrderReceived->{sort2};
279 $basket = GetBasket( $input->param('basketno') );
283 # Find the items.barcode subfield for barcode validations
284 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
286 # fill template
287 $template->param(
288 close => $close,
289 budget_id => $budget_id,
290 budget_name => $budget_name
291 ) if ($close);
293 # get option values for gist syspref
294 my @gst_values = map {
295 option => $_ + 0.0
296 }, split( '\|', C4::Context->preference("gist") );
298 my $quantity = $input->param('rr_quantity_to_order') ?
299 $input->param('rr_quantity_to_order') :
300 $data->{'quantity'};
301 $quantity //= 0;
303 $template->param(
304 existing => $biblionumber,
305 ordernumber => $ordernumber,
306 # basket informations
307 basketno => $basketno,
308 basket => $basket,
309 basketname => $basket->{'basketname'},
310 basketnote => $basket->{'note'},
311 booksellerid => $basket->{'booksellerid'},
312 basketbooksellernote => $basket->{booksellernote},
313 basketcontractno => $basket->{contractnumber},
314 basketcontractname => $contract->{contractname},
315 creationdate => $basket->{creationdate},
316 authorisedby => $basket->{'authorisedby'},
317 authorisedbyname => $basket->{'authorisedbyname'},
318 closedate => $basket->{'closedate'},
319 # order details
320 suggestionid => $suggestion->{suggestionid},
321 surnamesuggestedby => $suggestion->{surnamesuggestedby},
322 firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
323 biblionumber => $biblionumber,
324 uncertainprice => $data->{'uncertainprice'},
325 discount_2dp => sprintf( "%.2f", $bookseller->{'discount'} ) , # for display
326 discount => $bookseller->{'discount'},
327 orderdiscount_2dp => sprintf( "%.2f", $data->{'discount'} || 0 ),
328 orderdiscount => $data->{'discount'},
329 order_internalnote => $data->{'order_internalnote'},
330 order_vendornote => $data->{'order_vendornote'},
331 listincgst => $bookseller->{'listincgst'},
332 invoiceincgst => $bookseller->{'invoiceincgst'},
333 name => $bookseller->{'name'},
334 cur_active_sym => $active_currency->symbol,
335 cur_active => $active_currency->currency,
336 currencies => \@currencies,
337 currency => $data->{currency},
338 vendor_currency => $bookseller->{listprice},
339 orderexists => ( $new eq 'yes' ) ? 0 : 1,
340 title => $data->{'title'},
341 author => $data->{'author'},
342 publicationyear => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
343 editionstatement => $data->{'editionstatement'},
344 budget_loop => $budget_loop,
345 isbn => $data->{'isbn'},
346 ean => $data->{'ean'},
347 seriestitle => $data->{'seriestitle'},
348 itemtypeloop => \@itemtypes,
349 quantity => $quantity,
350 quantityrec => $quantity,
351 rrp => $data->{'rrp'},
352 gst_values => \@gst_values,
353 gstrate => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
354 listprice => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
355 total => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
356 ecost => sprintf( "%.2f", $data->{ecost} || 0),
357 unitprice => sprintf( "%.2f", $data->{unitprice} || 0),
358 publishercode => $data->{'publishercode'},
359 barcode_subfield => $barcode_subfield,
360 import_batch_id => $import_batch_id,
361 subscriptionid => $subscriptionid,
362 acqcreate => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
363 users_ids => join(':', @order_user_ids),
364 users => \@order_users,
365 (uc(C4::Context->preference("marcflavour"))) => 1
368 output_html_with_http_headers $input, $cookie, $template->output;
371 =head2 MARCfindbreeding
373 $record = MARCfindbreeding($breedingid);
375 Look up the import record repository for the record with
376 record with id $breedingid. If found, returns the decoded
377 MARC::Record; otherwise, -1 is returned (FIXME).
378 Returns as second parameter the character encoding.
380 =cut
382 sub MARCfindbreeding {
383 my ( $id ) = @_;
384 my ($marc, $encoding) = GetImportRecordMarc($id);
385 # remove the - in isbn, koha store isbn without any -
386 if ($marc) {
387 my $record = MARC::Record->new_from_usmarc($marc);
388 my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
389 if ( $record->field($isbnfield) ) {
390 foreach my $field ( $record->field($isbnfield) ) {
391 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
392 my $newisbn = $field->subfield($isbnsubfield);
393 $newisbn =~ s/-//g;
394 $field->update( $isbnsubfield => $newisbn );
398 # fix the unimarc 100 coded field (with unicode information)
399 if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
400 my $f100a=$record->subfield(100,'a');
401 my $f100 = $record->field(100);
402 my $f100temp = $f100->as_string;
403 $record->delete_field($f100);
404 if ( length($f100temp) > 28 ) {
405 substr( $f100temp, 26, 2, "50" );
406 $f100->update( 'a' => $f100temp );
407 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
408 $record->insert_fields_ordered($f100);
412 if ( !defined(ref($record)) ) {
413 return -1;
415 else {
416 # normalize author : probably UNIMARC specific...
417 if ( C4::Context->preference("z3950NormalizeAuthor")
418 and C4::Context->preference("z3950AuthorAuthFields") )
420 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
422 # my $summary = C4::Context->preference("z3950authortemplate");
423 my $auth_fields =
424 C4::Context->preference("z3950AuthorAuthFields");
425 my @auth_fields = split /,/, $auth_fields;
426 my $field;
428 if ( $record->field($tag) ) {
429 foreach my $tmpfield ( $record->field($tag)->subfields ) {
431 # foreach my $subfieldcode ($tmpfield->subfields){
432 my $subfieldcode = shift @$tmpfield;
433 my $subfieldvalue = shift @$tmpfield;
434 if ($field) {
435 $field->add_subfields(
436 "$subfieldcode" => $subfieldvalue )
437 if ( $subfieldcode ne $subfield );
439 else {
440 $field =
441 MARC::Field->new( $tag, "", "",
442 $subfieldcode => $subfieldvalue )
443 if ( $subfieldcode ne $subfield );
447 $record->delete_field( $record->field($tag) );
448 foreach my $fieldtag (@auth_fields) {
449 next unless ( $record->field($fieldtag) );
450 my $lastname = $record->field($fieldtag)->subfield('a');
451 my $firstname = $record->field($fieldtag)->subfield('b');
452 my $title = $record->field($fieldtag)->subfield('c');
453 my $number = $record->field($fieldtag)->subfield('d');
454 if ($title) {
456 # $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
457 $field->add_subfields(
458 "$subfield" => ucfirst($title) . " "
459 . ucfirst($firstname) . " "
460 . $number );
462 else {
464 # $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
465 $field->add_subfields(
466 "$subfield" => ucfirst($firstname) . ", "
467 . ucfirst($lastname) );
470 $record->insert_fields_ordered($field);
472 return $record, $encoding;
475 return -1;
478 sub Load_Duplicate {
479 my ($duplicatetitle)= @_;
480 ($template, $loggedinuser, $cookie) = get_template_and_user(
482 template_name => "acqui/neworderempty_duplicate.tt",
483 query => $input,
484 type => "intranet",
485 authnotrequired => 0,
486 flagsrequired => { acquisition => 'order_manage' },
487 # debug => 1,
491 $template->param(
492 biblionumber => $biblionumber,
493 basketno => $basketno,
494 booksellerid => $basket->{'booksellerid'},
495 breedingid => $params->{'breedingid'},
496 duplicatetitle => $duplicatetitle,
497 (uc(C4::Context->preference("marcflavour"))) => 1
500 output_html_with_http_headers $input, $cookie, $template->output;