Bug 29407: Make the pickup locations dropdown JS reusable
[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<list_price>
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 populate_order_with_prices ModOrder 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
141 ### "-------------------- addorder.pl ----------"
142
143 # FIXME: This needs to do actual error checking and possibly return user to the same form,
144 # not just blindly call C4 functions and print a redirect.  
145
146 my $input = CGI->new;
147 my $use_ACQ_framework = $input->param('use_ACQ_framework');
148
149 # Check if order total amount exceed allowed budget
150 my $confirm_budget_exceeding = $input->param('confirm_budget_exceeding');
151 unless($confirm_budget_exceeding) {
152     my $budget_id = $input->param('budget_id');
153     my $total = $input->param('total');
154     my $budget = GetBudget($budget_id);
155     my $budget_spent = GetBudgetSpent($budget_id);
156     my $budget_ordered = GetBudgetOrdered($budget_id);
157     my $budget_used = $budget_spent + $budget_ordered;
158     my $budget_remaining = $budget->{budget_amount} - $budget_used;
159     my $budget_encumbrance = $budget->{budget_amount} * $budget->{budget_encumb} / 100;
160     my $budget_expenditure = $budget->{budget_expend};
161
162     if ( $total > $budget_remaining
163       || ( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance)
164       || ( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure) )
165     {
166         my ($template, $loggedinuser, $cookie) = get_template_and_user({
167             template_name   => "acqui/addorder.tt",
168             query           => $input,
169             type            => "intranet",
170             flagsrequired   => {acquisition => 'order_manage'},
171         });
172
173         my $url = $input->referer();
174         unless ( defined $url ) {
175             my $basketno = $input->param('basketno');
176             $url = "/cgi-bin/koha/acqui/basket.pl?basketno=$basketno";
177         }
178
179         my $vars = $input->Vars;
180         my @vars_loop;
181         foreach (keys %$vars) {
182             push @vars_loop, {
183                 name => $_,
184                 values => [$input->param($_)],
185             };
186         }
187
188         if( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance
189           && $total <= $budget_remaining)
190         {
191             $template->param(
192                 encumbrance_exceeded => 1,
193                 encumbrance => sprintf("%.2f", $budget->{'budget_encumb'}),
194             );
195         }
196         if( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure
197           && $total <= $budget_remaining )
198         {
199             my $currency = Koha::Acquisition::Currencies->get_active;
200             $template->param(
201                 expenditure_exceeded => 1,
202                 expenditure => sprintf("%.2f", $budget_expenditure),
203                 currency => ($currency) ? $currency->symbol : '',
204             );
205         }
206         if($total > $budget_remaining){
207             $template->param(budget_exceeded => 1);
208         }
209
210         $template->param(
211             not_enough_budget => 1,
212             referer => $url,
213             vars_loop => \@vars_loop,
214         );
215         output_html_with_http_headers $input, $cookie, $template->output;
216         exit;
217     }
218 }
219
220 # get_template_and_user used only to check auth & get user id
221 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
222     {
223         template_name   => "acqui/booksellers.tt",
224         query           => $input,
225         type            => "intranet",
226         flagsrequired   => { acquisition => 'order_manage' },
227     }
228 );
229
230 # get CGI parameters
231 my $orderinfo = $input->Vars;
232 $orderinfo->{'list_price'}    ||=  0;
233 $orderinfo->{'uncertainprice'} ||= 0;
234 $orderinfo->{subscriptionid} ||= undef;
235
236 my $user     = $input->remote_user;
237 my $basketno = $$orderinfo{basketno};
238 my $basket   = Koha::Acquisition::Baskets->find($basketno);
239
240 # Order related fields we're going to log
241 my @log_order_fields = (
242     'quantity',
243     'listprice',
244     'unitprice',
245     'unitprice_tax_excluded',
246     'unitprice_tax_included',
247     'rrp',
248     'replacementprice',
249     'rrp_tax_excluded',
250     'rrp_tax_included',
251     'ecost',
252     'ecost_tax_excluded',
253     'ecost_tax_included',
254     'tax_rate_on_ordering'
255 );
256
257 # create, modify or delete biblio
258 # create if $quantity>0 and $existing='no'
259 # modify if $quantity>0 and $existing='yes'
260 if ( $basket->{is_standing} || $orderinfo->{quantity} ne '0' ) {
261     #TODO:check to see if biblio exists
262     unless ( $$orderinfo{biblionumber} ) {
263
264         my $record;
265         if ( $use_ACQ_framework ) {
266             my @tags         = $input->multi_param('bib_tag');
267             my @subfields    = $input->multi_param('bib_subfield');
268             my @field_values = $input->multi_param('bib_field_value');
269             my $xml = TransformHtmlToXml( \@tags, \@subfields, \@field_values );
270             $record=MARC::Record::new_from_xml($xml, 'UTF-8');
271         } else {
272             #if it doesn't create it
273             $record = TransformKohaToMarc(
274                 {
275                     "biblio.title"                => "$$orderinfo{title}",
276                     "biblio.author"               => $$orderinfo{author}          ? $$orderinfo{author}        : "",
277                     "biblio.seriestitle"          => $$orderinfo{series}          ? $$orderinfo{series}        : "",
278                     "biblioitems.isbn"            => $$orderinfo{isbn}            ? $$orderinfo{isbn}          : "",
279                     "biblioitems.ean"             => $$orderinfo{ean}             ? $$orderinfo{ean}           : "",
280                     "biblioitems.publishercode"   => $$orderinfo{publishercode}   ? $$orderinfo{publishercode} : "",
281                     "biblioitems.publicationyear" => $$orderinfo{publicationyear} ? $$orderinfo{publicationyear}: "",
282                     "biblio.copyrightdate"        => $$orderinfo{publicationyear} ? $$orderinfo{publicationyear}: "",
283                     "biblioitems.itemtype"        => $$orderinfo{itemtype} ? $$orderinfo{itemtype} : "",
284                     "biblioitems.editionstatement"=> $$orderinfo{editionstatement} ? $$orderinfo{editionstatement} : "",
285                 });
286
287         }
288         C4::Acquisition::FillWithDefaultValues( $record );
289
290         # create the record in catalogue, with framework ''
291         my ($biblionumber,$bibitemnum) = AddBiblio($record,'');
292
293         $orderinfo->{biblionumber}=$biblionumber;
294     }
295
296     # change suggestion status if applicable
297     if ( $orderinfo->{suggestionid} ) {
298         ModSuggestion(
299             {
300                 suggestionid => $orderinfo->{suggestionid},
301                 biblionumber => $orderinfo->{biblionumber},
302                 STATUS       => 'ORDERED',
303             }
304         );
305     }
306
307     $orderinfo->{unitprice} = $orderinfo->{ecost} if not defined $orderinfo->{unitprice} or $orderinfo->{unitprice} eq '';
308
309     $orderinfo = C4::Acquisition::populate_order_with_prices(
310         {
311             order        => $orderinfo,
312             booksellerid => $orderinfo->{booksellerid},
313             ordering     => 1,
314         }
315     );
316
317     # if we already have $ordernumber, then it's an ordermodif
318     my $order = Koha::Acquisition::Order->new($orderinfo);
319     if ( $orderinfo->{ordernumber} ) {
320         ModOrder($orderinfo);
321         # Log the order modification
322         if (C4::Context->preference("AcquisitionLog")) {
323             my $infos = {};
324             foreach my $field(@log_order_fields) {
325                 $infos->{$field} = $orderinfo->{$field};
326             }
327             logaction(
328                 'ACQUISITIONS',
329                 'MODIFY_ORDER',
330                 $orderinfo->{ordernumber},
331                 encode_json($infos)
332             );
333         }
334     }
335     else { # else, it's a new line
336         $order->store;
337         # Log the order creation
338         if (C4::Context->preference("AcquisitionLog")) {
339             my $infos = {};
340             foreach my $field(@log_order_fields) {
341                 $infos->{$field} = $orderinfo->{$field};
342             }
343             logaction(
344                 'ACQUISITIONS',
345                 'CREATE_ORDER',
346                 $order->ordernumber,
347                 encode_json($infos)
348             );
349         }
350     }
351     my $order_users_ids = $input->param('users_ids');
352     my @order_users = split( /:/, $order_users_ids );
353     ModOrderUsers( $order->ordernumber, @order_users );
354
355     # now, add items if applicable
356     if ($basket->effective_create_items eq 'ordering') {
357
358         my @tags         = $input->multi_param('tag');
359         my @subfields    = $input->multi_param('subfield');
360         my @field_values = $input->multi_param('field_value');
361         my @serials      = $input->multi_param('serial');
362         my @itemid       = $input->multi_param('itemid');
363         #Rebuilding ALL the data for items into a hash
364         # parting them on $itemid.
365
366         my %itemhash;
367         my $countdistinct;
368         my $range=scalar(@itemid);
369         for (my $i=0; $i<$range; $i++){
370             unless ($itemhash{$itemid[$i]}){
371             $countdistinct++;
372             }
373         push @{$itemhash{$itemid[$i]}->{'tags'}},$tags[$i];
374         push @{$itemhash{$itemid[$i]}->{'subfields'}},$subfields[$i];
375             push @{$itemhash{$itemid[$i]}->{'field_values'}},$field_values[$i];
376         }
377         foreach my $item (keys %itemhash){
378             my $xml = TransformHtmlToXml( $itemhash{$item}->{'tags'},
379                                     $itemhash{$item}->{'subfields'},
380                                     $itemhash{$item}->{'field_values'},
381                                     undef,
382                                     undef,
383                                     'ITEM');
384             my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
385             my ($barcodefield,$barcodesubfield) = GetMarcFromKohaField('items.barcode');
386             next unless ( defined $barcodefield && defined $barcodesubfield );
387             my $barcode = $record->subfield($barcodefield,$barcodesubfield) || '';
388             my $aBpref = C4::Context->preference('autoBarcode');
389             if( $barcode eq '' && $aBpref ne 'OFF'){
390                 my $barcodeobj;
391                 if ( $aBpref eq 'hbyymmincr'){
392                     my ($homebranchfield,$homebranchsubfield) = GetMarcFromKohaField('items.homebranch');
393                     my $homebranch = $record->subfield($homebranchfield,$homebranchsubfield);
394                     $barcodeobj = C4::Barcodes->new($aBpref, $homebranch);
395                 } else {
396                     $barcodeobj = C4::Barcodes->new($aBpref);
397                 }
398                 $barcode = $barcodeobj->value();
399                 $record->field($barcodefield)->delete_subfield( code => $barcodesubfield);
400                 $record->field($barcodefield)->add_subfields($barcodesubfield => $barcode);
401             }
402             my ($biblionumber,$bibitemnum,$itemnumber) = AddItemFromMarc($record,$$orderinfo{biblionumber});
403             $order->add_item($itemnumber);
404         }
405     }
406
407 }
408
409 if (C4::Context->preference("AcquisitionLog") && $basketno) {
410     my $modified = Koha::Acquisition::Baskets->find( $basketno );
411     logaction(
412         'ACQUISITIONS',
413         'MODIFY_BASKET',
414         $basketno,
415         to_json($modified->unblessed)
416     );
417 }
418
419 my $booksellerid=$$orderinfo{booksellerid};
420 if (my $import_batch_id=$$orderinfo{import_batch_id}) {
421     print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=$basketno&booksellerid=$booksellerid");
422 } elsif ( defined $orderinfo->{invoiceid} ) {
423     print $input->redirect("/cgi-bin/koha/acqui/parcel.pl?invoiceid=" . $orderinfo->{invoiceid});
424 } else {
425     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=$basketno");
426 }