Bug 35579: Cache authorised value lookup by MARC field
[koha.git] / acqui / addorder.pl
1 #!/usr/bin/perl
2
3 #script to add an order into the system
4 #written 29/2/00 by chris@katipo.co.nz
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 addorder.pl
27
28 =head1 DESCRIPTION
29
30 this script allows to add an order.
31 It is called by :
32
33 =over
34
35 =item neworderempty.pl to add an order from an existing record or from nothing.
36
37 =item newordersuggestion.pl to add an order from an existing suggestion.
38
39 =back
40
41 =head1 CGI PARAMETERS
42
43 All of the cgi parameters below are related to the new order.
44
45 =over
46
47 =item C<ordernumber>
48 the number of this new order.
49
50 =item C<basketno>
51 the number of this new basket
52
53 =item C<booksellerid>
54 the bookseller the librarian has to pay.
55
56 =item C<existing>
57
58 =item C<title>
59 the title of the record ordered.
60
61 =item C<author>
62 the author of the record ordered.
63
64 =item C<copyrightdate>
65 the copyrightdate of the record ordered.
66
67 =item C<ISBN>
68 the ISBN of the record ordered.
69
70 =item C<format>
71
72 =item C<quantity>
73 the quantity to order.
74
75 =item C<listprice>
76 the price of this order.
77
78 =item C<uncertainprice>
79 uncertain price, can't close basket until prices of all orders are known.
80
81 =item C<branch>
82 the branch where this order will be received.
83
84 =item C<series>
85
86 =item C<notes>
87 Notes on this basket.
88
89 =item C<budget_id>
90 budget_id used to pay this order.
91
92 =item C<sort1> & C<sort2>
93
94 =item C<rrp>
95
96 =item C<ecost>
97
98 =item C<GST>
99
100 =item C<budget>
101
102 =item C<cost>
103
104 =item C<sub>
105
106 =item C<invoice>
107 the number of the invoice for this order.
108
109 =item C<publishercode>
110
111 =item C<suggestionid>
112 if it is an order from an existing suggestion : the id of this suggestion.
113
114 =item C<donation>
115
116 =back
117
118 =cut
119
120 use Modern::Perl;
121 use CGI qw ( -utf8 );
122 use JSON qw ( to_json encode_json );
123 use C4::Auth qw( get_template_and_user );
124 use C4::Acquisition qw( FillWithDefaultValues ModOrderUsers );
125 use C4::Suggestions qw( ModSuggestion );
126 use C4::Biblio qw(
127     AddBiblio
128     GetMarcFromKohaField
129     TransformHtmlToXml
130     TransformKohaToMarc
131 );
132 use C4::Budgets qw( GetBudget GetBudgetSpent GetBudgetOrdered );
133 use C4::Items qw( AddItemFromMarc );
134 use C4::Output qw( output_html_with_http_headers );
135 use C4::Log qw( logaction );
136 use Koha::Acquisition::Currencies qw( get_active );
137 use Koha::Acquisition::Orders;
138 use Koha::Acquisition::Baskets;
139 use C4::Barcodes;
140 use Koha::DateUtils qw( dt_from_string );
141
142 use Koha::AdditionalFields;
143
144 ### "-------------------- addorder.pl ----------"
145
146 # FIXME: This needs to do actual error checking and possibly return user to the same form,
147 # not just blindly call C4 functions and print a redirect.  
148
149 my $input = CGI->new;
150 my $use_ACQ_framework = $input->param('use_ACQ_framework');
151
152 # Check if order total amount exceed allowed budget
153 my $confirm_budget_exceeding = $input->param('confirm_budget_exceeding');
154 unless($confirm_budget_exceeding) {
155     my $budget_id = $input->param('budget_id');
156     my $total = $input->param('total');
157     my $budget = GetBudget($budget_id);
158     my $budget_spent = GetBudgetSpent($budget_id);
159     my $budget_ordered = GetBudgetOrdered($budget_id);
160
161     my $ordernumber = $input->param('ordernumber');
162     if ( $ordernumber ) {
163         # modifying an existing order so remove order price from $budget_ordered
164         my $order = Koha::Acquisition::Orders->find($ordernumber);
165         $budget_ordered = $budget_ordered - ( $order->ecost_tax_included * $order->quantity );
166     }
167
168     my $budget_used = $budget_spent + $budget_ordered;
169     my $budget_remaining = $budget->{budget_amount} - $budget_used;
170     my $budget_encumbrance = $budget->{budget_amount} * $budget->{budget_encumb} / 100;
171     my $budget_expenditure = $budget->{budget_expend};
172
173     if ( $total > $budget_remaining
174       || ( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance)
175       || ( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure) )
176     {
177         my ($template, $loggedinuser, $cookie) = get_template_and_user({
178             template_name   => "acqui/addorder.tt",
179             query           => $input,
180             type            => "intranet",
181             flagsrequired   => {acquisition => 'order_manage'},
182         });
183
184         my $url = $input->referer();
185         unless ( defined $url ) {
186             my $basketno = $input->param('basketno');
187             $url = "/cgi-bin/koha/acqui/basket.pl?basketno=$basketno";
188         }
189
190         my $vars = $input->Vars;
191         my @vars_loop;
192         foreach (keys %$vars) {
193             push @vars_loop, {
194                 name => $_,
195                 values => [ $input->multi_param($_) ],
196             };
197         }
198
199         if( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance
200           && $total <= $budget_remaining)
201         {
202             $template->param(
203                 encumbrance_exceeded => 1,
204                 encumbrance => sprintf("%.2f", $budget->{'budget_encumb'}),
205             );
206         }
207         if( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure
208           && $total <= $budget_remaining )
209         {
210             my $currency = Koha::Acquisition::Currencies->get_active;
211             $template->param(
212                 expenditure_exceeded => 1,
213                 expenditure => sprintf("%.2f", $budget_expenditure),
214                 currency => ($currency) ? $currency->symbol : '',
215             );
216         }
217         if($total > $budget_remaining){
218             $template->param(budget_exceeded => 1);
219         }
220
221         $template->param(
222             not_enough_budget => 1,
223             referer => $url,
224             vars_loop => \@vars_loop,
225         );
226         output_html_with_http_headers $input, $cookie, $template->output;
227         exit;
228     }
229 }
230
231 # get_template_and_user used only to check auth & get user id
232 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
233     {
234         template_name   => "acqui/booksellers.tt",
235         query           => $input,
236         type            => "intranet",
237         flagsrequired   => { acquisition => 'order_manage' },
238     }
239 );
240
241 # get CGI parameters
242 my $orderinfo = {
243     ordernumber          => scalar $input->param('ordernumber'),
244     basketno             => scalar $input->param('basketno'),
245     biblionumber         => scalar $input->param('biblionumber'),
246     invoiceid            => scalar $input->param('invoiceid'),
247     quantity             => scalar $input->param('quantity'),
248     budget_id            => scalar $input->param('budget_id'),
249     currency             => scalar $input->param('currency'),
250     listprice            => scalar $input->param('listprice'),
251     uncertainprice       => scalar $input->param('uncertainprice'),
252     tax_rate_on_ordering => scalar $input->param('tax_rate'),
253     discount             => scalar $input->param('discount'),
254     rrp                  => scalar $input->param('rrp'),
255     replacementprice     => scalar $input->param('replacementprice'),
256     ecost                => scalar $input->param('ecost'),
257     unitprice            => scalar $input->param('unitprice'),
258     order_internalnote   => scalar $input->param('order_internalnote'),
259     order_vendornote     => scalar $input->param('order_vendornote'),
260     sort1                => scalar $input->param('sort1'),
261     sort2                => scalar $input->param('sort2'),
262     subscriptionid       => scalar $input->param('subscriptionid'),
263     estimated_delivery_date => scalar $input->param('estimated_delivery_date'),
264 };
265
266 $orderinfo->{uncertainprice} ||= 0;
267 $orderinfo->{subscriptionid} ||= undef;
268
269 my $user     = $input->remote_user;
270 my $basketno = $$orderinfo{basketno};
271 my $basket   = Koha::Acquisition::Baskets->find($basketno);
272
273 # Order related fields we're going to log
274 my @log_order_fields = (
275     'quantity',
276     'listprice',
277     'unitprice',
278     'unitprice_tax_excluded',
279     'unitprice_tax_included',
280     'rrp',
281     'replacementprice',
282     'rrp_tax_excluded',
283     'rrp_tax_included',
284     'ecost',
285     'ecost_tax_excluded',
286     'ecost_tax_included',
287     'tax_rate_on_ordering'
288 );
289
290 # create, modify or delete biblio
291 # create if $quantity>0 and $existing='no'
292 # modify if $quantity>0 and $existing='yes'
293 if ( $basket->{is_standing} || $orderinfo->{quantity} ne '0' ) {
294     #TODO:check to see if biblio exists
295     unless ( $$orderinfo{biblionumber} ) {
296
297         my $record;
298         if ( $use_ACQ_framework ) {
299             my @tags         = $input->multi_param('bib_tag');
300             my @subfields    = $input->multi_param('bib_subfield');
301             my @field_values = $input->multi_param('bib_field_value');
302             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
303             $record=MARC::Record::new_from_xml($xml, 'UTF-8');
304         } else {
305             #if it doesn't create it
306             $record = TransformKohaToMarc(
307                 {
308                     "biblio.title"                => $input->param('title') || '',
309                     "biblio.author"               => $input->param('author') || '',
310                     "biblio.seriestitle"          => $input->param('series') || '',
311                     "biblioitems.isbn"            => $input->param('isbn') || '',
312                     "biblioitems.ean"             => $input->param('ean') || '',
313                     "biblioitems.publishercode"   => $input->param('publishercode') || '',
314                     "biblioitems.publicationyear" => $input->param('publicationyear') || '',
315                     "biblio.copyrightdate"        => $input->param('publicationyear') || '',
316                     "biblioitems.itemtype"        => $input->param('itemtype') || '',
317                     "biblioitems.editionstatement"=> $input->param('editionstatement') || '',
318                 }
319             );
320         }
321         C4::Acquisition::FillWithDefaultValues( $record );
322
323         # create the record in catalogue, with framework ''
324         my ($biblionumber,$bibitemnum) = AddBiblio($record,'');
325
326         $orderinfo->{biblionumber}=$biblionumber;
327     }
328
329     # change suggestion status if applicable
330     if ( my $suggestionid = $input->param('suggestionid') ) {
331         ModSuggestion(
332             {
333                 suggestionid => $suggestionid,
334                 biblionumber => $orderinfo->{biblionumber},
335                 STATUS       => 'ORDERED',
336             }
337         );
338     }
339
340     $orderinfo->{unitprice} = $orderinfo->{ecost} if not defined $orderinfo->{unitprice} or $orderinfo->{unitprice} eq '';
341
342     my $order;
343     my $log_action_name;
344
345     if ( $orderinfo->{ordernumber} ) {
346         $order = Koha::Acquisition::Orders->find($orderinfo->{ordernumber});
347         $order->set($orderinfo);
348         $log_action_name = 'MODIFY_ORDER';
349     } else {
350         $order = Koha::Acquisition::Order->new($orderinfo);
351         $log_action_name = 'CREATE_ORDER';
352     }
353     $order->populate_with_prices_for_ordering();
354     $order->store;
355
356     # Log the order creation
357     if (C4::Context->preference("AcquisitionLog")) {
358         my $infos = {};
359         foreach my $field(@log_order_fields) {
360             $infos->{$field} = $order->$field;
361         }
362         logaction(
363             'ACQUISITIONS',
364             $log_action_name,
365             $order->ordernumber,
366             encode_json($infos)
367         );
368     }
369     my $order_users_ids = $input->param('users_ids');
370     my @order_users = split( /:/, $order_users_ids );
371     ModOrderUsers( $order->ordernumber, @order_users );
372
373     # Retrieve and save additional fields values
374     my @additional_fields = Koha::AdditionalFields->search({ tablename => 'aqorders' })->as_list;
375     my @additional_field_values;
376     foreach my $af (@additional_fields) {
377         my $id = $af->id;
378         my $value = $input->param("additional_field_$id");
379         push @additional_field_values, {
380             id => $id,
381             value => $value,
382         };
383     }
384     $order->set_additional_fields(\@additional_field_values);
385
386     # now, add items if applicable
387     if ($basket->effective_create_items eq 'ordering') {
388
389         my @tags         = $input->multi_param('tag');
390         my @subfields    = $input->multi_param('subfield');
391         my @field_values = $input->multi_param('field_value');
392         my @serials      = $input->multi_param('serial');
393         my @itemid       = $input->multi_param('itemid');
394         #Rebuilding ALL the data for items into a hash
395         # parting them on $itemid.
396
397         my %itemhash;
398         my $countdistinct;
399         my $range=scalar(@itemid);
400         for (my $i=0; $i<$range; $i++){
401             unless ($itemhash{$itemid[$i]}){
402             $countdistinct++;
403             }
404         push @{$itemhash{$itemid[$i]}->{'tags'}},$tags[$i];
405         push @{$itemhash{$itemid[$i]}->{'subfields'}},$subfields[$i];
406             push @{$itemhash{$itemid[$i]}->{'field_values'}},$field_values[$i];
407         }
408         foreach my $item (keys %itemhash){
409             my $xml = TransformHtmlToXml( $itemhash{$item}->{'tags'},
410                                     $itemhash{$item}->{'subfields'},
411                                     $itemhash{$item}->{'field_values'},
412                                     undef,
413                                     undef,
414                                     'ITEM');
415             my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
416             my ($barcodefield,$barcodesubfield) = GetMarcFromKohaField('items.barcode');
417             next unless ( defined $barcodefield && defined $barcodesubfield );
418             my $barcode = $record->subfield($barcodefield,$barcodesubfield) || '';
419             my $aBpref = C4::Context->preference('autoBarcode');
420             if( $barcode eq '' && $aBpref ne 'OFF'){
421                 my $barcodeobj;
422                 if ( $aBpref eq 'hbyymmincr'){
423                     my ($homebranchfield,$homebranchsubfield) = GetMarcFromKohaField('items.homebranch');
424                     my $homebranch = $record->subfield($homebranchfield,$homebranchsubfield);
425                     $barcodeobj = C4::Barcodes->new($aBpref, $homebranch);
426                 } else {
427                     $barcodeobj = C4::Barcodes->new($aBpref);
428                 }
429                 $barcode = $barcodeobj->value();
430                 $record->field($barcodefield)->delete_subfield( code => $barcodesubfield);
431                 $record->field($barcodefield)->add_subfields($barcodesubfield => $barcode);
432             }
433             my ($biblionumber,$bibitemnum,$itemnumber) = AddItemFromMarc($record,$$orderinfo{biblionumber});
434             $order->add_item($itemnumber);
435         }
436     }
437
438 }
439
440 if (C4::Context->preference("AcquisitionLog") && $basketno) {
441     my $modified = Koha::Acquisition::Baskets->find( $basketno );
442     logaction(
443         'ACQUISITIONS',
444         'MODIFY_BASKET',
445         $basketno,
446         to_json($modified->unblessed)
447     );
448 }
449
450 my $booksellerid=$$orderinfo{booksellerid};
451 if (my $import_batch_id = $input->param('import_batch_id')) {
452     print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=$basketno&booksellerid=$booksellerid");
453 } elsif ( defined $orderinfo->{invoiceid} ) {
454     print $input->redirect("/cgi-bin/koha/acqui/parcel.pl?invoiceid=" . $orderinfo->{invoiceid});
455 } else {
456     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=$basketno");
457 }