Bug 15685: Allow creation of items (AcqCreateItem) to be customizable per-basket
[koha.git] / acqui / neworderempty.pl
1 #!/usr/bin/perl
2
3 #script to show display basket of orders
4 #written by chris@katipo.co.nz 24/2/2000
5
6 # Copyright 2000-2002 Katipo Communications
7 #
8 # This file is part of Koha.
9 #
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.
14 #
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.
19 #
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>.
22
23
24 =head1 NAME
25
26 neworderempty.pl
27
28 =head1 DESCRIPTION
29
30 this script allows to create a new record to order it. This record shouldn't exist
31 on database.
32
33 =head1 CGI PARAMETERS
34
35 =over 4
36
37 =item booksellerid
38 the bookseller the librarian has to buy a new book.
39
40 =item title
41 the title of this new record.
42
43 =item author
44 the author of this new record.
45
46 =item publication year
47 the publication year of this new record.
48
49 =item ordernumber
50 the number of this order.
51
52 =item biblio
53
54 =item basketno
55 the basket number for this new order.
56
57 =item suggestionid
58 if this order comes from a suggestion.
59
60 =item breedingid
61 the item's id in the breeding reservoir
62
63 =item close
64
65 =back
66
67 =cut
68
69 use warnings;
70 use strict;
71 use CGI qw ( -utf8 );
72 use C4::Context;
73
74 use C4::Auth;
75 use C4::Budgets;
76
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/;
86
87 #needed for z3950 import:
88 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
89
90 use Koha::Acquisition::Booksellers;
91 use Koha::Acquisition::Currencies;
92 use Koha::ItemTypes;
93 use Koha::Patrons;
94
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';
111
112 my $budget_name;
113
114 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
115     {
116         template_name   => "acqui/neworderempty.tt",
117         query           => $input,
118         type            => "intranet",
119         authnotrequired => 0,
120         flagsrequired   => { acquisition => 'order_manage' },
121         debug           => 1,
122     }
123 );
124
125 our $marcflavour = C4::Context->preference('marcflavour');
126
127 if(!$basketno) {
128     my $order = GetOrder($ordernumber);
129     $basketno = $order->{'basketno'};
130 }
131
132 our $basket = GetBasket($basketno);
133 my $basketobj = Koha::Acquisition::Baskets->find( $basketno );
134 $booksellerid = $basket->{booksellerid} unless $booksellerid;
135 my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
136
137 my $contract = GetContract({
138     contractnumber => $basket->{contractnumber}
139 });
140
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;
148
149     # Remove all the items (952) from the imported record
150     foreach my $item ($marcrecord->field('952')) {
151         $marcrecord->delete_field($item);
152     }
153
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 them choose between using a new record or an existing record
160         Load_Duplicate($duplicatetitle);
161         exit;
162     }
163     #from this point: add a new record
164         if (C4::Context->preference("BiblioAddsAuthorities")){
165             my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
166         }
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');
173 }
174
175
176
177 my ( @order_user_ids, @order_users );
178 if ( $ordernumber eq '' ) {    # create order
179     $new = 'yes';
180
181     #   $ordernumber=newordernum;
182     if ( $biblionumber && !$suggestionid ) {
183         $data = GetBiblioData($biblionumber);
184     }
185
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;
191     }
192 }
193 else {    #modify order
194     $data   = GetOrder($ordernumber);
195     $biblionumber = $data->{'biblionumber'};
196     $budget_id = $data->{'budget_id'};
197
198     $basket   = GetBasket( $data->{'basketno'} );
199     $basketno = $basket->{'basketno'};
200
201     @order_user_ids = GetOrderUsers($ordernumber);
202     foreach my $order_user_id (@order_user_ids) {
203         # FIXME Could be improved with search -in
204         my $order_patron = Koha::Patrons->find( $order_user_id );
205         push @order_users, $order_patron if $order_patron;
206     }
207 }
208
209 my $suggestion;
210 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
211
212 my @currencies = Koha::Acquisition::Currencies->search;
213 my $active_currency = Koha::Acquisition::Currencies->get_active;
214
215 # build bookfund list
216 my $patron = Koha::Patrons->find( $loggedinuser )->unblessed;
217
218 my $budget =  GetBudget($budget_id);
219 # build budget list
220 my $budget_loop = [];
221 my $budgets = GetBudgetHierarchy;
222 foreach my $r (@{$budgets}) {
223     next unless (CanUserUseBudget($patron, $r, $userflags));
224     if (!defined $r->{budget_amount} || $r->{budget_amount} <0) {
225         next;
226     }
227     push @{$budget_loop}, {
228         b_id  => $r->{budget_id},
229         b_txt => $r->{budget_name},
230         b_sort1_authcat => $r->{'sort1_authcat'},
231         b_sort2_authcat => $r->{'sort2_authcat'},
232         b_active => $r->{budget_period_active},
233         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
234         b_level => $r->{budget_level},
235     };
236 }
237
238 if ($close) {
239     $budget_id      =  $data->{'budget_id'};
240     $budget_name    =   $budget->{'budget_name'};
241
242 }
243
244 $template->param( sort1 => $data->{'sort1'} );
245 $template->param( sort2 => $data->{'sort2'} );
246
247 if ($basketobj->effective_create_items 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);
252     }
253     $template->param(
254         AcqCreateItemOrdering => 1,
255         UniqueItemFields => C4::Context->preference('UniqueItemFields'),
256     );
257 }
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');
261
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->{tax_rate}       = $lastOrderReceived->{tax_rate_on_ordering};
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};
278
279         $basket = GetBasket( $input->param('basketno') );
280     }
281 }
282
283 # Find the items.barcode subfield for barcode validations
284 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
285
286 # fill template
287 $template->param(
288     close        => $close,
289     budget_id    => $budget_id,
290     budget_name  => $budget_name
291 ) if ($close);
292
293 # get option values for gist syspref
294 my @gst_values = map {
295     option => $_ + 0.0
296 }, split( '\|', C4::Context->preference("gist") );
297
298 my $quantity = $input->param('rr_quantity_to_order') ?
299       $input->param('rr_quantity_to_order') :
300       $data->{'quantity'};
301 $quantity //= 0;
302
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     tax_rate         => $data->{tax_rate_on_ordering} ? $data->{tax_rate_on_ordering}+0.0 : $bookseller->tax_rate ? $bookseller->tax_rate+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        => $basketobj->effective_create_items eq "ordering" ? 1 : "",
363     users_ids        => join(':', @order_user_ids),
364     users            => \@order_users,
365     (uc(C4::Context->preference("marcflavour"))) => 1
366 );
367
368 output_html_with_http_headers $input, $cookie, $template->output;
369
370
371 =head2 MARCfindbreeding
372
373   $record = MARCfindbreeding($breedingid);
374
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.
379
380 =cut
381
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 );
395                 }
396             }
397         }
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);
409             }
410         }
411         
412         if ( !defined(ref($record)) ) {
413             return -1;
414         }
415         else {
416             # normalize author : probably UNIMARC specific...
417             if (    C4::Context->preference("z3950NormalizeAuthor")
418                 and C4::Context->preference("z3950AuthorAuthFields") )
419             {
420                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
421
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;
427
428                 if ( $record->field($tag) ) {
429                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
430
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 );
438                         }
439                         else {
440                             $field =
441                             MARC::Field->new( $tag, "", "",
442                                 $subfieldcode => $subfieldvalue )
443                             if ( $subfieldcode ne $subfield );
444                         }
445                     }
446                 }
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) {
455
456 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
457                         $field->add_subfields(
458                                 "$subfield" => ucfirst($title) . " "
459                             . ucfirst($firstname) . " "
460                             . $number );
461                     }
462                     else {
463
464 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
465                         $field->add_subfields(
466                             "$subfield" => ucfirst($firstname) . ", "
467                             . ucfirst($lastname) );
468                     }
469                 }
470                 $record->insert_fields_ordered($field);
471             }
472             return $record, $encoding;
473         }
474     }
475     return -1;
476 }
477
478 sub Load_Duplicate {
479   my ($duplicatetitle)= @_;
480   ($template, $loggedinuser, $cookie) = get_template_and_user(
481     {
482         template_name   => "acqui/neworderempty_duplicate.tt",
483         query           => $input,
484         type            => "intranet",
485         authnotrequired => 0,
486         flagsrequired   => { acquisition => 'order_manage' },
487 #        debug           => 1,
488     }
489   );
490
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
498   );
499
500   output_html_with_http_headers $input, $cookie, $template->output;
501 }