Bug 9978: Replace license header with the correct license (GPLv3+)
[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
133 ### "-------------------- addorder.pl ----------"
134
135 # FIXME: This needs to do actual error checking and possibly return user to the same form,
136 # not just blindly call C4 functions and print a redirect.  
137
138 my $input = new CGI;
139
140 # Check if order total amount exceed allowed budget
141 my $confirm_budget_exceeding = $input->param('confirm_budget_exceeding');
142 unless($confirm_budget_exceeding) {
143     my $budget_id = $input->param('budget_id');
144     my $total = $input->param('total');
145     my $budget = GetBudget($budget_id);
146     my $budget_spent = GetBudgetSpent($budget_id);
147     my $budget_ordered = GetBudgetOrdered($budget_id);
148     my $budget_used = $budget_spent + $budget_ordered;
149     my $budget_remaining = $budget->{budget_amount} - $budget_used;
150     my $budget_encumbrance = $budget->{budget_amount} * $budget->{budget_encumb} / 100;
151     my $budget_expenditure = $budget->{budget_expend};
152
153     if ( $total > $budget_remaining
154       || ( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance)
155       || ( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure) )
156     {
157         my ($template, $loggedinuser, $cookie) = get_template_and_user({
158             template_name   => "acqui/addorder.tt",
159             query           => $input,
160             type            => "intranet",
161             authnotrequired => 0,
162             flagsrequired   => {acquisition => 'order_manage'},
163         });
164
165         my $url = $input->referer();
166         unless ( defined $url ) {
167             my $basketno = $input->param('basketno');
168             $url = "/cgi-bin/koha/acqui/basket.pl?basketno=$basketno";
169         }
170
171         my $vars = $input->Vars;
172         my @vars_loop;
173         foreach (keys %$vars) {
174             push @vars_loop, {
175                 name => $_,
176                 values => [$input->param($_)],
177             };
178         }
179
180         if( ($budget_encumbrance+0) && ($budget_used + $total) > $budget_encumbrance
181           && $total <= $budget_remaining)
182         {
183             $template->param(
184                 encumbrance_exceeded => 1,
185                 encumbrance => sprintf("%.2f", $budget->{'budget_encumb'}),
186             );
187         }
188         if( ($budget_expenditure+0) && ($budget_used + $total) > $budget_expenditure
189           && $total <= $budget_remaining )
190         {
191             my $currency = GetCurrency;
192             $template->param(
193                 expenditure_exceeded => 1,
194                 expenditure => sprintf("%.2f", $budget_expenditure),
195                 currency => ($currency) ? $currency->{'symbol'} : '',
196             );
197         }
198         if($total > $budget_remaining){
199             $template->param(budget_exceeded => 1);
200         }
201
202         $template->param(
203             not_enough_budget => 1,
204             referer => $url,
205             vars_loop => \@vars_loop,
206         );
207         output_html_with_http_headers $input, $cookie, $template->output;
208         exit;
209     }
210 }
211
212 # get_template_and_user used only to check auth & get user id
213 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
214     {
215         template_name   => "acqui/booksellers.tt",
216         query           => $input,
217         type            => "intranet",
218         authnotrequired => 0,
219         flagsrequired   => { acquisition => 'order_manage' },
220         debug           => 1,
221     }
222 );
223
224 # get CGI parameters
225 my $orderinfo                                   = $input->Vars;
226 $orderinfo->{'list_price'}    ||=  0;
227 $orderinfo->{'uncertainprice'} ||= 0;
228 $orderinfo->{subscriptionid} ||= undef;
229
230 my $user = $input->remote_user;
231
232 # create, modify or delete biblio
233 # create if $quantity>0 and $existing='no'
234 # modify if $quantity>0 and $existing='yes'
235 if ( $orderinfo->{quantity} ne '0' ) {
236     #TODO:check to see if biblio exists
237     unless ( $$orderinfo{biblionumber} ) {
238         #if it doesnt create it
239         my $record = TransformKohaToMarc(
240             {
241                 "biblio.title"                => "$$orderinfo{title}",
242                 "biblio.author"               => $$orderinfo{author}          ? $$orderinfo{author}        : "",
243                 "biblio.seriestitle"          => $$orderinfo{series}          ? $$orderinfo{series}        : "",
244                 "biblioitems.isbn"            => $$orderinfo{isbn}            ? $$orderinfo{isbn}          : "",
245                 "biblioitems.ean"             => $$orderinfo{ean}             ? $$orderinfo{ean}           : "",
246                 "biblioitems.publishercode"   => $$orderinfo{publishercode}   ? $$orderinfo{publishercode} : "",
247                 "biblioitems.publicationyear" => $$orderinfo{publicationyear} ? $$orderinfo{publicationyear}: "",
248                 "biblio.copyrightdate"        => $$orderinfo{publicationyear} ? $$orderinfo{publicationyear}: "",
249                 "biblioitems.itemtype"        => $$orderinfo{itemtype} ? $$orderinfo{itemtype} : "",
250                 "biblioitems.editionstatement"=> $$orderinfo{editionstatement} ? $$orderinfo{editionstatement} : "",
251             });
252
253         # create the record in catalogue, with framework ''
254         my ($biblionumber,$bibitemnum) = AddBiblio($record,'');
255         # change suggestion status if applicable
256         if ($$orderinfo{suggestionid}) {
257             ModSuggestion( {suggestionid=>$$orderinfo{suggestionid}, STATUS=>'ORDERED', biblionumber=>$biblionumber} );
258         }
259         $orderinfo->{biblionumber}=$biblionumber;
260     }
261
262     $orderinfo->{unitprice} = $orderinfo->{ecost} if not defined $orderinfo->{unitprice} or $orderinfo->{unitprice} eq '';
263
264     # if we already have $ordernumber, then it's an ordermodif
265     my $order = Koha::Acquisition::Order->new($orderinfo);
266     if ( $orderinfo->{ordernumber} ) {
267         ModOrder($orderinfo);
268         my $order_users_ids = $input->param('users_ids');
269         my @order_users = split( /:/, $order_users_ids );
270
271         ModOrderUsers( $orderinfo->{ordernumber}, @order_users );
272     }
273     else { # else, it's a new line
274         $order->insert;
275     }
276
277     # now, add items if applicable
278     if (C4::Context->preference('AcqCreateItem') eq 'ordering') {
279
280         my @tags         = $input->param('tag');
281         my @subfields    = $input->param('subfield');
282         my @field_values = $input->param('field_value');
283         my @serials      = $input->param('serial');
284         my @itemid       = $input->param('itemid');
285         my @ind_tag      = $input->param('ind_tag');
286         my @indicator    = $input->param('indicator');
287         #Rebuilding ALL the data for items into a hash
288         # parting them on $itemid.
289
290         my %itemhash;
291         my $countdistinct;
292         my $range=scalar(@itemid);
293         for (my $i=0; $i<$range; $i++){
294             unless ($itemhash{$itemid[$i]}){
295             $countdistinct++;
296             }
297             push @{$itemhash{$itemid[$i]}->{'tags'}},$tags[$i];
298             push @{$itemhash{$itemid[$i]}->{'subfields'}},$subfields[$i];
299             push @{$itemhash{$itemid[$i]}->{'field_values'}},$field_values[$i];
300             push @{$itemhash{$itemid[$i]}->{'ind_tag'}},$ind_tag[$i];
301             push @{$itemhash{$itemid[$i]}->{'indicator'}},$indicator[$i];
302         }
303         foreach my $item (keys %itemhash){
304
305             my $xml = TransformHtmlToXml( $itemhash{$item}->{'tags'},
306                                     $itemhash{$item}->{'subfields'},
307                                     $itemhash{$item}->{'field_values'},
308                                     $itemhash{$item}->{'ind_tag'},
309                                     $itemhash{$item}->{'indicator'},
310                                     'ITEM');
311             my $record=MARC::Record::new_from_xml($xml, 'UTF-8');
312             my ($biblionumber,$bibitemnum,$itemnumber) = AddItemFromMarc($record,$$orderinfo{biblionumber});
313             $order->add_item($itemnumber);
314         }
315     }
316
317 }
318
319 my $basketno=$$orderinfo{basketno};
320 my $booksellerid=$$orderinfo{booksellerid};
321 if (my $import_batch_id=$$orderinfo{import_batch_id}) {
322     print $input->redirect("/cgi-bin/koha/acqui/addorderiso2709.pl?import_batch_id=$import_batch_id&basketno=$basketno&booksellerid=$booksellerid");
323 } elsif ( defined $orderinfo->{invoiceid} ) {
324     print $input->redirect("/cgi-bin/koha/acqui/parcel.pl?invoiceid=" . $orderinfo->{invoiceid});
325 } else {
326     print $input->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=$basketno");
327 }