(BUG #4342) should not be able to close an empty basket
[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;
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     my $count = scalar GetOrders( $basketno);
118     $template->param(
119         basketno             => $basketno,
120         basketname           => $basket->{'basketname'},
121         basketnote           => $basket->{note},
122         basketbooksellernote => $basket->{booksellernote},
123         basketcontractno     => $basket->{contractnumber},
124         basketcontractname   => $contract->{contractname},
125         creationdate         => format_date( $basket->{creationdate} ),
126         authorisedby         => $basket->{authorisedby},
127         authorisedbyname     => $basket->{authorisedbyname},
128         closedate            => format_date( $basket->{closedate} ),
129         active               => $bookseller->{'active'},
130         booksellerid         => $bookseller->{'id'},
131         name                 => $bookseller->{'name'},
132         address1             => $bookseller->{'address1'},
133         address2             => $bookseller->{'address2'},
134         address3             => $bookseller->{'address3'},
135         address4             => $bookseller->{'address4'},
136         count               =>     $count,
137       );
138 } elsif ($op eq 'attachbasket' && $template->{'param_map'}->{'CAN_user_acquisition_group_manage'} == 1) {
139       print $query->redirect('/cgi-bin/koha/acqui/basketgroup.pl?basketno=' . $basket->{'basketno'} . '&op=attachbasket&booksellerid=' . $booksellerid);
140     # check if we have to "close" a basket before building page
141 } elsif ($op eq 'export') {
142     print $query->header(
143         -type       => 'text/csv',
144         -attachment => 'basket' . $basket->{'basketno'} . '.csv',
145     );
146     print GetBasketAsCSV($query->param('basketno'));
147     exit;
148 } elsif ($op eq 'close') {
149     my $confirm = $query->param('confirm');
150     if ($confirm) {
151         my $basketno = $query->param('basketno');
152         my $booksellerid = $query->param('booksellerid');
153         $basketno =~ /^\d+$/ and CloseBasket($basketno);
154         # if requested, create basket group, close it and attach the basket
155         if ($query->param('createbasketgroup')) {
156             my $basketgroupid = NewBasketgroup( { name => $basket->{basketname},
157                             booksellerid => $booksellerid,
158                             closed => 1,
159                             });
160             ModBasket( { basketno => $basketno,
161                          basketgroupid => $basketgroupid } );
162             print $query->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid='.$booksellerid);
163         } else {
164             print $query->redirect('/cgi-bin/koha/acqui/basketgroup.pl?basketno='.$basketno.'&op=attachbasket&booksellerid=' . $booksellerid);
165         }
166         exit;
167     } else {
168     $template->param(confirm_close => "1",
169             booksellerid    => $booksellerid,
170             basketno        => $basket->{'basketno'},
171                 basketname      => $basket->{'basketname'},
172             basketgroupname => $basket->{'basketname'});
173         
174     }
175 } elsif ($query->param('op') eq 'reopen') {
176     my $basket;
177     $basket->{basketno} = $query->param('basketno');
178     $basket->{closedate} = undef;
179     ModBasket($basket);
180     print $query->redirect('/cgi-bin/koha/acqui/basket.pl?basketno='.$basket->{'basketno'})
181 } else {
182     # get librarian branch...
183     if ( C4::Context->preference("IndependantBranches") ) {
184         my $userenv = C4::Context->userenv;
185         unless ( $userenv->{flags} == 1 ) {
186             my $validtest = ( $basket->{creationdate} eq '' )
187               || ( $userenv->{branch} eq $basket->{branch} )
188               || ( $userenv->{branch} eq '' )
189               || ( $basket->{branch}  eq '' );
190             unless ($validtest) {
191                 print $query->redirect("../mainpage.pl");
192                 exit 1;
193             }
194         }
195     }
196 #if the basket is closed,and the user has the permission to edit basketgroups, display a list of basketgroups
197     my $basketgroups;
198     my $member = GetMember(borrowernumber => $loggedinuser);
199     if ($basket->{closedate} && haspermission({ flagsrequired   => { acquisition => 'group_manage'} })) {
200         $basketgroups = GetBasketgroups($basket->{booksellerid});
201         for (my $i=0; $i < scalar(@$basketgroups); $i++) {
202             if ($basket->{basketgroupid} == @$basketgroups[$i]->{id}){
203                 @$basketgroups[$i]->{default} = 1;
204             }
205         }
206         my %emptygroup = ( id   =>   undef,
207                            name =>   "No group");
208         if ( ! $basket->{basketgroupid} ) {
209             $emptygroup{default} = 1;
210         }
211         unshift( @$basketgroups, \%emptygroup );
212     }
213     # if new basket, pre-fill infos
214     $basket->{creationdate} = ""            unless ( $basket->{creationdate} );
215     $basket->{authorisedby} = $loggedinuser unless ( $basket->{authorisedby} );
216     $debug
217       and warn sprintf
218       "loggedinuser: $loggedinuser; creationdate: %s; authorisedby: %s",
219       $basket->{creationdate}, $basket->{authorisedby};
220
221     my @results = GetOrders( $basketno );
222     my $count = scalar @results;
223     
224         my $gist = $bookseller->{gstrate} || C4::Context->preference("gist") || 0;
225         my $discount = $bookseller->{'discount'} / 100;
226     my $total_rrp;      # RRP Total, its value will be assigned to $total_rrp_gsti or $total_rrp_gste depending of $bookseller->{'listincgst'}
227         my $total_rrp_gsti; # RRP Total, GST included
228         my $total_rrp_gste; # RRP Total, GST excluded
229         my $gist_rrp;
230         
231     my $qty_total;
232     my @books_loop;
233
234     for ( my $i = 0 ; $i < $count ; $i++ ) {
235         my $rrp = $results[$i]->{'listprice'};
236                 my $qty = $results[$i]->{'quantity'} || 0;
237         if (!defined $results[$i]->{quantityreceived}) {
238             $results[$i]->{quantityreceived} = 0;
239         }
240
241         my $budget = GetBudget(  $results[$i]->{'budget_id'} );
242         $rrp = ConvertCurrency( $results[$i]->{'currency'}, $rrp );
243
244         $total_rrp += $qty * $results[$i]->{'rrp'};
245         my $line_total = $qty * $results[$i]->{'ecost'};
246                 # FIXME: what about the "actual cost" field?
247         $qty_total += $qty;
248         my %line = %{ $results[$i] };
249                 ($i%2) and $line{toggle} = 1;
250
251         $line{order_received} = ( $qty == $results[$i]->{'quantityreceived'} );
252         $line{basketno}       = $basketno;
253         $line{i}              = $i;
254         $line{budget_name}    = $budget->{budget_name};
255         $line{rrp}            = sprintf( "%.2f", $line{'rrp'} );
256         $line{ecost}          = sprintf( "%.2f", $line{'ecost'} );
257         $line{line_total}     = sprintf( "%.2f", $line_total );
258         $line{odd}            = $i % 2;
259         if ($line{uncertainprice}) {
260             $template->param( unclosable => 1 );
261             for my $key (qw/ecost line_total rrp/) {
262                 $line{$key} .= '??';
263             }
264         }
265         if ($line{'title'}){
266             my $volume = $results[$i]->{'volume'};
267             my $seriestitle = $results[$i]->{'seriestitle'};
268             $line{'title'} .= " / $seriestitle" if $seriestitle;
269             $line{'title'} .= " / $volume" if $volume;
270         } else {
271             $line{'title'} = "Deleted bibliographic notice, can't find title.";
272         }
273         push @books_loop, \%line;
274     }
275
276         if ($bookseller->{'listincgst'}) {                        # if prices already includes GST
277                 $total_rrp_gsti = $total_rrp;                         # we know $total_rrp_gsti
278                 $total_rrp_gste = $total_rrp_gsti / ($gist + 1);      # and can reverse compute other values
279                 $gist_rrp       = $total_rrp_gsti - $total_rrp_gste;  #
280         } else {                                                  # if prices does not include GST
281                 $total_rrp_gste = $total_rrp;                         # then we use the common way to compute other values
282                 $gist_rrp = $total_rrp_gste * $gist;                  #
283                 $total_rrp_gsti = $total_rrp_gste + $gist_rrp;        #
284         }
285         # These vars are estimated totals and GST, taking in account the booksellet discount
286         my $total_est_gsti = $total_rrp_gsti - ($total_rrp_gsti * $discount);
287         my $gist_est       = $gist_rrp       - ($gist_rrp * $discount);
288         my $total_est_gste = $total_rrp_gste - ($total_rrp_gste * $discount);
289
290     my $contract = &GetContract($basket->{contractnumber});
291     my @orders = GetOrders($basketno);
292     $template->param(
293         basketno             => $basketno,
294         basketname           => $basket->{'basketname'},
295         basketnote           => $basket->{note},
296         basketbooksellernote => $basket->{booksellernote},
297         basketcontractno     => $basket->{contractnumber},
298         basketcontractname   => $contract->{contractname},
299         creationdate         => C4::Dates->new($basket->{creationdate},'iso')->output,
300         authorisedby         => $basket->{authorisedby},
301         authorisedbyname     => $basket->{authorisedbyname},
302         closedate            => C4::Dates->new($basket->{closedate},'iso')->output,
303         active               => $bookseller->{'active'},
304         booksellerid         => $bookseller->{'id'},
305         name                 => $bookseller->{'name'},
306         entrydate            => C4::Dates->new($results[0]->{'entrydate'},'iso')->output,
307         books_loop           => \@books_loop,
308         count                => $count,
309         gist_rate            => sprintf( "%.2f", $gist * 100 ) . '%',
310         total_rrp_gste       => sprintf( "%.2f", $total_rrp_gste ),
311         total_est_gste       => sprintf( "%.2f", $total_est_gste ),
312         gist_est             => sprintf( "%.2f", $gist_est ),
313         gist_rrp             => sprintf( "%.2f", $gist_rrp ),        
314         total_rrp_gsti       => sprintf( "%.2f", $total_rrp_gsti ),
315         total_est_gsti       => sprintf( "%.2f", $total_est_gsti ),
316         currency             => $bookseller->{'listprice'},
317         qty_total            => $qty_total,
318         GST                  => $gist,
319         basketgroups         => $basketgroups,
320         grouped              => $basket->{basketgroupid},
321         unclosable           => @orders ? 0 : 1, 
322     );
323 }
324
325 output_html_with_http_headers $query, $cookie, $template->output;