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