Merge remote branch 'kc/new/biblibre_reports' into kcmaster
[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
30 This script shows all orders receipt or pending for a given supplier.
31 It allows to write an order as 'received' when he arrives.
32
33 =head1 CGI PARAMETERS
34
35 =over 4
36
37 =item supplierid
38
39 To know the supplier this script has to show orders.
40
41 =item code
42
43 is the bookseller invoice number.
44
45 =item freight
46
47
48 =item gst
49
50
51 =item datereceived
52
53 To filter the results list on this given date.
54
55 =back
56
57 =cut
58
59 use strict;
60 #use warnings; FIXME - Bug 2505
61 use C4::Auth;
62 use C4::Acquisition;
63 use C4::Budgets;
64 use C4::Bookseller;
65 use C4::Biblio;
66 use C4::Items;
67 use CGI;
68 use C4::Output;
69 use C4::Dates qw/format_date format_date_in_iso/;
70 use JSON;
71
72 my $input=new CGI;
73 my $supplierid=$input->param('supplierid');
74 my $bookseller=GetBookSellerFromId($supplierid);
75
76 my $invoice=$input->param('invoice') || '';
77 my $freight=$input->param('freight');
78 my $gst= $input->param('gst') || $bookseller->{gstrate} || C4::Context->preference("gist") || 0;
79 my $datereceived =  ($input->param('op') eq 'new') ? C4::Dates->new($input->param('datereceived')) 
80                                         :  C4::Dates->new($input->param('datereceived'), 'iso')   ;
81 $datereceived = C4::Dates->new() unless $datereceived;
82 my $code            = $input->param('code');
83 my @rcv_err         = $input->param('error');
84 my @rcv_err_barcode = $input->param('error_bc');
85
86 my $startfrom=$input->param('startfrom');
87 my $resultsperpage = $input->param('resultsperpage');
88 $resultsperpage = 20 unless ($resultsperpage);
89 $startfrom=0 unless ($startfrom);
90
91 if($input->param('format') eq "json"){
92     my ($template, $loggedinuser, $cookie)
93         = get_template_and_user({template_name => "acqui/ajax.tmpl",
94                  query => $input,
95                                  type => "intranet",
96                  authnotrequired => 0,
97                  flagsrequired => {acquisition => 'order_receive'},
98                  debug => 1,
99     });
100        
101     my @datas;
102     my $search   = $input->param('search') || '';
103     my $supplier = $input->param('supplierid') || '';
104     my $basketno = $input->param('basketno') || '';
105     my $orderno  = $input->param('orderno') || '';
106
107     my $orders = SearchOrder($orderno, $search, $supplier, $basketno);
108     foreach my $order (@$orders){
109         if($order->{quantityreceived} < $order->{quantity}){
110             my $data = {};
111             
112             $data->{basketno} = $order->{basketno};
113             $data->{ordernumber} = $order->{ordernumber};
114             $data->{title} = $order->{title};
115             $data->{author} = $order->{author};
116             $data->{isbn} = $order->{isbn};
117             $data->{booksellerid} = $order->{booksellerid};
118             $data->{biblionumber} = $order->{biblionumber};
119             $data->{freight} = $order->{freight};
120             $data->{quantity} = $order->{quantity};
121             $data->{ecost} = $order->{ecost};
122             $data->{ordertotal} = sprintf("%.2f",$order->{ecost}*$order->{quantity});
123             push @datas, $data;
124         }
125     }
126     
127     my $json_text = to_json(\@datas);
128     $template->param(return => $json_text);
129     output_html_with_http_headers $input, $cookie, $template->output;
130     exit;
131 }
132
133 my ($template, $loggedinuser, $cookie)
134     = get_template_and_user({template_name => "acqui/parcel.tmpl",
135                  query => $input,
136                                  type => "intranet",
137                  authnotrequired => 0,
138                  flagsrequired => {acquisition => 'order_receive'},
139                  debug => 1,
140 });
141
142 my $action = $input->param('action');
143 my $ordernumber = $input->param('ordernumber');
144 my $biblionumber = $input->param('biblionumber');
145
146 # If canceling an order
147 if ($action eq "cancelorder") {
148
149     my $error_delitem;
150     my $error_delbiblio;
151
152     # We delete the order
153     DelOrder($biblionumber, $ordernumber);
154
155     # We delete all the items related to this order
156     my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
157     foreach (@itemnumbers) {
158         my $delcheck = DelItemCheck(C4::Context->dbh, $biblionumber, $_);
159         # (should always success, as no issue should exist on item on order)
160         if ($delcheck != 1) { $error_delitem = 1; }
161     }
162
163     # We get the number of remaining items
164     my $itemcount = GetItemsCount($biblionumber);
165     
166     # If there are no items left,
167     if ($itemcount eq 0) {
168         # We delete the record
169         $error_delbiblio = DelBiblio($biblionumber);    
170     }
171
172     if ($error_delitem || $error_delbiblio) {
173         if ($error_delitem)   { $template->param(error_delitem => 1); }
174         if ($error_delbiblio) { $template->param(error_delbiblio => 1); }
175     } else {
176         $template->param(success_delorder => 1);
177     }
178 }
179
180 # If receiving error, report the error (coming from finishrecieve.pl(sic)).
181 if( scalar(@rcv_err) ) {
182         my $cnt=0;
183         my $error_loop;
184         for my $err (@rcv_err) {
185                 push @$error_loop, { "error_$err" => 1 , barcode => $rcv_err_barcode[$cnt] };
186                 $cnt++;
187         }
188         $template->param( receive_error => 1 ,
189                                                 error_loop => $error_loop,
190                                         );
191 }
192
193 my $cfstr         = "%.2f";                                                           # currency format string -- could get this from currency table.
194 my @parcelitems   = GetParcel($supplierid, $invoice, $datereceived->output('iso'));
195 my $countlines    = scalar @parcelitems;
196 my $totalprice    = 0;
197 my $totalfreight  = 0;
198 my $totalquantity = 0;
199 my $total;
200 my $tototal;
201 my @loop_received = ();
202
203 for (my $i = 0 ; $i < $countlines ; $i++) {
204
205     #$total=($parcelitems[$i]->{'unitprice'} + $parcelitems[$i]->{'freight'}) * $parcelitems[$i]->{'quantityreceived'};   #weird, are the freight fees counted by book? (pierre)
206     $total = ($parcelitems[$i]->{'unitprice'}) * $parcelitems[$i]->{'quantityreceived'};    #weird, are the freight fees counted by book? (pierre)
207     $parcelitems[$i]->{'unitprice'} += 0;
208     my %line;
209     %line          = %{ $parcelitems[$i] };
210     $line{invoice} = $invoice;
211     $line{gst}     = $gst;
212     $line{total} = sprintf($cfstr, $total);
213     $line{supplierid} = $supplierid;
214     push @loop_received, \%line;
215     $totalprice += $parcelitems[$i]->{'unitprice'};
216     $line{unitprice} = sprintf($cfstr, $parcelitems[$i]->{'unitprice'});
217
218     #double FIXME - totalfreight is redefined later.
219
220 # 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..
221     if ($i > 0 && $totalfreight != $parcelitems[$i]->{'freight'}) {
222         warn "FREIGHT CHARGE MISMATCH!!";
223     }
224     $totalfreight = $parcelitems[$i]->{'freight'};
225     $totalquantity += $parcelitems[$i]->{'quantityreceived'};
226     $tototal       += $total;
227 }
228
229 my $pendingorders = GetPendingOrders($supplierid);
230 my $countpendings = scalar @$pendingorders;
231
232 # pending orders totals
233 my ($totalPunitprice, $totalPquantity, $totalPecost, $totalPqtyrcvd);
234 my $ordergrandtotal;
235 my @loop_orders = ();
236 for (my $i = 0 ; $i < $countpendings ; $i++) {
237     my %line;
238     %line = %{$pendingorders->[$i]};
239     $line{quantity}+=0;
240     $line{quantityreceived}+=0;
241     $line{unitprice}+=0;
242     $totalPunitprice += $line{unitprice};
243     $totalPquantity +=$line{quantity};
244     $totalPqtyrcvd +=$line{quantityreceived};
245     $totalPecost += $line{ecost};
246     $line{ecost} = sprintf("%.2f",$line{ecost});
247     $line{ordertotal} = sprintf("%.2f",$line{ecost}*$line{quantity});
248     $line{unitprice} = sprintf("%.2f",$line{unitprice});
249     $line{invoice} = $invoice;
250     $line{gst} = $gst;
251     $line{total} = $total;
252     $line{supplierid} = $supplierid;
253     $ordergrandtotal += $line{ecost} * $line{quantity};
254     push @loop_orders, \%line if ($i >= $startfrom and $i < $startfrom + $resultsperpage);
255 }
256 $freight = $totalfreight unless $freight;
257
258 my $count = $countpendings;
259
260 if ($count>$resultsperpage){
261     my $displaynext=0;
262     my $displayprev=$startfrom;
263     if(($count - ($startfrom+$resultsperpage)) > 0 ) {
264         $displaynext = 1;
265     }
266
267     my @numbers = ();
268     for (my $i=1; $i<$count/$resultsperpage+1; $i++) {
269             my $highlight=0;
270             ($startfrom/$resultsperpage==($i-1)) && ($highlight=1);
271             push @numbers, { number => $i,
272                 highlight => $highlight ,
273                 startfrom => ($i-1)*$resultsperpage};
274     }
275
276     my $from = $startfrom*$resultsperpage+1;
277     my $to;
278     if($count < (($startfrom+1)*$resultsperpage)){
279         $to = $count;
280     } else {
281         $to = (($startfrom+1)*$resultsperpage);
282     }
283     $template->param(numbers=>\@numbers,
284                      displaynext=>$displaynext,
285                      displayprev=>$displayprev,
286                      nextstartfrom=>(($startfrom+$resultsperpage<$count)?$startfrom+$resultsperpage:$count),
287                      prevstartfrom=>(($startfrom-$resultsperpage>0)?$startfrom-$resultsperpage:0)
288                     );
289 }
290
291 #$totalfreight=$freight;
292 $tototal = $tototal + $freight;
293
294 $template->param(
295     invoice               => $invoice,
296     datereceived          => $datereceived->output('iso'),
297     invoicedatereceived   => $datereceived->output('iso'),
298     formatteddatereceived => $datereceived->output(),
299     name                  => $bookseller->{'name'},
300     supplierid            => $supplierid,
301     gst                   => $gst,
302     freight               => $freight,
303     invoice               => $invoice,
304     countreceived         => $countlines,
305     loop_received         => \@loop_received,
306     countpending          => $countpendings,
307     loop_orders           => \@loop_orders,
308     totalprice            => sprintf($cfstr, $totalprice),
309     totalfreight          => $totalfreight,
310     totalquantity         => $totalquantity,
311     tototal               => sprintf($cfstr, $tototal),
312     ordergrandtotal       => sprintf($cfstr, $ordergrandtotal),
313     gst                   => $gst,
314     grandtot              => sprintf($cfstr, $tototal + $gst),
315     totalPunitprice       => sprintf("%.2f", $totalPunitprice),
316     totalPquantity        => $totalPquantity,
317     totalPqtyrcvd         => $totalPqtyrcvd,
318     totalPecost           => sprintf("%.2f", $totalPecost),
319     resultsperpage        => $resultsperpage,
320 );
321 output_html_with_http_headers $input, $cookie, $template->output;