Bug 15685: Allow creation of items (AcqCreateItem) to be customizable per-basket
[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 neworderbiblio.pl to add an order from nothing.
36
37 =item neworderempty.pl to add an order from an existing biblio.
38
39 =item newordersuggestion.pl to add an order from an existing suggestion.
40
41 =back
42
43 =head1 CGI PARAMETERS
44
45 All of the cgi parameters below are related to the new order.
46
47 =over
48
49 =item C<ordernumber>
50 the number of this new order.
51
52 =item C<basketno>
53 the number of this new basket
54
55 =item C<booksellerid>
56 the bookseller the librarian has to pay.
57
58 =item C<existing>
59
60 =item C<title>
61 the title of the record ordered.
62
63 =item C<author>
64 the author of the record ordered.
65
66 =item C<copyrightdate>
67 the copyrightdate of the record ordered.
68
69 =item C<ISBN>
70 the ISBN of the record ordered.
71
72 =item C<format>
73
74 =item C<quantity>
75 the quantity to order.
76
77 =item C<list_price>
78 the price of this order.
79
80 =item C<uncertainprice>
81 uncertain price, can't close basket until prices of all orders are known.
82
83 =item C<branch>
84 the branch where this order will be received.
85
86 =item C<series>
87
88 =item C<notes>
89 Notes on this basket.
90
91 =item C<budget_id>
92 budget_id used to pay this order.
93
94 =item C<sort1> & C<sort2>
95
96 =item C<rrp>
97
98 =item C<ecost>
99
100 =item C<GST>
101
102 =item C<budget>
103
104 =item C<cost>
105
106 =item C<sub>
107
108 =item C<invoice>
109 the number of the invoice for this order.
110
111 =item C<publishercode>
112
113 =item C<suggestionid>
114 if it is an order from an existing suggestion : the id of this suggestion.
115
116 =item C<donation>
117
118 =back
119
120 =cut
121
122 use strict;
123 use warnings;
124 use CGI qw ( -utf8 );
125 use C4::Auth;           # get_template_and_user
126 use C4::Acquisition;    # ModOrder
127 use C4::Suggestions;    # ModStatus
128 use C4::Biblio;         # AddBiblio TransformKohaToMarc
129 use C4::Budgets;
130 use C4::Items;
131 use C4::Output;
132 use Koha::Acquisition::Currencies;
133 use Koha::Acquisition::Orders;
134 use C4::Barcodes;
135
136 ### "-------------------- addorder.pl ----------"
137
138 # FIXME: This needs to do actual error checking and possibly return user to the same form,
139 # not just blindly call C4 functions and print a redirect.  
140
141 my $input = new CGI;
142
143 # Check if order total amount exceed allowed budget
144 my $confirm_budget_exceeding = $input->param('confirm_budget_exceeding');
145 unless($confirm_budget_exceeding) {
146     my $budget_id = $input->param('budget_id');
147     my $total = $input->param('total');
148     my $budget = GetBudget($budget_id);
149     my $budget_spent = GetBudgetSpent($budget_id);
150     my $budget_ordered = GetBudgetOrdered($budget_id);
151     my $budget_used = $budget_spent + $budget_ordered;
152     my $budget_remaining = $budget->{budget_amount} - $budget_used;
153     my $budget_encumbrance = $budget->{budget_amount} * $budget->{budget_encumb} / 100;
154     my $budget_expenditure = $budget->{budget_expend};
155
156     if ( $total > $budget_remaining
157       || ( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance)
158       || ( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure) )
159     {
160         my ($template, $loggedinuser, $cookie) = get_template_and_user({
161             template_name   => "acqui/addorder.tt",
162             query           => $input,
163             type            => "intranet",
164             authnotrequired => 0,
165             flagsrequired   => {acquisition => 'order_manage'},
166         });
167
168         my $url = $input->referer();
169         unless ( defined $url ) {
170             my $basketno = $input->param('basketno');
171             $url = "/cgi-bin/koha/acqui/basket.pl?basketno=$basketno";
172         }
173
174         my $vars = $input->Vars;
175         my @vars_loop;
176         foreach (keys %$vars) {
177             push @vars_loop, {
178                 name => $_,
179                 values => [$input->param($_)],
180             };
181         }
182
183         if( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance
184           && $total <= $budget_remaining)
185         {
186             $template->param(
187                 encumbrance_exceeded => 1,
188                 encumbrance => sprintf("%.2f", $budget->{'budget_encumb'}),
189             );
190         }
191         if( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure
192           && $total <= $budget_remaining )
193         {
194             my $currency = Koha::Acquisition::Currencies->get_active;
195             $template->param(
196                 expenditure_exceeded => 1,
197                 expenditure => sprintf("%.2f", $budget_expenditure),
198                 currency => ($currency) ? $currency->symbol : '',
199             );
200         }
201         if($total > $budget_remaining){
202             $template->param(budget_exceeded => 1);
203         }
204
205         $template->param(
206             not_enough_budget => 1,
207             referer => $url,
208             vars_loop => \@vars_loop,
209         );
210         output_html_with_http_headers $input, $cookie, $template->output;
211         exit;
212     }
213 }
214
215 # get_template_and_user used only to check auth & get user id
216 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
217     {
218         template_name   => "acqui/booksellers.tt",
219         query           => $input,
220         type            => "intranet",
221         authnotrequired => 0,
222         flagsrequired   => { acquisition => 'order_manage' },
223         debug           => 1,
224     }
225 );
226
227 # get CGI parameters
228 my $orderinfo = $input->Vars;
229 $orderinfo->{'list_price'}    ||=  0;
230 $orderinfo->{'uncertainprice'} ||= 0;
231 $orderinfo->{subscriptionid} ||= undef;
232
233 my $basketno=$$orderinfo{basketno};
234 my $basket = GetBasket($basketno);
235
236 my $user = $input->remote_user;
237 my $basketno=$$orderinfo{basketno};
238 my $basket = Koha::Acquisition::Baskets->find( $basketno );
239
240 # create, modify or delete biblio
241 # create if $quantity>0 and $existing='no'
242 # modify if $quantity>0 and $existing='yes'
243 if ( $basket->{is_standing} || $orderinfo->{quantity} ne '0' ) {
244     #TODO:check to see if biblio exists
245     unless ( $$orderinfo{biblionumber} ) {
246         #if it doesn't create it
247         my $record = TransformKohaToMarc(
248             {
249                 "biblio.title"                => "$$orderinfo{title}",
250                 "biblio.author"               => $$orderinfo{author}          ? $$orderinfo{author}        : "",
251                 "biblio.seriestitle"          => $$orderinfo{series}          ? $$orderinfo{series}        : "",
252                 "biblioitems.isbn"            => $$orderinfo{isbn}            ? $$orderinfo{isbn}          : "",
253                 "biblioitems.ean"             => $$orderinfo{ean}             ? $$orderinfo{ean}           : "",
254                 "biblioitems.publishercode"   => $$orderinfo{publishercode}   ? $$orderinfo{publishercode} : "",
255                 "biblioitems.publicationyear" => $$orderinfo{publicationyear} ? $$orderinfo{publicationyear}: "",
256                 "biblio.copyrightdate"        => $$orderinfo{publicationyear} ? $$orderinfo{publicationyear}: "",
257                 "biblioitems.itemtype"        => $$orderinfo{itemtype} ? $$orderinfo{itemtype} : "",
258                 "biblioitems.editionstatement"=> $$orderinfo{editionstatement} ? $$orderinfo{editionstatement} : "",
259             });
260
261         C4::Acquisition::FillWithDefaultValues( $record );
262
263         # create the record in catalogue, with framework ''
264         my ($biblionumber,$bibitemnum) = AddBiblio($record,'');
265         # change suggestion status if applicable
266         if ($$orderinfo{suggestionid}) {
267             ModSuggestion( {suggestionid=>$$orderinfo{suggestionid}, STATUS=>'ORDERED', biblionumber=>$biblionumber} );
268         }
269         $orderinfo->{biblionumber}=$biblionumber;
270     }
271
272     $orderinfo->{unitprice} = $orderinfo->{ecost} if not defined $orderinfo->{unitprice} or $orderinfo->{unitprice} eq '';
273
274     $orderinfo = C4::Acquisition::populate_order_with_prices(
275         {
276             order        => $orderinfo,
277             booksellerid => $orderinfo->{booksellerid},
278             ordering     => 1,
279         }
280     );
281
282     # if we already have $ordernumber, then it's an ordermodif
283     my $order = Koha::Acquisition::Order->new($orderinfo);
284     if ( $orderinfo->{ordernumber} ) {
285         ModOrder($orderinfo);
286         my $order_users_ids = $input->param('users_ids');
287         my @order_users = split( /:/, $order_users_ids );
288
289         ModOrderUsers( $orderinfo->{ordernumber}, @order_users );
290     }
291     else { # else, it's a new line
292         $order->store;
293     }
294
295     # now, add items if applicable
296     if ($basket->effective_create_items eq 'ordering') {
297
298         my @tags         = $input->multi_param('tag');
299         my @subfields    = $input->multi_param('subfield');
300         my @field_values = $input->multi_param('field_value');
301         my @serials      = $input->multi_param('serial');
302         my @itemid       = $input->multi_param('itemid');
303         my @ind_tag      = $input->multi_param('ind_tag');
304         my @indicator    = $input->multi_param('indicator');
305         #Rebuilding ALL the data for items into a hash
306         # parting them on $itemid.
307
308         my %itemhash;
309         my $countdistinct;
310         my $range=scalar(@itemid);
311         for (my $i=0; $i<$range; $i++){
312             unless ($itemhash{$itemid[$i]}){
313             $countdistinct++;
314             }
315             push @{$itemhash{$itemid[$i]}->{'tags'}},$tags[$i];
316             push @{$itemhash{$itemid[$i]}->{'subfields'}},$subfields[$i];
317             push @{$itemhash{$itemid[$i]}->{'field_values'}},$field_values[$i];
318             push @{$itemhash{$itemid[$i]}->{'ind_tag'}},$ind_tag[$i];
319             push @{$itemhash{$itemid[$i]}->{'indicator'}},$indicator[$i];
320         }
321         foreach my $item (keys %itemhash){
322             my $xml = TransformHtmlToXml( $itemhash{$item}->{'tags'},
323                                     $itemhash{$item}->{'subfields'},
324                                     $itemhash{$item}->{'field_values'},
325                                     $itemhash{$item}->{'indicator'},
326                                     $itemhash{$item}->{'ind_tag'},
327                                     'ITEM');
328             my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
329             my ($barcodefield,$barcodesubfield) = GetMarcFromKohaField('items.barcode');
330             next unless ( defined $barcodefield && defined $barcodesubfield );
331             my $barcode = $record->subfield($barcodefield,$barcodesubfield) || '';
332             my $aBpref = C4::Context->preference('autoBarcode');
333             if( $barcode eq '' && $aBpref ne 'OFF'){
334                 my $barcodeobj;
335                 if ( $aBpref eq 'hbyymmincr'){
336                     my ($homebranchfield,$homebranchsubfield) = GetMarcFromKohaField('items.homebranch');
337                     my $homebranch = $record->subfield($homebranchfield,$homebranchsubfield);
338                     $barcodeobj = C4::Barcodes->new($aBpref, $homebranch);
339                 } else {
340                     $barcodeobj = C4::Barcodes->new($aBpref);
341                 }
342                 $barcode = $barcodeobj->value();
343                 $record->field($barcodefield)->delete_subfield( code => $barcodesubfield);
344                 $record->field($barcodefield)->add_subfields($barcodesubfield => $barcode);
345             }
346             my ($biblionumber,$bibitemnum,$itemnumber) = AddItemFromMarc($record,$$orderinfo{biblionumber});
347             $order->add_item($itemnumber);
348         }
349     }
350
351 }
352
353 my $booksellerid=$$orderinfo{booksellerid};
354 if (my $import_batch_id=$$orderinfo{import_batch_id}) {
355     print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=$basketno&booksellerid=$booksellerid");
356 } elsif ( defined $orderinfo->{invoiceid} ) {
357     print $input->redirect("/cgi-bin/koha/acqui/parcel.pl?invoiceid=" . $orderinfo->{invoiceid});
358 } else {
359     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=$basketno");
360 }