Bug 15531: Add support for standing orders
[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::Branch;                 # GetBranches
85 use C4::Members;
86 use C4::Search qw/FindDuplicate/;
87
88 #needed for z3950 import:
89 use C4::ImportBatch qw/GetImportRecordMarc SetImportRecordStatus/;
90
91 use Koha::Acquisition::Bookseller;
92 use Koha::Acquisition::Currencies;
93 use Koha::ItemTypes;
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 $booksellerid = $basket->{booksellerid} unless $booksellerid;
134 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
135
136 my $contract = GetContract({
137     contractnumber => $basket->{contractnumber}
138 });
139
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;
147
148     # Remove all the items (952) from the imported record
149     foreach my $item ($marcrecord->field('952')) {
150         $marcrecord->delete_field($item);
151     }
152
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;
161     }
162     #from this point: add a new record
163         if (C4::Context->preference("BiblioAddsAuthorities")){
164             my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
165         }
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');
172 }
173
174
175
176 my ( @order_user_ids, @order_users );
177 if ( $ordernumber eq '' ) {    # create order
178     $new = 'yes';
179
180     #   $ordernumber=newordernum;
181     if ( $biblionumber && !$suggestionid ) {
182         $data = GetBiblioData($biblionumber);
183     }
184
185 # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists
186 # otherwise, retrieve suggestion information.
187     if ($suggestionid) {
188         $data = ($biblionumber) ? GetBiblioData($biblionumber) : GetSuggestion($suggestionid);
189         $budget_id ||= $data->{'budgetid'} // 0;
190     }
191 }
192 else {    #modify order
193     $data   = GetOrder($ordernumber);
194     $biblionumber = $data->{'biblionumber'};
195     $budget_id = $data->{'budget_id'};
196
197     $basket   = GetBasket( $data->{'basketno'} );
198     $basketno = $basket->{'basketno'};
199
200     @order_user_ids = GetOrderUsers($ordernumber);
201     foreach my $order_user_id (@order_user_ids) {
202         my $order_user = GetMember(borrowernumber => $order_user_id);
203         push @order_users, $order_user if $order_user;
204     }
205 }
206
207 my $suggestion;
208 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
209
210 my @currencies = Koha::Acquisition::Currencies->search;
211 my $active_currency = Koha::Acquisition::Currencies->get_active;
212
213 # build branches list
214 my $onlymine =
215      C4::Context->preference('IndependentBranches')
216   && C4::Context->userenv
217   && !C4::Context->IsSuperLibrarian()
218   && C4::Context->userenv->{branch};
219 my $branches = GetBranches($onlymine);
220 my @branchloop;
221 foreach my $thisbranch ( sort {$branches->{$a}->{'branchname'} cmp $branches->{$b}->{'branchname'}} keys %$branches ) {
222     my %row = (
223         value      => $thisbranch,
224         branchname => $branches->{$thisbranch}->{'branchname'},
225     );
226     $row{'selected'} = 1 if( $thisbranch && $data->{branchcode} && $thisbranch eq $data->{branchcode}) ;
227     push @branchloop, \%row;
228 }
229 $template->param( branchloop => \@branchloop );
230
231 # build bookfund list
232 my $borrower= GetMember('borrowernumber' => $loggedinuser);
233 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
234
235 my $budget =  GetBudget($budget_id);
236 # build budget list
237 my $budget_loop = [];
238 my $budgets = GetBudgetHierarchy;
239 foreach my $r (@{$budgets}) {
240     next unless (CanUserUseBudget($borrower, $r, $userflags));
241     if (!defined $r->{budget_amount} || $r->{budget_amount} == 0) {
242         next;
243     }
244     push @{$budget_loop}, {
245         b_id  => $r->{budget_id},
246         b_txt => $r->{budget_name},
247         b_sort1_authcat => $r->{'sort1_authcat'},
248         b_sort2_authcat => $r->{'sort2_authcat'},
249         b_active => $r->{budget_period_active},
250         b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0,
251     };
252 }
253
254 @{$budget_loop} =
255   sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop};
256
257 if ($close) {
258     $budget_id      =  $data->{'budget_id'};
259     $budget_name    =   $budget->{'budget_name'};
260
261 }
262
263 $template->param( sort1 => $data->{'sort1'} );
264 $template->param( sort2 => $data->{'sort2'} );
265
266 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
267     # Check if ACQ framework exists
268     my $marc = GetMarcStructure(1, 'ACQ');
269     unless($marc) {
270         $template->param('NoACQframework' => 1);
271     }
272     $template->param(
273         AcqCreateItemOrdering => 1,
274         UniqueItemFields => C4::Context->preference('UniqueItemFields'),
275     );
276 }
277 # 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
278 my @itemtypes;
279 @itemtypes = Koha::ItemTypes->search unless C4::Context->preference('item-level_itypes');
280
281 if ( defined $subscriptionid ) {
282     my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
283     if ( defined $lastOrderReceived ) {
284         $budget_id              = $lastOrderReceived->{budgetid};
285         $data->{listprice}      = $lastOrderReceived->{listprice};
286         $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
287         $data->{gstrate}        = $lastOrderReceived->{gstrate};
288         $data->{discount}       = $lastOrderReceived->{discount};
289         $data->{rrp}            = $lastOrderReceived->{rrp};
290         $data->{ecost}          = $lastOrderReceived->{ecost};
291         $data->{quantity}       = $lastOrderReceived->{quantity};
292         $data->{unitprice}      = $lastOrderReceived->{unitprice};
293         $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
294         $data->{order_vendornote}   = $lastOrderReceived->{order_vendornote};
295         $data->{sort1}          = $lastOrderReceived->{sort1};
296         $data->{sort2}          = $lastOrderReceived->{sort2};
297
298         $basket = GetBasket( $input->param('basketno') );
299     }
300 }
301
302 # Find the items.barcode subfield for barcode validations
303 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
304
305 # fill template
306 $template->param(
307     close        => $close,
308     budget_id    => $budget_id,
309     budget_name  => $budget_name
310 ) if ($close);
311
312 # get option values for gist syspref
313 my @gst_values = map {
314     option => $_ + 0.0
315 }, split( '\|', C4::Context->preference("gist") );
316
317 my $quantity = $input->param('rr_quantity_to_order') ?
318       $input->param('rr_quantity_to_order') :
319       $data->{'quantity'};
320 $quantity //= 0;
321
322 $template->param(
323     existing         => $biblionumber,
324     ordernumber           => $ordernumber,
325     # basket informations
326     basketno             => $basketno,
327     basket               => $basket,
328     basketname           => $basket->{'basketname'},
329     basketnote           => $basket->{'note'},
330     booksellerid         => $basket->{'booksellerid'},
331     basketbooksellernote => $basket->{booksellernote},
332     basketcontractno     => $basket->{contractnumber},
333     basketcontractname   => $contract->{contractname},
334     creationdate         => $basket->{creationdate},
335     authorisedby         => $basket->{'authorisedby'},
336     authorisedbyname     => $basket->{'authorisedbyname'},
337     closedate            => $basket->{'closedate'},
338     # order details
339     suggestionid         => $suggestion->{suggestionid},
340     surnamesuggestedby   => $suggestion->{surnamesuggestedby},
341     firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
342     biblionumber         => $biblionumber,
343     uncertainprice       => $data->{'uncertainprice'},
344     discount_2dp         => sprintf( "%.2f",  $bookseller->{'discount'} ) ,   # for display
345     discount             => $bookseller->{'discount'},
346     orderdiscount_2dp    => sprintf( "%.2f", $data->{'discount'} || 0 ),
347     orderdiscount        => $data->{'discount'},
348     order_internalnote   => $data->{'order_internalnote'},
349     order_vendornote     => $data->{'order_vendornote'},
350     listincgst       => $bookseller->{'listincgst'},
351     invoiceincgst    => $bookseller->{'invoiceincgst'},
352     name             => $bookseller->{'name'},
353     cur_active_sym   => $active_currency->symbol,
354     cur_active       => $active_currency->currency,
355     currencies       => \@currencies,
356     currency         => $data->{currency},
357     vendor_currency  => $bookseller->{listprice},
358     orderexists      => ( $new eq 'yes' ) ? 0 : 1,
359     title            => $data->{'title'},
360     author           => $data->{'author'},
361     publicationyear  => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
362     editionstatement => $data->{'editionstatement'},
363     budget_loop      => $budget_loop,
364     isbn             => $data->{'isbn'},
365     ean              => $data->{'ean'},
366     seriestitle      => $data->{'seriestitle'},
367     itemtypeloop     => \@itemtypes,
368     quantity         => $quantity,
369     quantityrec      => $quantity,
370     rrp              => $data->{'rrp'},
371     gst_values       => \@gst_values,
372     gstrate          => $data->{gstrate} ? $data->{gstrate}+0.0 : $bookseller->{gstrate} ? $bookseller->{gstrate}+0.0 : 0,
373     listprice        => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
374     total            => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
375     ecost            => sprintf( "%.2f", $data->{ecost} || 0),
376     unitprice        => sprintf( "%.2f", $data->{unitprice} || 0),
377     publishercode    => $data->{'publishercode'},
378     barcode_subfield => $barcode_subfield,
379     import_batch_id  => $import_batch_id,
380     subscriptionid   => $subscriptionid,
381     acqcreate        => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
382     users_ids        => join(':', @order_user_ids),
383     users            => \@order_users,
384     (uc(C4::Context->preference("marcflavour"))) => 1
385 );
386
387 output_html_with_http_headers $input, $cookie, $template->output;
388
389
390 =head2 MARCfindbreeding
391
392   $record = MARCfindbreeding($breedingid);
393
394 Look up the import record repository for the record with
395 record with id $breedingid.  If found, returns the decoded
396 MARC::Record; otherwise, -1 is returned (FIXME).
397 Returns as second parameter the character encoding.
398
399 =cut
400
401 sub MARCfindbreeding {
402     my ( $id ) = @_;
403     my ($marc, $encoding) = GetImportRecordMarc($id);
404     # remove the - in isbn, koha store isbn without any -
405     if ($marc) {
406         my $record = MARC::Record->new_from_usmarc($marc);
407         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
408         if ( $record->field($isbnfield) ) {
409             foreach my $field ( $record->field($isbnfield) ) {
410                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
411                     my $newisbn = $field->subfield($isbnsubfield);
412                     $newisbn =~ s/-//g;
413                     $field->update( $isbnsubfield => $newisbn );
414                 }
415             }
416         }
417         # fix the unimarc 100 coded field (with unicode information)
418         if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
419             my $f100a=$record->subfield(100,'a');
420             my $f100 = $record->field(100);
421             my $f100temp = $f100->as_string;
422             $record->delete_field($f100);
423             if ( length($f100temp) > 28 ) {
424                 substr( $f100temp, 26, 2, "50" );
425                 $f100->update( 'a' => $f100temp );
426                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
427                 $record->insert_fields_ordered($f100);
428             }
429         }
430         
431         if ( !defined(ref($record)) ) {
432             return -1;
433         }
434         else {
435             # normalize author : probably UNIMARC specific...
436             if (    C4::Context->preference("z3950NormalizeAuthor")
437                 and C4::Context->preference("z3950AuthorAuthFields") )
438             {
439                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
440
441 #                 my $summary = C4::Context->preference("z3950authortemplate");
442                 my $auth_fields =
443                 C4::Context->preference("z3950AuthorAuthFields");
444                 my @auth_fields = split /,/, $auth_fields;
445                 my $field;
446
447                 if ( $record->field($tag) ) {
448                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
449
450     #                        foreach my $subfieldcode ($tmpfield->subfields){
451                         my $subfieldcode  = shift @$tmpfield;
452                         my $subfieldvalue = shift @$tmpfield;
453                         if ($field) {
454                             $field->add_subfields(
455                                 "$subfieldcode" => $subfieldvalue )
456                             if ( $subfieldcode ne $subfield );
457                         }
458                         else {
459                             $field =
460                             MARC::Field->new( $tag, "", "",
461                                 $subfieldcode => $subfieldvalue )
462                             if ( $subfieldcode ne $subfield );
463                         }
464                     }
465                 }
466                 $record->delete_field( $record->field($tag) );
467                 foreach my $fieldtag (@auth_fields) {
468                     next unless ( $record->field($fieldtag) );
469                     my $lastname  = $record->field($fieldtag)->subfield('a');
470                     my $firstname = $record->field($fieldtag)->subfield('b');
471                     my $title     = $record->field($fieldtag)->subfield('c');
472                     my $number    = $record->field($fieldtag)->subfield('d');
473                     if ($title) {
474
475 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
476                         $field->add_subfields(
477                                 "$subfield" => ucfirst($title) . " "
478                             . ucfirst($firstname) . " "
479                             . $number );
480                     }
481                     else {
482
483 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
484                         $field->add_subfields(
485                             "$subfield" => ucfirst($firstname) . ", "
486                             . ucfirst($lastname) );
487                     }
488                 }
489                 $record->insert_fields_ordered($field);
490             }
491             return $record, $encoding;
492         }
493     }
494     return -1;
495 }
496
497 sub Load_Duplicate {
498   my ($duplicatetitle)= @_;
499   ($template, $loggedinuser, $cookie) = get_template_and_user(
500     {
501         template_name   => "acqui/neworderempty_duplicate.tt",
502         query           => $input,
503         type            => "intranet",
504         authnotrequired => 0,
505         flagsrequired   => { acquisition => 'order_manage' },
506 #        debug           => 1,
507     }
508   );
509
510   $template->param(
511     biblionumber        => $biblionumber,
512     basketno            => $basketno,
513     booksellerid        => $basket->{'booksellerid'},
514     breedingid          => $params->{'breedingid'},
515     duplicatetitle      => $duplicatetitle,
516     (uc(C4::Context->preference("marcflavour"))) => 1
517   );
518
519   output_html_with_http_headers $input, $cookie, $template->output;
520 }