(BUG #4348) parcel.pl: list with duplicates orders after a clearfilter
[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
21 # with Koha; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 strict;
56 #use warnings; FIXME - Bug 2505
57 use C4::Auth;
58 use C4::Acquisition;
59 use C4::Budgets;
60 use C4::Bookseller;
61 use C4::Biblio;
62 use C4::Items;
63 use CGI;
64 use C4::Output;
65 use C4::Dates qw/format_date format_date_in_iso/;
66 use JSON;
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->{isbn} = $order->{isbn};
113             $data->{booksellerid} = $order->{booksellerid};
114             $data->{biblionumber} = $order->{biblionumber};
115             $data->{freight} = $order->{freight};
116             $data->{quantity} = $order->{quantity};
117             $data->{ecost} = $order->{ecost};
118             $data->{ordertotal} = sprintf("%.2f",$order->{ecost}*$order->{quantity});
119             push @datas, $data;
120         }
121     }
122     
123     my $json_text = to_json(\@datas);
124     $template->param(return => $json_text);
125     output_html_with_http_headers $input, $cookie, $template->output;
126     exit;
127 }
128
129 my ($template, $loggedinuser, $cookie)
130     = get_template_and_user({template_name => "acqui/parcel.tmpl",
131                  query => $input,
132                                  type => "intranet",
133                  authnotrequired => 0,
134                  flagsrequired => {acquisition => 'order_receive'},
135                  debug => 1,
136 });
137
138 my $action = $input->param('action');
139 my $ordernumber = $input->param('ordernumber');
140 my $biblionumber = $input->param('biblionumber');
141
142 # If canceling an order
143 if ($action eq "cancelorder") {
144
145     my $error_delitem;
146     my $error_delbiblio;
147
148     # We delete the order
149     DelOrder($biblionumber, $ordernumber);
150
151     # We delete all the items related to this order
152     my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
153     foreach (@itemnumbers) {
154         my $delcheck = DelItemCheck(C4::Context->dbh, $biblionumber, $_);
155         # (should always success, as no issue should exist on item on order)
156         if ($delcheck != 1) { $error_delitem = 1; }
157     }
158
159     # We get the number of remaining items
160     my $itemcount = GetItemsCount($biblionumber);
161     
162     # If there are no items left,
163     if ($itemcount eq 0) {
164         # We delete the record
165         $error_delbiblio = DelBiblio($biblionumber);    
166     }
167
168     if ($error_delitem || $error_delbiblio) {
169         warn $error_delitem;
170         warn $error_delbiblio;
171         if ($error_delitem)   { $template->param(error_delitem => 1); }
172         if ($error_delbiblio) { $template->param(error_delbiblio => 1); }
173     } else {
174         $template->param(success_delorder => 1);
175     }
176 }
177
178 # If receiving error, report the error (coming from finishrecieve.pl(sic)).
179 if( scalar(@rcv_err) ) {
180         my $cnt=0;
181         my $error_loop;
182         for my $err (@rcv_err) {
183                 push @$error_loop, { "error_$err" => 1 , barcode => $rcv_err_barcode[$cnt] };
184                 $cnt++;
185         }
186         $template->param( receive_error => 1 ,
187                                                 error_loop => $error_loop,
188                                         );
189 }
190
191 my $cfstr         = "%.2f";                                                           # currency format string -- could get this from currency table.
192 my @parcelitems   = GetParcel($supplierid, $invoice, $datereceived->output('iso'));
193 my $countlines    = scalar @parcelitems;
194 my $totalprice    = 0;
195 my $totalfreight  = 0;
196 my $totalquantity = 0;
197 my $total;
198 my $tototal;
199 my @loop_received = ();
200
201 for (my $i = 0 ; $i < $countlines ; $i++) {
202
203     #$total=($parcelitems[$i]->{'unitprice'} + $parcelitems[$i]->{'freight'}) * $parcelitems[$i]->{'quantityreceived'};   #weird, are the freight fees counted by book? (pierre)
204     $total = ($parcelitems[$i]->{'unitprice'}) * $parcelitems[$i]->{'quantityreceived'};    #weird, are the freight fees counted by book? (pierre)
205     $parcelitems[$i]->{'unitprice'} += 0;
206     my %line;
207     %line          = %{ $parcelitems[$i] };
208     $line{invoice} = $invoice;
209     $line{gst}     = $gst;
210     $line{total} = sprintf($cfstr, $total);
211     $line{supplierid} = $supplierid;
212     push @loop_received, \%line;
213     $totalprice += $parcelitems[$i]->{'unitprice'};
214     $line{unitprice} = sprintf($cfstr, $parcelitems[$i]->{'unitprice'});
215
216     #double FIXME - totalfreight is redefined later.
217
218 # 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..
219     if ($i > 0 && $totalfreight != $parcelitems[$i]->{'freight'}) {
220         warn "FREIGHT CHARGE MISMATCH!!";
221     }
222     $totalfreight = $parcelitems[$i]->{'freight'};
223     $totalquantity += $parcelitems[$i]->{'quantityreceived'};
224     $tototal       += $total;
225 }
226
227 my $pendingorders = GetPendingOrders($supplierid);
228 my $countpendings = scalar @$pendingorders;
229
230 # pending orders totals
231 my ($totalPunitprice, $totalPquantity, $totalPecost, $totalPqtyrcvd);
232 my $ordergrandtotal;
233 my @loop_orders = ();
234 for (my $i = 0 ; $i < $countpendings ; $i++) {
235     my %line;
236     %line = %{$pendingorders->[$i]};
237     $line{quantity}+=0;
238     $line{quantityreceived}+=0;
239     $line{unitprice}+=0;
240     $totalPunitprice += $line{unitprice};
241     $totalPquantity +=$line{quantity};
242     $totalPqtyrcvd +=$line{quantityreceived};
243     $totalPecost += $line{ecost};
244     $line{ecost} = sprintf("%.2f",$line{ecost});
245     $line{ordertotal} = sprintf("%.2f",$line{ecost}*$line{quantity});
246     $line{unitprice} = sprintf("%.2f",$line{unitprice});
247     $line{invoice} = $invoice;
248     $line{gst} = $gst;
249     $line{total} = $total;
250     $line{supplierid} = $supplierid;
251     $ordergrandtotal += $line{ecost} * $line{quantity};
252     push @loop_orders, \%line if ($i >= $startfrom and $i < $startfrom + $resultsperpage);
253 }
254 $freight = $totalfreight unless $freight;
255
256 my $count = $countpendings;
257
258 if ($count>$resultsperpage){
259     my $displaynext=0;
260     my $displayprev=$startfrom;
261     if(($count - ($startfrom+$resultsperpage)) > 0 ) {
262         $displaynext = 1;
263     }
264
265     my @numbers = ();
266     for (my $i=1; $i<$count/$resultsperpage+1; $i++) {
267             my $highlight=0;
268             ($startfrom/$resultsperpage==($i-1)) && ($highlight=1);
269             push @numbers, { number => $i,
270                 highlight => $highlight ,
271                 startfrom => ($i-1)*$resultsperpage};
272     }
273
274     my $from = $startfrom*$resultsperpage+1;
275     my $to;
276     if($count < (($startfrom+1)*$resultsperpage)){
277         $to = $count;
278     } else {
279         $to = (($startfrom+1)*$resultsperpage);
280     }
281     $template->param(numbers=>\@numbers,
282                      displaynext=>$displaynext,
283                      displayprev=>$displayprev,
284                      nextstartfrom=>(($startfrom+$resultsperpage<$count)?$startfrom+$resultsperpage:$count),
285                      prevstartfrom=>(($startfrom-$resultsperpage>0)?$startfrom-$resultsperpage:0)
286                     );
287 }
288
289 #$totalfreight=$freight;
290 $tototal = $tototal + $freight;
291
292 $template->param(
293     invoice               => $invoice,
294     datereceived          => $datereceived->output('iso'),
295     invoicedatereceived   => $datereceived->output('iso'),
296     formatteddatereceived => $datereceived->output(),
297     name                  => $bookseller->{'name'},
298     supplierid            => $supplierid,
299     gst                   => $gst,
300     freight               => $freight,
301     invoice               => $invoice,
302     countreceived         => $countlines,
303     loop_received         => \@loop_received,
304     countpending          => $countpendings,
305     loop_orders           => \@loop_orders,
306     totalprice            => sprintf($cfstr, $totalprice),
307     totalfreight          => $totalfreight,
308     totalquantity         => $totalquantity,
309     tototal               => sprintf($cfstr, $tototal),
310     ordergrandtotal       => sprintf($cfstr, $ordergrandtotal),
311     gst                   => $gst,
312     grandtot              => sprintf($cfstr, $tototal + $gst),
313     totalPunitprice       => sprintf("%.2f", $totalPunitprice),
314     totalPquantity        => $totalPquantity,
315     totalPqtyrcvd         => $totalPqtyrcvd,
316     totalPecost           => sprintf("%.2f", $totalPecost),
317     resultsperpage        => $resultsperpage,
318 );
319 output_html_with_http_headers $input, $cookie, $template->output;