Fixes for basket closing:
[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 with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA  02111-1307 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 my $sort         = $query->param('order') || "aqorders.ordernumber";
69
70 my @sort_loop;
71 if (defined $sort) {
72         foreach (split /\,/, $sort) {
73                 my %sorthash = (
74                         string => $_,
75                 );
76                 # other possibly valid tables for later: aqbookfund biblio biblioitems
77                 if (
78                         (/^\s*(biblioitems)\.(\w+)\s*$/      and $2 eq 'publishercode') or
79                         (/^\s*(aqorders)\.(\w+)\s*$/ and $2 eq 'ordernumber' )
80                 ) {
81                         $sorthash{table} = $1;
82                         $sorthash{field} = $2;
83                 } else {
84                         $sorthash{error} = 1;
85                 }
86                 push @sort_loop, \%sorthash;
87         }
88 }
89
90 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
91     {
92         template_name   => "acqui/basket.tmpl",
93         query           => $query,
94         type            => "intranet",
95         authnotrequired => 0,
96         flagsrequired   => { acquisition => 'order_manage' },
97         debug           => 1,
98     }
99 );
100
101 my $basket = GetBasket($basketno);
102
103 # FIXME : what about the "discount" percentage?
104 # FIXME : the query->param('supplierid') below is probably useless. The bookseller is always known from the basket
105 # if no booksellerid in parameter, get it from basket
106 # warn "=>".$basket->{booksellerid};
107 $booksellerid = $basket->{booksellerid} unless $booksellerid;
108 my ($bookseller) = GetBookSellerFromId($booksellerid);
109 my $op = $query->param('op');
110
111 if ( $op eq 'delete_confirm' ) {
112     my $basketno = $query->param('basketno');
113     DelBasket($basketno);
114     $template->param( delete_confirmed => 1 );
115 } elsif ( !$bookseller ) {
116     $template->param( NO_BOOKSELLER => 1 );
117 } elsif ( $op eq 'del_basket') {
118     $template->param( delete_confirm => 1 );
119     if ( C4::Context->preference("IndependantBranches") ) {
120         my $userenv = C4::Context->userenv;
121         unless ( $userenv->{flags} == 1 ) {
122             my $validtest = ( $basket->{creationdate} eq '' )
123               || ( $userenv->{branch} eq $basket->{branch} )
124               || ( $userenv->{branch} eq '' )
125               || ( $basket->{branch}  eq '' );
126             unless ($validtest) {
127                 print $query->redirect("../mainpage.pl");
128                 exit 1;
129             }
130         }
131     }
132     $basket->{creationdate} = ""            unless ( $basket->{creationdate} );
133     $basket->{authorisedby} = $loggedinuser unless ( $basket->{authorisedby} );
134     my $contract = &GetContract($basket->{contractnumber});
135     my $count = scalar GetOrders( $basketno);
136     $template->param(
137         basketno             => $basketno,
138         basketname           => $basket->{'basketname'},
139         basketnote           => $basket->{note},
140         basketbooksellernote => $basket->{booksellernote},
141         basketcontractno     => $basket->{contractnumber},
142         basketcontractname   => $contract->{contractname},
143         creationdate         => format_date( $basket->{creationdate} ),
144         authorisedby         => $basket->{authorisedby},
145         authorisedbyname     => $basket->{authorisedbyname},
146         closedate            => format_date( $basket->{closedate} ),
147         active               => $bookseller->{'active'},
148         booksellerid         => $bookseller->{'id'},
149         name                 => $bookseller->{'name'},
150         address1             => $bookseller->{'address1'},
151         address2             => $bookseller->{'address2'},
152         address3             => $bookseller->{'address3'},
153         address4             => $bookseller->{'address4'},
154         count               =>     $count,
155       );
156 } elsif ($op eq 'attachbasket' && $template->{'param_map'}->{'CAN_user_acquisition_group_manage'} == 1) {
157     my $basketgroups = GetBasketgroups($basket->{booksellerid});
158     for (my $i=0; $i < scalar(@$basketgroups); $i++) {
159         if (@$basketgroups[$i]->{closed}) {
160             splice(@$basketgroups, $i, 1);
161             $i--;
162         } elsif ($basket->{basketgroupid} == @$basketgroups[$i]->{id}){
163             @$basketgroups[$i]->{default} = 1;
164         }
165     }
166     $template->param(
167         basketgroups    => $basketgroups,
168         booksellerid    => $booksellerid,
169         basketno        => $basket->{'basketno'},
170         basketname      => $basket->{'basketname'},
171         name            => $bookseller->{'name'},
172         selectbasketg    => "1"
173     );
174     # check if we have to "close" a basket before building page
175 } elsif ($op eq 'close') {
176     my $basket = $query->param('basketno');
177     $basket =~ /^\d+$/ and CloseBasket($basket);
178     if ($template->{'param_map'}->{'CAN_user_acquisition_group_manage'} == 1){
179         print $query->redirect('/cgi-bin/koha/acqui/basket.pl?basketno='.$basket.'&op=attachbasket');
180         exit;
181     } else {
182         print $query->redirect('/cgi-bin/koha/acqui/booksellers.pl?supplierid='.$booksellerid);
183         exit;
184     }
185 } elsif ($query->param('op') eq 'reopen') {
186     my $basket;
187     $basket->{basketno} = $query->param('basketno');
188     $basket->{closedate} = undef;
189     ModBasket($basket);
190     print $query->redirect('/cgi-bin/koha/acqui/basket.pl?basketno='.$basket->{'basketno'})
191 } else {
192     # get librarian branch...
193     if ( C4::Context->preference("IndependantBranches") ) {
194         my $userenv = C4::Context->userenv;
195         unless ( $userenv->{flags} == 1 ) {
196             my $validtest = ( $basket->{creationdate} eq '' )
197               || ( $userenv->{branch} eq $basket->{branch} )
198               || ( $userenv->{branch} eq '' )
199               || ( $basket->{branch}  eq '' );
200             unless ($validtest) {
201                 print $query->redirect("../mainpage.pl");
202                 exit 1;
203             }
204         }
205     }
206 #if the basket is closed,and the user has the permission to edit basketgroups, display a list of basketgroups
207     my $basketgroups;
208     my $member = GetMember($loggedinuser, "borrowernumber");
209     if ($basket->{closedate} && haspermission({ flagsrequired   => { acquisition => 'group_manage'} })) {
210         $basketgroups = GetBasketgroups($basket->{booksellerid});
211         for (my $i=0; $i < scalar(@$basketgroups); $i++) {
212             if (@$basketgroups[$i]->{closed}) {
213                 splice(@$basketgroups, $i, 1);
214                 $i--;
215             } elsif ($basket->{basketgroupid} == @$basketgroups[$i]->{id}){
216                 @$basketgroups[$i]->{default} = 1;
217             }
218         }
219         my %emptygroup = ( id   =>   undef,
220                            name =>   "No group");
221         if ( ! $basket->{basketgroupid} ) {
222             $emptygroup{default} = 1;
223         }
224         unshift( @$basketgroups, \%emptygroup );
225     }
226     # if new basket, pre-fill infos
227     $basket->{creationdate} = ""            unless ( $basket->{creationdate} );
228     $basket->{authorisedby} = $loggedinuser unless ( $basket->{authorisedby} );
229     $debug
230       and warn sprintf
231       "loggedinuser: $loggedinuser; creationdate: %s; authorisedby: %s",
232       $basket->{creationdate}, $basket->{authorisedby};
233
234     my @results = GetOrders( $basketno, $sort );
235     my $count = scalar @results;
236
237     my $sub_total;      # total of line totals
238     my $grand_total;    # $subttotal + $gist
239
240     # my $line_total_est; # total of each line
241     my $sub_total_est;      # total of line totals
242     my $sub_total_rrp;      # total of line totals
243     my $grand_total_est;    # $subttotal + $gist
244
245     my $qty_total;
246     my @books_loop;
247
248     for ( my $i = 0 ; $i < $count ; $i++ ) {
249         my $rrp = $results[$i]->{'listprice'};
250                 my $qty = $results[$i]->{'quantity'};
251
252         my $budget = GetBudget(  $results[$i]->{'budget_id'} );
253         $rrp = ConvertCurrency( $results[$i]->{'currency'}, $rrp );
254
255         $sub_total_rrp += $qty * $results[$i]->{'rrp'};
256         my $line_total = $qty * $results[$i]->{'ecost'};
257                 # FIXME: what about the "actual cost" field?
258         $sub_total += $line_total;
259         $qty_total += $qty;
260         my %line = %{ $results[$i] };
261                 ($i%2) and $line{toggle} = 1;
262
263         $line{order_received} = ( $qty eq $results[$i]->{'quantityreceived'} );
264         $line{basketno}       = $basketno;
265         $line{i}              = $i;
266         $line{budget_name}    = $budget->{budget_name};
267         $line{rrp}            = sprintf( "%.2f", $line{'rrp'} );
268         $line{ecost}          = sprintf( "%.2f", $line{'ecost'} );
269         $line{line_total}     = sprintf( "%.2f", $line_total );
270         $line{odd}            = $i % 2;
271         if ($line{uncertainprice}) {
272             $template->param( unclosable => 1 );
273             for my $key (qw/ecost line_total rrp/) {
274                 $line{$key} .= '??';
275             }
276         }
277         if ($line{'title'}){
278             my $volume = $results[$i]->{'volume'};
279             my $seriestitle = $results[$i]->{'seriestitle'};
280             $line{'title'} .= " / $seriestitle" if $seriestitle;
281             $line{'title'} .= " / $volume" if $volume;
282         } else {
283             $line{'title'} = "Deleted bibliographic notice, can't find title.";
284         }
285         push @books_loop, \%line;
286     }
287
288
289
290
291     my $prefgist = $bookseller->{gstrate} || C4::Context->preference("gist") || 0;
292     my $gist     = $sub_total     * $prefgist;
293     my $gist_rrp = $sub_total_rrp * $prefgist;
294     $grand_total     = $sub_total_est = $sub_total;
295     $grand_total_est = $sub_total_est;          # FIXME: Too many things that are ALL the SAME
296         my $temp;
297     if ($temp = $bookseller->{'listincgst'}) {
298                 $template->param(listincgst => $temp);
299                 $gist = 0;
300         } else {
301         $grand_total += $gist;
302         $grand_total_est += $sub_total_est * $prefgist;         # same thing as += gist
303     }
304     if ($temp = $bookseller->{'discount'}) {
305                 $template->param(discount => sprintf( "%.2f", $temp ));
306         }
307     my $contract = &GetContract($basket->{contractnumber});
308     $template->param(
309         basketno             => $basketno,
310         basketname           => $basket->{'basketname'},
311         basketnote           => $basket->{note},
312         basketbooksellernote => $basket->{booksellernote},
313         basketcontractno     => $basket->{contractnumber},
314         basketcontractname   => $contract->{contractname},
315         creationdate         => format_date( $basket->{creationdate} ),
316         authorisedby         => $basket->{authorisedby},
317         authorisedbyname     => $basket->{authorisedbyname},
318         closedate            => format_date( $basket->{closedate} ),
319         active               => $bookseller->{'active'},
320         booksellerid         => $bookseller->{'id'},
321         name                 => $bookseller->{'name'},
322         address1             => $bookseller->{'address1'},
323         address2             => $bookseller->{'address2'},
324         address3             => $bookseller->{'address3'},
325         address4             => $bookseller->{'address4'},
326         entrydate            => format_date( $results[0]->{'entrydate'} ),
327         books_loop           => \@books_loop,
328         sort_loop            => \@sort_loop,
329         count                => $count,
330         gist                 => $gist ? sprintf( "%.2f", $gist ) : 0,
331         gist_rate       => sprintf( "%.2f", $prefgist * 100 ) . '%',
332         gist_est        => sprintf( "%.2f", $sub_total_est * $prefgist ),
333         gist_rrp        => sprintf( "%.2f", $gist_rrp ),
334         sub_total       => sprintf( "%.2f", $sub_total ),
335         grand_total     => sprintf( "%.2f", $grand_total ),
336         sub_total_est   => sprintf( "%.2f", $sub_total_est ),
337         grand_total_est => sprintf( "%.2f", $grand_total_est ),
338         sub_total_rrp   => sprintf( "%.2f", $sub_total_rrp ),
339         grand_total_rrp => sprintf( "%.2f", $sub_total_rrp + $gist_rrp ),
340         currency        => $bookseller->{'listprice'},
341         qty_total       => $qty_total,
342         GST             => $prefgist,
343         basketgroups  =>  $basketgroups,
344         grouped    => $basket->{basketgroupid},
345     );
346 }
347 output_html_with_http_headers $query, $cookie, $template->output;