Bug 8612: Use CSV profile for exporting 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
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';
110
111 my $budget_name;
112
113 our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user(
114     {
115         template_name   => "acqui/neworderempty.tt",
116         query           => $input,
117         type            => "intranet",
118         authnotrequired => 0,
119         flagsrequired   => { acquisition => 'order_manage' },
120         debug           => 1,
121     }
122 );
123
124 our $marcflavour = C4::Context->preference('marcflavour');
125
126 if(!$basketno) {
127     my $order = GetOrder($ordernumber);
128     $basketno = $order->{'basketno'};
129 }
130
131 our $basket = GetBasket($basketno);
132 $booksellerid = $basket->{booksellerid} unless $booksellerid;
133 my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid );
134
135 my $contract = GetContract({
136     contractnumber => $basket->{contractnumber}
137 });
138
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;
146
147     # Remove all the items (952) from the imported record
148     foreach my $item ($marcrecord->field('952')) {
149         $marcrecord->delete_field($item);
150     }
151
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 them choose between using a new record or an existing record
158         Load_Duplicate($duplicatetitle);
159         exit;
160     }
161     #from this point: add a new record
162         if (C4::Context->preference("BiblioAddsAuthorities")){
163             my $headings_linked=BiblioAutoLink($marcrecord, $params->{'frameworkcode'});
164         }
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');
171 }
172
173
174
175 my ( @order_user_ids, @order_users );
176 if ( $ordernumber eq '' ) {    # create order
177     $new = 'yes';
178
179     #   $ordernumber=newordernum;
180     if ( $biblionumber && !$suggestionid ) {
181         $data = GetBiblioData($biblionumber);
182     }
183
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;
189     }
190 }
191 else {    #modify order
192     $data   = GetOrder($ordernumber);
193     $biblionumber = $data->{'biblionumber'};
194     $budget_id = $data->{'budget_id'};
195
196     $basket   = GetBasket( $data->{'basketno'} );
197     $basketno = $basket->{'basketno'};
198
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;
203     }
204 }
205
206 my $suggestion;
207 $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid;
208
209 my @currencies = Koha::Acquisition::Currencies->search;
210 my $active_currency = Koha::Acquisition::Currencies->get_active;
211
212 # build bookfund list
213 my $borrower= GetMember('borrowernumber' => $loggedinuser);
214 my ( $flags, $homebranch )= ($borrower->{'flags'},$borrower->{'branchcode'});
215
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;
224     }
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,
232         b_level => $r->{budget_level},
233     };
234 }
235
236 if ($close) {
237     $budget_id      =  $data->{'budget_id'};
238     $budget_name    =   $budget->{'budget_name'};
239
240 }
241
242 $template->param( sort1 => $data->{'sort1'} );
243 $template->param( sort2 => $data->{'sort2'} );
244
245 if (C4::Context->preference('AcqCreateItem') eq 'ordering' && !$ordernumber) {
246     # Check if ACQ framework exists
247     my $marc = GetMarcStructure(1, 'ACQ', { unsafe => 1 } );
248     unless($marc) {
249         $template->param('NoACQframework' => 1);
250     }
251     $template->param(
252         AcqCreateItemOrdering => 1,
253         UniqueItemFields => C4::Context->preference('UniqueItemFields'),
254     );
255 }
256 # 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
257 my @itemtypes;
258 @itemtypes = Koha::ItemTypes->search unless C4::Context->preference('item-level_itypes');
259
260 if ( defined $subscriptionid ) {
261     my $lastOrderReceived = GetLastOrderReceivedFromSubscriptionid $subscriptionid;
262     if ( defined $lastOrderReceived ) {
263         $budget_id              = $lastOrderReceived->{budgetid};
264         $data->{listprice}      = $lastOrderReceived->{listprice};
265         $data->{uncertainprice} = $lastOrderReceived->{uncertainprice};
266         $data->{tax_rate}       = $lastOrderReceived->{tax_rate_on_ordering};
267         $data->{discount}       = $lastOrderReceived->{discount};
268         $data->{rrp}            = $lastOrderReceived->{rrp};
269         $data->{ecost}          = $lastOrderReceived->{ecost};
270         $data->{quantity}       = $lastOrderReceived->{quantity};
271         $data->{unitprice}      = $lastOrderReceived->{unitprice};
272         $data->{order_internalnote} = $lastOrderReceived->{order_internalnote};
273         $data->{order_vendornote}   = $lastOrderReceived->{order_vendornote};
274         $data->{sort1}          = $lastOrderReceived->{sort1};
275         $data->{sort2}          = $lastOrderReceived->{sort2};
276
277         $basket = GetBasket( $input->param('basketno') );
278     }
279 }
280
281 # Find the items.barcode subfield for barcode validations
282 my (undef, $barcode_subfield) = GetMarcFromKohaField('items.barcode', '');
283
284 # fill template
285 $template->param(
286     close        => $close,
287     budget_id    => $budget_id,
288     budget_name  => $budget_name
289 ) if ($close);
290
291 # get option values for gist syspref
292 my @gst_values = map {
293     option => $_ + 0.0
294 }, split( '\|', C4::Context->preference("gist") );
295
296 my $quantity = $input->param('rr_quantity_to_order') ?
297       $input->param('rr_quantity_to_order') :
298       $data->{'quantity'};
299 $quantity //= 0;
300
301 $template->param(
302     existing         => $biblionumber,
303     ordernumber           => $ordernumber,
304     # basket informations
305     basketno             => $basketno,
306     basket               => $basket,
307     basketname           => $basket->{'basketname'},
308     basketnote           => $basket->{'note'},
309     booksellerid         => $basket->{'booksellerid'},
310     basketbooksellernote => $basket->{booksellernote},
311     basketcontractno     => $basket->{contractnumber},
312     basketcontractname   => $contract->{contractname},
313     creationdate         => $basket->{creationdate},
314     authorisedby         => $basket->{'authorisedby'},
315     authorisedbyname     => $basket->{'authorisedbyname'},
316     closedate            => $basket->{'closedate'},
317     # order details
318     suggestionid         => $suggestion->{suggestionid},
319     surnamesuggestedby   => $suggestion->{surnamesuggestedby},
320     firstnamesuggestedby => $suggestion->{firstnamesuggestedby},
321     biblionumber         => $biblionumber,
322     uncertainprice       => $data->{'uncertainprice'},
323     discount_2dp         => sprintf( "%.2f",  $bookseller->discount ) ,   # for display
324     discount             => $bookseller->discount,
325     orderdiscount_2dp    => sprintf( "%.2f", $data->{'discount'} || 0 ),
326     orderdiscount        => $data->{'discount'},
327     order_internalnote   => $data->{'order_internalnote'},
328     order_vendornote     => $data->{'order_vendornote'},
329     listincgst       => $bookseller->listincgst,
330     invoiceincgst    => $bookseller->invoiceincgst,
331     name             => $bookseller->name,
332     cur_active_sym   => $active_currency->symbol,
333     cur_active       => $active_currency->currency,
334     currencies       => \@currencies,
335     currency         => $data->{currency},
336     vendor_currency  => $bookseller->listprice,
337     orderexists      => ( $new eq 'yes' ) ? 0 : 1,
338     title            => $data->{'title'},
339     author           => $data->{'author'},
340     publicationyear  => $data->{'publicationyear'} ? $data->{'publicationyear'} : $data->{'copyrightdate'},
341     editionstatement => $data->{'editionstatement'},
342     budget_loop      => $budget_loop,
343     isbn             => $data->{'isbn'},
344     ean              => $data->{'ean'},
345     seriestitle      => $data->{'seriestitle'},
346     itemtypeloop     => \@itemtypes,
347     quantity         => $quantity,
348     quantityrec      => $quantity,
349     rrp              => $data->{'rrp'},
350     gst_values       => \@gst_values,
351     tax_rate         => $data->{tax_rate_on_ordering} ? $data->{tax_rate_on_ordering}+0.0 : $bookseller->tax_rate ? $bookseller->tax_rate+0.0 : 0,
352     listprice        => sprintf( "%.2f", $data->{listprice} || $data->{price} || $listprice),
353     total            => sprintf( "%.2f", ($data->{ecost} || 0) * ($data->{'quantity'} || 0) ),
354     ecost            => sprintf( "%.2f", $data->{ecost} || 0),
355     unitprice        => sprintf( "%.2f", $data->{unitprice} || 0),
356     publishercode    => $data->{'publishercode'},
357     barcode_subfield => $barcode_subfield,
358     import_batch_id  => $import_batch_id,
359     subscriptionid   => $subscriptionid,
360     acqcreate        => C4::Context->preference("AcqCreateItem") eq "ordering" ? 1 : "",
361     users_ids        => join(':', @order_user_ids),
362     users            => \@order_users,
363     (uc(C4::Context->preference("marcflavour"))) => 1
364 );
365
366 output_html_with_http_headers $input, $cookie, $template->output;
367
368
369 =head2 MARCfindbreeding
370
371   $record = MARCfindbreeding($breedingid);
372
373 Look up the import record repository for the record with
374 record with id $breedingid.  If found, returns the decoded
375 MARC::Record; otherwise, -1 is returned (FIXME).
376 Returns as second parameter the character encoding.
377
378 =cut
379
380 sub MARCfindbreeding {
381     my ( $id ) = @_;
382     my ($marc, $encoding) = GetImportRecordMarc($id);
383     # remove the - in isbn, koha store isbn without any -
384     if ($marc) {
385         my $record = MARC::Record->new_from_usmarc($marc);
386         my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField('biblioitems.isbn','');
387         if ( $record->field($isbnfield) ) {
388             foreach my $field ( $record->field($isbnfield) ) {
389                 foreach my $subfield ( $field->subfield($isbnsubfield) ) {
390                     my $newisbn = $field->subfield($isbnsubfield);
391                     $newisbn =~ s/-//g;
392                     $field->update( $isbnsubfield => $newisbn );
393                 }
394             }
395         }
396         # fix the unimarc 100 coded field (with unicode information)
397         if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) {
398             my $f100a=$record->subfield(100,'a');
399             my $f100 = $record->field(100);
400             my $f100temp = $f100->as_string;
401             $record->delete_field($f100);
402             if ( length($f100temp) > 28 ) {
403                 substr( $f100temp, 26, 2, "50" );
404                 $f100->update( 'a' => $f100temp );
405                 my $f100 = MARC::Field->new( '100', '', '', 'a' => $f100temp );
406                 $record->insert_fields_ordered($f100);
407             }
408         }
409         
410         if ( !defined(ref($record)) ) {
411             return -1;
412         }
413         else {
414             # normalize author : probably UNIMARC specific...
415             if (    C4::Context->preference("z3950NormalizeAuthor")
416                 and C4::Context->preference("z3950AuthorAuthFields") )
417             {
418                 my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author", '');
419
420 #                 my $summary = C4::Context->preference("z3950authortemplate");
421                 my $auth_fields =
422                 C4::Context->preference("z3950AuthorAuthFields");
423                 my @auth_fields = split /,/, $auth_fields;
424                 my $field;
425
426                 if ( $record->field($tag) ) {
427                     foreach my $tmpfield ( $record->field($tag)->subfields ) {
428
429     #                        foreach my $subfieldcode ($tmpfield->subfields){
430                         my $subfieldcode  = shift @$tmpfield;
431                         my $subfieldvalue = shift @$tmpfield;
432                         if ($field) {
433                             $field->add_subfields(
434                                 "$subfieldcode" => $subfieldvalue )
435                             if ( $subfieldcode ne $subfield );
436                         }
437                         else {
438                             $field =
439                             MARC::Field->new( $tag, "", "",
440                                 $subfieldcode => $subfieldvalue )
441                             if ( $subfieldcode ne $subfield );
442                         }
443                     }
444                 }
445                 $record->delete_field( $record->field($tag) );
446                 foreach my $fieldtag (@auth_fields) {
447                     next unless ( $record->field($fieldtag) );
448                     my $lastname  = $record->field($fieldtag)->subfield('a');
449                     my $firstname = $record->field($fieldtag)->subfield('b');
450                     my $title     = $record->field($fieldtag)->subfield('c');
451                     my $number    = $record->field($fieldtag)->subfield('d');
452                     if ($title) {
453
454 #                         $field->add_subfields("$subfield"=>"[ ".ucfirst($title).ucfirst($firstname)." ".$number." ]");
455                         $field->add_subfields(
456                                 "$subfield" => ucfirst($title) . " "
457                             . ucfirst($firstname) . " "
458                             . $number );
459                     }
460                     else {
461
462 #                       $field->add_subfields("$subfield"=>"[ ".ucfirst($firstname).", ".ucfirst($lastname)." ]");
463                         $field->add_subfields(
464                             "$subfield" => ucfirst($firstname) . ", "
465                             . ucfirst($lastname) );
466                     }
467                 }
468                 $record->insert_fields_ordered($field);
469             }
470             return $record, $encoding;
471         }
472     }
473     return -1;
474 }
475
476 sub Load_Duplicate {
477   my ($duplicatetitle)= @_;
478   ($template, $loggedinuser, $cookie) = get_template_and_user(
479     {
480         template_name   => "acqui/neworderempty_duplicate.tt",
481         query           => $input,
482         type            => "intranet",
483         authnotrequired => 0,
484         flagsrequired   => { acquisition => 'order_manage' },
485 #        debug           => 1,
486     }
487   );
488
489   $template->param(
490     biblionumber        => $biblionumber,
491     basketno            => $basketno,
492     booksellerid        => $basket->{'booksellerid'},
493     breedingid          => $params->{'breedingid'},
494     duplicatetitle      => $duplicatetitle,
495     (uc(C4::Context->preference("marcflavour"))) => 1
496   );
497
498   output_html_with_http_headers $input, $cookie, $template->output;
499 }