[MT2593] Fixed budget amount computation in acqui-home
[koha.git] / acqui / parcel.pl
1 #!/usr/bin/perl
2
3 #script to recieve orders
4
5
6 # Copyright 2000-2002 Katipo Communications
7 # Copyright 2008-2009 BibLibre SARL
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along with
21 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
22 # Suite 330, Boston, MA  02111-1307 USA
23
24 =head1 NAME
25
26 parcel.pl
27
28 =head1 DESCRIPTION
29 This script shows all orders receipt or pending for a given supplier.
30 It allows to write an order as 'received' when he arrives.
31
32 =head1 CGI PARAMETERS
33
34 =over 4
35
36 =item supplierid
37 To know the supplier this script has to show orders.
38
39 =item code
40 is the bookseller invoice number.
41
42 =item freight
43
44
45 =item gst
46
47
48 =item datereceived
49 To filter the results list on this given date.
50
51 =back
52
53 =cut
54
55 use C4::Auth;
56 use C4::Acquisition;
57 use C4::Budgets;
58 use C4::Bookseller;
59 use C4::Biblio;
60 use C4::Items;
61 use CGI;
62 use C4::Output;
63 use C4::Dates qw/format_date format_date_in_iso/;
64 use JSON;
65
66 use strict;
67
68 my $input=new CGI;
69 my $supplierid=$input->param('supplierid');
70 my $bookseller=GetBookSellerFromId($supplierid);
71
72 my $invoice=$input->param('invoice') || '';
73 my $freight=$input->param('freight');
74 my $gst= $input->param('gst') || $bookseller->{gstrate} || C4::Context->preference("gist") || 0;
75 my $datereceived =  ($input->param('op') eq 'new') ? C4::Dates->new($input->param('datereceived')) 
76                                         :  C4::Dates->new($input->param('datereceived'), 'iso')   ;
77 $datereceived = C4::Dates->new() unless $datereceived;
78 my $code            = $input->param('code');
79 my @rcv_err         = $input->param('error');
80 my @rcv_err_barcode = $input->param('error_bc');
81
82 my $startfrom=$input->param('startfrom');
83 my $resultsperpage = $input->param('resultsperpage');
84 $resultsperpage = 20 unless ($resultsperpage);
85 $startfrom=0 unless ($startfrom);
86
87 if($input->param('format') eq "json"){
88     my ($template, $loggedinuser, $cookie)
89         = get_template_and_user({template_name => "acqui/ajax.tmpl",
90                  query => $input,
91                                  type => "intranet",
92                  authnotrequired => 0,
93                  flagsrequired => {acquisition => 'order_receive'},
94                  debug => 1,
95     });
96        
97     my @datas;
98     my $search   = $input->param('search') || '';
99     my $supplier = $input->param('supplierid') || '';
100     my $basketno = $input->param('basketno') || '';
101     my $orderno  = $input->param('orderno') || '';
102
103     my $orders = SearchOrder($orderno, $search, $supplier, $basketno);
104     foreach my $order (@$orders){
105         if($order->{quantityreceived} < $order->{quantity}){
106             my $data = {};
107             
108             $data->{basketno} = $order->{basketno};
109             $data->{ordernumber} = $order->{ordernumber};
110             $data->{title} = $order->{title};
111             $data->{author} = $order->{author};
112             $data->{biblionumber} = $order->{biblionumber};
113             $data->{freight} = $order->{freight};
114             $data->{quantity} = $order->{quantity};
115             $data->{ecost} = $order->{ecost};
116             $data->{ordertotal} = sprintf("%.2f",$order->{ecost}*$order->{quantity});
117             push @datas, $data;
118         }
119     }
120     
121     my $json_text = to_json(\@datas);
122     $template->param(return => $json_text);
123     output_html_with_http_headers $input, $cookie, $template->output;
124     exit;
125 }
126
127 my ($template, $loggedinuser, $cookie)
128     = get_template_and_user({template_name => "acqui/parcel.tmpl",
129                  query => $input,
130                                  type => "intranet",
131                  authnotrequired => 0,
132                  flagsrequired => {acquisition => 'order_receive'},
133                  debug => 1,
134 });
135
136 my $action = $input->param('action');
137 my $ordernumber = $input->param('ordernumber');
138 my $biblionumber = $input->param('biblionumber');
139
140 # If canceling an order
141 if ($action eq "cancelorder") {
142
143     my $error_delitem;
144     my $error_delbiblio;
145
146     # We delete the order
147     DelOrder($biblionumber, $ordernumber);
148
149     # We delete all the items related to this order
150     my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
151     foreach (@itemnumbers) {
152         my $delcheck = DelItemCheck(C4::Context->dbh, $biblionumber, $_);
153         # (should always success, as no issue should exist on item on order)
154         if ($delcheck != 1) { $error_delitem = 1; }
155     }
156
157     # We get the number of remaining items
158     my $itemcount = GetItemsCount($biblionumber);
159     
160     # If there are no items left,
161     if ($itemcount eq 0) {
162         # We delete the record
163         $error_delbiblio = DelBiblio($biblionumber);    
164     }
165
166     if ($error_delitem || $error_delbiblio) {
167         warn $error_delitem;
168         warn $error_delbiblio;
169         if ($error_delitem)   { $template->param(error_delitem => 1); }
170         if ($error_delbiblio) { $template->param(error_delbiblio => 1); }
171     } else {
172         $template->param(success_delorder => 1);
173     }
174 }
175
176 # If receiving error, report the error (coming from finishrecieve.pl(sic)).
177 if( scalar(@rcv_err) ) {
178         my $cnt=0;
179         my $error_loop;
180         for my $err (@rcv_err) {
181                 push @$error_loop, { "error_$err" => 1 , barcode => $rcv_err_barcode[$cnt] };
182                 $cnt++;
183         }
184         $template->param( receive_error => 1 ,
185                                                 error_loop => $error_loop,
186                                         );
187 }
188
189 my $cfstr         = "%.2f";                                                           # currency format string -- could get this from currency table.
190 my @parcelitems   = GetParcel($supplierid, $invoice, $datereceived->output('iso'));
191 my $countlines    = scalar @parcelitems;
192 my $totalprice    = 0;
193 my $totalfreight  = 0;
194 my $totalquantity = 0;
195 my $total;
196 my $tototal;
197 my @loop_received = ();
198
199 for (my $i = 0 ; $i < $countlines ; $i++) {
200
201     #$total=($parcelitems[$i]->{'unitprice'} + $parcelitems[$i]->{'freight'}) * $parcelitems[$i]->{'quantityreceived'};   #weird, are the freight fees counted by book? (pierre)
202     $total = ($parcelitems[$i]->{'unitprice'}) * $parcelitems[$i]->{'quantityreceived'};    #weird, are the freight fees counted by book? (pierre)
203     $parcelitems[$i]->{'unitprice'} += 0;
204     my %line;
205     %line          = %{ $parcelitems[$i] };
206     $line{invoice} = $invoice;
207     $line{gst}     = $gst;
208     $line{total} = sprintf($cfstr, $total);
209     $line{supplierid} = $supplierid;
210     push @loop_received, \%line;
211     $totalprice += $parcelitems[$i]->{'unitprice'};
212     $line{unitprice} = sprintf($cfstr, $parcelitems[$i]->{'unitprice'});
213
214     #double FIXME - totalfreight is redefined later.
215
216 # FIXME - each order in a  parcel holds the freight for the whole parcel. This means if you receive a parcel with items from multiple budgets, you'll see the freight charge in each budget..
217     if ($i > 0 && $totalfreight != $parcelitems[$i]->{'freight'}) {
218         warn "FREIGHT CHARGE MISMATCH!!";
219     }
220     $totalfreight = $parcelitems[$i]->{'freight'};
221     $totalquantity += $parcelitems[$i]->{'quantityreceived'};
222     $tototal       += $total;
223 }
224
225 my $pendingorders = GetPendingOrders($supplierid);
226 my $countpendings = scalar @$pendingorders;
227
228 # pending orders totals
229 my ($totalPunitprice, $totalPquantity, $totalPecost, $totalPqtyrcvd);
230 my $ordergrandtotal;
231 my @loop_orders = ();
232 for (my $i = 0 ; $i < $countpendings ; $i++) {
233     my %line;
234     %line = %{$pendingorders->[$i]};
235     $line{quantity}+=0;
236     $line{quantityreceived}+=0;
237     $line{unitprice}+=0;
238     $totalPunitprice += $line{unitprice};
239     $totalPquantity +=$line{quantity};
240     $totalPqtyrcvd +=$line{quantityreceived};
241     $totalPecost += $line{ecost};
242     $line{ecost} = sprintf("%.2f",$line{ecost});
243     $line{ordertotal} = sprintf("%.2f",$line{ecost}*$line{quantity});
244     $line{unitprice} = sprintf("%.2f",$line{unitprice});
245     $line{invoice} = $invoice;
246     $line{gst} = $gst;
247     $line{total} = $total;
248     $line{supplierid} = $supplierid;
249     $ordergrandtotal += $line{ecost} * $line{quantity};
250     push @loop_orders, \%line if ($i >= $startfrom and $i < $startfrom + $resultsperpage);
251 }
252 $freight = $totalfreight unless $freight;
253
254 my $count = $countpendings;
255
256 if ($count>$resultsperpage){
257     my $displaynext=0;
258     my $displayprev=$startfrom;
259     if(($count - ($startfrom+$resultsperpage)) > 0 ) {
260         $displaynext = 1;
261     }
262
263     my @numbers = ();
264     for (my $i=1; $i<$count/$resultsperpage+1; $i++) {
265             my $highlight=0;
266             ($startfrom/$resultsperpage==($i-1)) && ($highlight=1);
267             push @numbers, { number => $i,
268                 highlight => $highlight ,
269                 startfrom => ($i-1)*$resultsperpage};
270     }
271
272     my $from = $startfrom*$resultsperpage+1;
273     my $to;
274     if($count < (($startfrom+1)*$resultsperpage)){
275         $to = $count;
276     } else {
277         $to = (($startfrom+1)*$resultsperpage);
278     }
279     $template->param(numbers=>\@numbers,
280                      displaynext=>$displaynext,
281                      displayprev=>$displayprev,
282                      nextstartfrom=>(($startfrom+$resultsperpage<$count)?$startfrom+$resultsperpage:$count),
283                      prevstartfrom=>(($startfrom-$resultsperpage>0)?$startfrom-$resultsperpage:0)
284                     );
285 }
286
287 #$totalfreight=$freight;
288 $tototal = $tototal + $freight;
289
290 $template->param(
291     invoice               => $invoice,
292     datereceived          => $datereceived->output('iso'),
293     invoicedatereceived   => $datereceived->output('iso'),
294     formatteddatereceived => $datereceived->output(),
295     name                  => $bookseller->{'name'},
296     supplierid            => $supplierid,
297     gst                   => $gst,
298     freight               => $freight,
299     invoice               => $invoice,
300     countreceived         => $countlines,
301     loop_received         => \@loop_received,
302     countpending          => $countpendings,
303     loop_orders           => \@loop_orders,
304     totalprice            => sprintf($cfstr, $totalprice),
305     totalfreight          => $totalfreight,
306     totalquantity         => $totalquantity,
307     tototal               => sprintf($cfstr, $tototal),
308     ordergrandtotal       => sprintf($cfstr, $ordergrandtotal),
309     gst                   => $gst,
310     grandtot              => sprintf($cfstr, $tototal + $gst),
311     totalPunitprice       => sprintf("%.2f", $totalPunitprice),
312     totalPquantity        => $totalPquantity,
313     totalPqtyrcvd         => $totalPqtyrcvd,
314     totalPecost           => sprintf("%.2f", $totalPecost),
315     resultsperpage        => $resultsperpage,
316 );
317 output_html_with_http_headers $input, $cookie, $template->output;