Merge remote branch 'kc/new/bug_3013' into kcmaster
[koha.git] / acqui / basket.pl
1 #!/usr/bin/perl
2
3 #script to show display basket of orders
4
5 # Copyright 2000 - 2004 Katipo
6 # Copyright 2008 - 2009 BibLibre SARL
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
13 # version.
14 #
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along
20 # with Koha; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22
23 use strict;
24 use warnings;
25 use C4::Auth;
26 use C4::Koha;
27 use C4::Output;
28 use CGI;
29 use C4::Acquisition;
30 use C4::Budgets;
31
32 use C4::Bookseller qw( GetBookSellerFromId);
33 use C4::Dates qw/format_date/;
34 use C4::Debug;
35
36 use C4::Members qw/GetMember/;  #needed for permissions checking for changing basketgroup of a basket
37 =head1 NAME
38
39 basket.pl
40
41 =head1 DESCRIPTION
42
43  This script display all informations about basket for the supplier given
44  on input arg.  Moreover, it allows us to add a new order for this supplier from
45  an existing record, a suggestion or a new record.
46
47 =head1 CGI PARAMETERS
48
49 =over 4
50
51 =item $basketno
52
53 The basket number.
54
55 =item supplierid
56
57 the supplier this script have to display the basket.
58
59 =item order
60
61 =back
62
63 =cut
64
65 my $query        = new CGI;
66 my $basketno     = $query->param('basketno');
67 my $booksellerid = $query->param('supplierid');
68
69 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
70     {
71         template_name   => "acqui/basket.tmpl",
72         query           => $query,
73         type            => "intranet",
74         authnotrequired => 0,
75         flagsrequired   => { acquisition => 'order_manage' },
76         debug           => 1,
77     }
78 );
79
80 my $basket = GetBasket($basketno);
81
82 # FIXME : what about the "discount" percentage?
83 # FIXME : the query->param('supplierid') below is probably useless. The bookseller is always known from the basket
84 # if no booksellerid in parameter, get it from basket
85 # warn "=>".$basket->{booksellerid};
86 $booksellerid = $basket->{booksellerid} unless $booksellerid;
87 my ($bookseller) = GetBookSellerFromId($booksellerid);
88 my $op = $query->param('op');
89 if (!defined $op) {
90     $op = q{};
91 }
92
93 if ( $op eq 'delete_confirm' ) {
94     my $basketno = $query->param('basketno');
95     DelBasket($basketno);
96     $template->param( delete_confirmed => 1 );
97 } elsif ( !$bookseller ) {
98     $template->param( NO_BOOKSELLER => 1 );
99 } elsif ( $op eq 'del_basket') {
100     $template->param( delete_confirm => 1 );
101     if ( C4::Context->preference("IndependantBranches") ) {
102         my $userenv = C4::Context->userenv;
103         unless ( $userenv->{flags} == 1 ) {
104             my $validtest = ( $basket->{creationdate} eq '' )
105               || ( $userenv->{branch} eq $basket->{branch} )
106               || ( $userenv->{branch} eq '' )
107               || ( $basket->{branch}  eq '' );
108             unless ($validtest) {
109                 print $query->redirect("../mainpage.pl");
110                 exit 1;
111             }
112         }
113     }
114     $basket->{creationdate} = ""            unless ( $basket->{creationdate} );
115     $basket->{authorisedby} = $loggedinuser unless ( $basket->{authorisedby} );
116     my $contract = &GetContract($basket->{contractnumber});
117     $template->param(
118         basketno             => $basketno,
119         basketname           => $basket->{'basketname'},
120         basketnote           => $basket->{note},
121         basketbooksellernote => $basket->{booksellernote},
122         basketcontractno     => $basket->{contractnumber},
123         basketcontractname   => $contract->{contractname},
124         creationdate         => format_date( $basket->{creationdate} ),
125         authorisedby         => $basket->{authorisedby},
126         authorisedbyname     => $basket->{authorisedbyname},
127         closedate            => format_date( $basket->{closedate} ),
128         active               => $bookseller->{'active'},
129         booksellerid         => $bookseller->{'id'},
130         name                 => $bookseller->{'name'},
131         address1             => $bookseller->{'address1'},
132         address2             => $bookseller->{'address2'},
133         address3             => $bookseller->{'address3'},
134         address4             => $bookseller->{'address4'},
135       );
136 } elsif ($op eq 'attachbasket' && $template->{'param_map'}->{'CAN_user_acquisition_group_manage'} == 1) {
137       print $query->redirect('/cgi-bin/koha/acqui/basketgroup.pl?basketno=' . $basket->{'basketno'} . '&op=attachbasket&booksellerid=' . $booksellerid);
138     # check if we have to "close" a basket before building page
139 } elsif ($op eq 'export') {
140     print $query->header(
141         -type       => 'text/csv',
142         -attachment => 'basket' . $basket->{'basketno'} . '.csv',
143     );
144     print GetBasketAsCSV($query->param('basketno'));
145     exit;
146 } elsif ($op eq 'close') {
147     my $confirm = $query->param('confirm');
148     if ($confirm) {
149         my $basketno = $query->param('basketno');
150         my $booksellerid = $query->param('booksellerid');
151         $basketno =~ /^\d+$/ and CloseBasket($basketno);
152         # if requested, create basket group, close it and attach the basket
153         if ($query->param('createbasketgroup')) {
154             my $basketgroupid = NewBasketgroup( { name => $basket->{basketname},
155                             booksellerid => $booksellerid,
156                             closed => 1,
157                             });
158             ModBasket( { basketno => $basketno,
159                          basketgroupid => $basketgroupid } );
160             print $query->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid='.$booksellerid.'&closed=1');
161         } else {
162             print $query->redirect('/cgi-bin/koha/acqui/booksellers.pl?supplierid=' . $booksellerid);
163         }
164         exit;
165     } else {
166     $template->param(confirm_close => "1",
167             booksellerid    => $booksellerid,
168             basketno        => $basket->{'basketno'},
169                 basketname      => $basket->{'basketname'},
170             basketgroupname => $basket->{'basketname'});
171         
172     }
173 } elsif ($op eq 'reopen') {
174     my $basket;
175     $basket->{basketno} = $query->param('basketno');
176     $basket->{closedate} = undef;
177     ModBasket($basket);
178     print $query->redirect('/cgi-bin/koha/acqui/basket.pl?basketno='.$basket->{'basketno'})
179 } else {
180     # get librarian branch...
181     if ( C4::Context->preference("IndependantBranches") ) {
182         my $userenv = C4::Context->userenv;
183         unless ( $userenv->{flags} == 1 ) {
184             my $validtest = ( $basket->{creationdate} eq '' )
185               || ( $userenv->{branch} eq $basket->{branch} )
186               || ( $userenv->{branch} eq '' )
187               || ( $basket->{branch}  eq '' );
188             unless ($validtest) {
189                 print $query->redirect("../mainpage.pl");
190                 exit 1;
191             }
192         }
193     }
194 #if the basket is closed,and the user has the permission to edit basketgroups, display a list of basketgroups
195     my $basketgroups;
196     my $member = GetMember(borrowernumber => $loggedinuser);
197     if ($basket->{closedate} && haspermission({ flagsrequired   => { acquisition => 'group_manage'} })) {
198         $basketgroups = GetBasketgroups($basket->{booksellerid});
199         for my $bg ( @{$basketgroups} ) {
200             if ($basket->{basketgroupid} == $bg->{id}){
201                 $bg->{default} = 1;
202             }
203         }
204         my %emptygroup = ( id   =>   undef,
205                            name =>   "No group");
206         if ( ! $basket->{basketgroupid} ) {
207             $emptygroup{default} = 1;
208             $emptygroup{nogroup} = 1;
209         }
210         unshift( @$basketgroups, \%emptygroup );
211     }
212     # if new basket, pre-fill infos
213     $basket->{creationdate} = ""            unless ( $basket->{creationdate} );
214     $basket->{authorisedby} = $loggedinuser unless ( $basket->{authorisedby} );
215     $debug
216       and warn sprintf
217       "loggedinuser: $loggedinuser; creationdate: %s; authorisedby: %s",
218       $basket->{creationdate}, $basket->{authorisedby};
219
220     my @results = GetOrders( $basketno );
221     
222         my $gist = $bookseller->{gstrate} // C4::Context->preference("gist") // 0;
223         my $discount = $bookseller->{'discount'} / 100;
224     my $total_rrp;      # RRP Total, its value will be assigned to $total_rrp_gsti or $total_rrp_gste depending of $bookseller->{'listincgst'}
225         my $total_rrp_gsti; # RRP Total, GST included
226         my $total_rrp_gste; # RRP Total, GST excluded
227         my $gist_rrp;
228         
229     my $qty_total;
230     my @books_loop;
231
232     for my $order ( @results ) {
233         my $rrp = $order->{'listprice'} || 0;
234                 my $qty = $order->{'quantity'} || 0;
235         if (!defined $order->{quantityreceived}) {
236             $order->{quantityreceived} = 0;
237         }
238         for ( qw(rrp ecost quantityreceived)) {
239             if (!defined $order->{$_}) {
240                 $order->{$_} = 0;
241             }
242         }
243
244         my $budget = GetBudget(  $order->{'budget_id'} );
245         $rrp = ConvertCurrency( $order->{'currency'}, $rrp );
246
247         $total_rrp += $qty * $order->{'rrp'};
248         my $line_total = $qty * $order->{'ecost'};
249                 # FIXME: what about the "actual cost" field?
250         $qty_total += $qty;
251         my %line = %{ $order };
252
253         $line{order_received} = ( $qty == $order->{'quantityreceived'} );
254         $line{basketno}       = $basketno;
255         $line{budget_name}    = $budget->{budget_name};
256         $line{rrp}            = sprintf( "%.2f", $line{'rrp'} );
257         $line{ecost}          = sprintf( "%.2f", $line{'ecost'} );
258         $line{line_total}     = sprintf( "%.2f", $line_total );
259         if ($line{uncertainprice}) {
260             $template->param( uncertainprices => 1 );
261             $line{rrp} .= ' (Uncertain)';
262         }
263         if ($line{'title'}){
264             my $volume = $order->{'volume'};
265             my $seriestitle = $order->{'seriestitle'};
266             $line{'title'} .= " / $seriestitle" if $seriestitle;
267             $line{'title'} .= " / $volume" if $volume;
268         } else {
269             $line{'title'} = "Deleted bibliographic notice, can't find title.";
270         }
271         push @books_loop, \%line;
272     }
273
274         if ($bookseller->{'listincgst'}) {                        # if prices already includes GST
275                 $total_rrp_gsti = $total_rrp;                         # we know $total_rrp_gsti
276                 $total_rrp_gste = $total_rrp_gsti / ($gist + 1);      # and can reverse compute other values
277                 $gist_rrp       = $total_rrp_gsti - $total_rrp_gste;  #
278         } else {                                                  # if prices does not include GST
279                 $total_rrp_gste = $total_rrp;                         # then we use the common way to compute other values
280                 $gist_rrp = $total_rrp_gste * $gist;                  #
281                 $total_rrp_gsti = $total_rrp_gste + $gist_rrp;        #
282         }
283         # These vars are estimated totals and GST, taking in account the booksellet discount
284         my $total_est_gsti = $total_rrp_gsti - ($total_rrp_gsti * $discount);
285         my $gist_est       = $gist_rrp       - ($gist_rrp * $discount);
286         my $total_est_gste = $total_rrp_gste - ($total_rrp_gste * $discount);
287
288     my $contract = &GetContract($basket->{contractnumber});
289     my @orders = GetOrders($basketno);
290     $template->param(
291         basketno             => $basketno,
292         basketname           => $basket->{'basketname'},
293         basketnote           => $basket->{note},
294         basketbooksellernote => $basket->{booksellernote},
295         basketcontractno     => $basket->{contractnumber},
296         basketcontractname   => $contract->{contractname},
297         creationdate         => C4::Dates->new($basket->{creationdate},'iso')->output,
298         authorisedby         => $basket->{authorisedby},
299         authorisedbyname     => $basket->{authorisedbyname},
300         closedate            => C4::Dates->new($basket->{closedate},'iso')->output,
301         active               => $bookseller->{'active'},
302         booksellerid         => $bookseller->{'id'},
303         name                 => $bookseller->{'name'},
304         entrydate            => C4::Dates->new($results[0]->{'entrydate'},'iso')->output,
305         books_loop           => \@books_loop,
306         gist_rate            => sprintf( "%.2f", $gist * 100 ) . '%',
307         total_rrp_gste       => sprintf( "%.2f", $total_rrp_gste ),
308         total_est_gste       => sprintf( "%.2f", $total_est_gste ),
309         gist_est             => sprintf( "%.2f", $gist_est ),
310         gist_rrp             => sprintf( "%.2f", $gist_rrp ),        
311         total_rrp_gsti       => sprintf( "%.2f", $total_rrp_gsti ),
312         total_est_gsti       => sprintf( "%.2f", $total_est_gsti ),
313         currency             => $bookseller->{'listprice'},
314         qty_total            => $qty_total,
315         GST                  => $gist,
316         basketgroups         => $basketgroups,
317         grouped              => $basket->{basketgroupid},
318         unclosable           => @orders ? 0 : 1, 
319     );
320 }
321
322 output_html_with_http_headers $query, $cookie, $template->output;