Merge remote-tracking branch 'origin/new/bug_7460'
[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 booksellerid
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 qw/ GetBookSellerFromId /;
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 C4::Suggestions;
71 use JSON;
72
73 my $input=new CGI;
74 my $booksellerid=$input->param('booksellerid');
75 my $bookseller=GetBookSellerFromId($booksellerid);
76
77 my $invoice=$input->param('invoice') || '';
78 my $freight=$input->param('freight');
79 my $input_gst = ($input->param('gst') eq '' ? undef : $input->param('gst'));
80 my $gst= $input_gst // $bookseller->{gstrate} // C4::Context->preference("gist") // 0;
81 my $datereceived =  ($input->param('op') eq 'new') ? C4::Dates->new($input->param('datereceived')) 
82                                         :  C4::Dates->new($input->param('datereceived'), 'iso')   ;
83 $datereceived = C4::Dates->new() unless $datereceived;
84 my $code            = $input->param('code');
85 my @rcv_err         = $input->param('error');
86 my @rcv_err_barcode = $input->param('error_bc');
87
88 my $startfrom=$input->param('startfrom');
89 my $resultsperpage = $input->param('resultsperpage');
90 $resultsperpage = 20 unless ($resultsperpage);
91 $startfrom=0 unless ($startfrom);
92
93 if($input->param('format') eq "json"){
94     my ($template, $loggedinuser, $cookie)
95         = get_template_and_user({template_name => "acqui/ajax.tmpl",
96                  query => $input,
97                                  type => "intranet",
98                  authnotrequired => 0,
99                  flagsrequired => {acquisition => 'order_receive'},
100                  debug => 1,
101     });
102        
103     my @datas;
104     my $search   = $input->param('search') || '';
105     my $supplier = $input->param('booksellerid') || '';
106     my $basketno = $input->param('basketno') || '';
107     my $orderno  = $input->param('orderno') || '';
108
109     my $orders = SearchOrder($orderno, $search, $supplier, $basketno);
110     foreach my $order (@$orders){
111         if($order->{quantityreceived} < $order->{quantity}){
112             my $data = {};
113             
114             $data->{basketno} = $order->{basketno};
115             $data->{ordernumber} = $order->{ordernumber};
116             $data->{title} = $order->{title};
117             $data->{author} = $order->{author};
118             $data->{isbn} = $order->{isbn};
119             $data->{booksellerid} = $order->{booksellerid};
120             $data->{biblionumber} = $order->{biblionumber};
121             $data->{freight} = $order->{freight};
122             $data->{quantity} = $order->{quantity};
123             $data->{ecost} = $order->{ecost};
124             $data->{ordertotal} = sprintf("%.2f",$order->{ecost}*$order->{quantity});
125             push @datas, $data;
126         }
127     }
128     
129     my $json_text = to_json(\@datas);
130     $template->param(return => $json_text);
131     output_html_with_http_headers $input, $cookie, $template->output;
132     exit;
133 }
134
135 my ($template, $loggedinuser, $cookie)
136     = get_template_and_user({template_name => "acqui/parcel.tmpl",
137                  query => $input,
138                                  type => "intranet",
139                  authnotrequired => 0,
140                  flagsrequired => {acquisition => 'order_receive'},
141                  debug => 1,
142 });
143
144 # If receiving error, report the error (coming from finishrecieve.pl(sic)).
145 if( scalar(@rcv_err) ) {
146         my $cnt=0;
147         my $error_loop;
148         for my $err (@rcv_err) {
149                 push @$error_loop, { "error_$err" => 1 , barcode => $rcv_err_barcode[$cnt] };
150                 $cnt++;
151         }
152         $template->param( receive_error => 1 ,
153                                                 error_loop => $error_loop,
154                                         );
155 }
156
157 my $cfstr         = "%.2f";                                                           # currency format string -- could get this from currency table.
158 my @parcelitems   = GetParcel($booksellerid, $invoice, $datereceived->output('iso'));
159 my $countlines    = scalar @parcelitems;
160 my $totalprice    = 0;
161 my $totalfreight  = 0;
162 my $totalquantity = 0;
163 my $total;
164 my $tototal;
165 my @loop_received = ();
166
167 for (my $i = 0 ; $i < $countlines ; $i++) {
168
169     #$total=($parcelitems[$i]->{'unitprice'} + $parcelitems[$i]->{'freight'}) * $parcelitems[$i]->{'quantityreceived'};   #weird, are the freight fees counted by book? (pierre)
170     $total = ($parcelitems[$i]->{'unitprice'}) * $parcelitems[$i]->{'quantityreceived'};    #weird, are the freight fees counted by book? (pierre)
171     $parcelitems[$i]->{'unitprice'} += 0;
172     my %line;
173     %line          = %{ $parcelitems[$i] };
174     $line{invoice} = $invoice;
175     $line{gst}     = $gst;
176     $line{total} = sprintf($cfstr, $total);
177     $line{booksellerid} = $booksellerid;
178     push @loop_received, \%line;
179     $totalprice += $parcelitems[$i]->{'unitprice'};
180     $line{unitprice} = sprintf($cfstr, $parcelitems[$i]->{'unitprice'});
181
182     my $suggestion   = GetSuggestionInfoFromBiblionumber($line{biblionumber});
183     $line{suggestionid}         = $suggestion->{suggestionid};
184     $line{surnamesuggestedby}   = $suggestion->{surnamesuggestedby};
185     $line{firstnamesuggestedby} = $suggestion->{firstnamesuggestedby};
186
187     #double FIXME - totalfreight is redefined later.
188
189 # 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..
190     if ($i > 0 && $totalfreight != $parcelitems[$i]->{'freight'}) {
191         warn "FREIGHT CHARGE MISMATCH!!";
192     }
193     $totalfreight = $parcelitems[$i]->{'freight'};
194     $totalquantity += $parcelitems[$i]->{'quantityreceived'};
195     $tototal       += $total;
196 }
197
198 my $pendingorders = GetPendingOrders($booksellerid);
199 my $countpendings = scalar @$pendingorders;
200
201 # pending orders totals
202 my ($totalPunitprice, $totalPquantity, $totalPecost, $totalPqtyrcvd);
203 my $ordergrandtotal;
204 my @loop_orders = ();
205 for (my $i = 0 ; $i < $countpendings ; $i++) {
206     my %line;
207     %line = %{$pendingorders->[$i]};
208    
209     $line{quantity}+=0;
210     $line{quantityreceived}+=0;
211     $line{unitprice}+=0;
212     $totalPunitprice += $line{unitprice};
213     $totalPquantity +=$line{quantity};
214     $totalPqtyrcvd +=$line{quantityreceived};
215     $totalPecost += $line{ecost};
216     $line{ecost} = sprintf("%.2f",$line{ecost});
217     $line{ordertotal} = sprintf("%.2f",$line{ecost}*$line{quantity});
218     $line{unitprice} = sprintf("%.2f",$line{unitprice});
219     $line{invoice} = $invoice;
220     $line{gst} = $gst;
221     $line{total} = $total;
222     $line{booksellerid} = $booksellerid;
223     $ordergrandtotal += $line{ecost} * $line{quantity};
224     
225     my $biblionumber = $line{'biblionumber'};
226     my $countbiblio = CountBiblioInOrders($biblionumber);
227     my $ordernumber = $line{'ordernumber'};
228     my @subscriptions = GetSubscriptionsId ($biblionumber);
229     my $itemcount = GetItemsCount($biblionumber);
230     my $holds  = GetHolds ($biblionumber);
231     my @items = GetItemnumbersFromOrder( $ordernumber );
232     my $itemholds;
233     foreach my $item (@items){
234         my $nb = GetItemHolds($biblionumber, $item);
235         if ($nb){
236             $itemholds += $nb;
237         }
238     }
239
240     my $suggestion   = GetSuggestionInfoFromBiblionumber($line{biblionumber});
241     $line{suggestionid}         = $suggestion->{suggestionid};
242     $line{surnamesuggestedby}   = $suggestion->{surnamesuggestedby};
243     $line{firstnamesuggestedby} = $suggestion->{firstnamesuggestedby};
244
245     # if the biblio is not in other orders and if there is no items elsewhere and no subscriptions and no holds we can then show the link "Delete order and Biblio" see bug 5680
246     $line{can_del_bib}          = 1 if $countbiblio <= 1 && $itemcount == scalar @items && !(@subscriptions) && !($holds);
247     $line{items}                = ($itemcount) - (scalar @items);
248     $line{left_item}            = 1 if $line{items} >= 1;
249     $line{left_biblio}          = 1 if $countbiblio > 1;
250     $line{biblios}              = $countbiblio - 1;
251     $line{left_subscription}    = 1 if scalar @subscriptions >= 1;
252     $line{subscriptions}        = scalar @subscriptions;
253     $line{left_holds}           = 1 if $holds >= 1;
254     $line{left_holds_on_order}  = 1 if $line{left_holds}==1 && ($line{items} == 0 || $itemholds );
255     $line{holds}                = $holds;
256     $line{holds_on_order}       = $itemholds?$itemholds:$holds if $line{left_holds_on_order};
257     
258     
259     push @loop_orders, \%line if ($i >= $startfrom and $i < $startfrom + $resultsperpage);
260 }
261 $freight = $totalfreight unless $freight;
262
263 my $count = $countpendings;
264
265 if ($count>$resultsperpage){
266     my $displaynext=0;
267     my $displayprev=$startfrom;
268     if(($count - ($startfrom+$resultsperpage)) > 0 ) {
269         $displaynext = 1;
270     }
271
272     my @numbers = ();
273     for (my $i=1; $i<$count/$resultsperpage+1; $i++) {
274             my $highlight=0;
275             ($startfrom/$resultsperpage==($i-1)) && ($highlight=1);
276             push @numbers, { number => $i,
277                 highlight => $highlight ,
278                 startfrom => ($i-1)*$resultsperpage};
279     }
280
281     my $from = $startfrom*$resultsperpage+1;
282     my $to;
283     if($count < (($startfrom+1)*$resultsperpage)){
284         $to = $count;
285     } else {
286         $to = (($startfrom+1)*$resultsperpage);
287     }
288     $template->param(numbers=>\@numbers,
289                      displaynext=>$displaynext,
290                      displayprev=>$displayprev,
291                      nextstartfrom=>(($startfrom+$resultsperpage<$count)?$startfrom+$resultsperpage:$count),
292                      prevstartfrom=>(($startfrom-$resultsperpage>0)?$startfrom-$resultsperpage:0)
293                     );
294 }
295
296 #$totalfreight=$freight;
297 $tototal = $tototal + $freight;
298
299 $template->param(
300     invoice               => $invoice,
301     datereceived          => $datereceived->output('iso'),
302     invoicedatereceived   => $datereceived->output('iso'),
303     formatteddatereceived => $datereceived->output(),
304     name                  => $bookseller->{'name'},
305     booksellerid            => $booksellerid,
306     gst                   => $gst,
307     freight               => $freight,
308     invoice               => $invoice,
309     countreceived         => $countlines,
310     loop_received         => \@loop_received,
311     countpending          => $countpendings,
312     loop_orders           => \@loop_orders,
313     totalprice            => sprintf($cfstr, $totalprice),
314     totalfreight          => $totalfreight,
315     totalquantity         => $totalquantity,
316     tototal               => sprintf($cfstr, $tototal),
317     ordergrandtotal       => sprintf($cfstr, $ordergrandtotal),
318     gst                   => $gst,
319     grandtot              => sprintf($cfstr, $tototal + $gst),
320     totalPunitprice       => sprintf("%.2f", $totalPunitprice),
321     totalPquantity        => $totalPquantity,
322     totalPqtyrcvd         => $totalPqtyrcvd,
323     totalPecost           => sprintf("%.2f", $totalPecost),
324     resultsperpage        => $resultsperpage,
325 );
326 output_html_with_http_headers $input, $cookie, $template->output;
327