BZ6066 let's the librarian choose the itemtype when ordering
[wip/koha-chris_n.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         #to get active currency
221         my $cur = GetCurrency();
222
223
224     my @results = GetOrders( $basketno );
225     
226         my $gist = $bookseller->{gstrate} // C4::Context->preference("gist") // 0;
227         my $discount = $bookseller->{'discount'} / 100;
228     my $total_rrp;      # RRP Total, its value will be assigned to $total_rrp_gsti or $total_rrp_gste depending of $bookseller->{'listincgst'}
229         my $total_rrp_gsti; # RRP Total, GST included
230         my $total_rrp_gste; # RRP Total, GST excluded
231         my $gist_rrp;
232         
233     my $qty_total;
234     my @books_loop;
235
236     for my $order ( @results ) {
237         my $rrp = $order->{'listprice'} || 0;
238                 my $qty = $order->{'quantity'} || 0;
239         if (!defined $order->{quantityreceived}) {
240             $order->{quantityreceived} = 0;
241         }
242         for ( qw(rrp ecost quantityreceived)) {
243             if (!defined $order->{$_}) {
244                 $order->{$_} = 0;
245             }
246         }
247
248         my $budget = GetBudget(  $order->{'budget_id'} );
249         $rrp = ConvertCurrency( $order->{'currency'}, $rrp );
250
251         $total_rrp += $qty * $order->{'rrp'};
252         my $line_total = $qty * $order->{'ecost'};
253                 # FIXME: what about the "actual cost" field?
254         $qty_total += $qty;
255         my %line = %{ $order };
256
257         $line{order_received} = ( $qty == $order->{'quantityreceived'} );
258         $line{basketno}       = $basketno;
259         $line{budget_name}    = $budget->{budget_name};
260         $line{rrp}            = sprintf( "%.2f", $line{'rrp'} );
261         $line{ecost}          = sprintf( "%.2f", $line{'ecost'} );
262         $line{line_total}     = sprintf( "%.2f", $line_total );
263         if ($line{uncertainprice}) {
264             $template->param( uncertainprices => 1 );
265             $line{rrp} .= ' (Uncertain)';
266         }
267         if ($line{'title'}){
268             my $volume = $order->{'volume'};
269             my $seriestitle = $order->{'seriestitle'};
270             $line{'title'} .= " / $seriestitle" if $seriestitle;
271             $line{'title'} .= " / $volume" if $volume;
272         } else {
273             $line{'title'} = "Deleted bibliographic notice, can't find title.";
274         }
275         push @books_loop, \%line;
276     }
277
278         if ($bookseller->{'listincgst'}) {                        # if prices already includes GST
279                 $total_rrp_gsti = $total_rrp;                         # we know $total_rrp_gsti
280                 $total_rrp_gste = $total_rrp_gsti / ($gist + 1);      # and can reverse compute other values
281                 $gist_rrp       = $total_rrp_gsti - $total_rrp_gste;  #
282         } else {                                                  # if prices does not include GST
283                 $total_rrp_gste = $total_rrp;                         # then we use the common way to compute other values
284                 $gist_rrp = $total_rrp_gste * $gist;                  #
285                 $total_rrp_gsti = $total_rrp_gste + $gist_rrp;        #
286         }
287         # These vars are estimated totals and GST, taking in account the booksellet discount
288         my $total_est_gsti = $total_rrp_gsti - ($total_rrp_gsti * $discount);
289         my $gist_est       = $gist_rrp       - ($gist_rrp * $discount);
290         my $total_est_gste = $total_rrp_gste - ($total_rrp_gste * $discount);
291
292     my $contract = &GetContract($basket->{contractnumber});
293     my @orders = GetOrders($basketno);
294     $template->param(
295         basketno             => $basketno,
296         basketname           => $basket->{'basketname'},
297         basketnote           => $basket->{note},
298         basketbooksellernote => $basket->{booksellernote},
299         basketcontractno     => $basket->{contractnumber},
300         basketcontractname   => $contract->{contractname},
301         creationdate         => C4::Dates->new($basket->{creationdate},'iso')->output,
302         authorisedby         => $basket->{authorisedby},
303         authorisedbyname     => $basket->{authorisedbyname},
304         closedate            => C4::Dates->new($basket->{closedate},'iso')->output,
305         active               => $bookseller->{'active'},
306         booksellerid         => $bookseller->{'id'},
307         name                 => $bookseller->{'name'},
308         entrydate            => C4::Dates->new($results[0]->{'entrydate'},'iso')->output,
309         books_loop           => \@books_loop,
310         gist_rate            => sprintf( "%.2f", $gist * 100 ) . '%',
311         total_rrp_gste       => sprintf( "%.2f", $total_rrp_gste ),
312         total_est_gste       => sprintf( "%.2f", $total_est_gste ),
313         gist_est             => sprintf( "%.2f", $gist_est ),
314         gist_rrp             => sprintf( "%.2f", $gist_rrp ),        
315         total_rrp_gsti       => sprintf( "%.2f", $total_rrp_gsti ),
316         total_est_gsti       => sprintf( "%.2f", $total_est_gsti ),
317 #        currency             => $bookseller->{'listprice'},
318         currency                => $cur->{'currency'},
319         qty_total            => $qty_total,
320         GST                  => $gist,
321         basketgroups         => $basketgroups,
322         grouped              => $basket->{basketgroupid},
323         unclosable           => @orders ? 0 : 1, 
324     );
325 }
326
327 output_html_with_http_headers $query, $cookie, $template->output;