Bug 24157: New permission - delete_invoices
[koha.git] / acqui / invoice.pl
1 #!/usr/bin/perl
2
3 # Copyright 2011 BibLibre SARL
4 # This file is part of Koha.
5 #
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18
19 =head1 NAME
20
21 invoice.pl
22
23 =head1 DESCRIPTION
24
25 Invoice details
26
27 =cut
28
29 use Modern::Perl;
30
31 use CGI qw ( -utf8 );
32 use C4::Auth;
33 use C4::Output;
34 use C4::Acquisition;
35 use C4::Budgets;
36
37 use Koha::Acquisition::Booksellers;
38 use Koha::Acquisition::Currencies;
39 use Koha::DateUtils;
40 use Koha::Misc::Files;
41 use Koha::Acquisition::Invoice::Adjustments;
42
43 my $input = new CGI;
44 my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user(
45     {
46         template_name   => 'acqui/invoice.tt',
47         query           => $input,
48         type            => 'intranet',
49         authnotrequired => 0,
50         flagsrequired   => { 'acquisition' => '*' },
51         debug           => 1,
52     }
53 );
54
55 my $logged_in_patron = Koha::Patrons->find( $loggedinuser );
56 my $invoiceid = $input->param('invoiceid');
57 my $op        = $input->param('op');
58
59 output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
60   if $op
61   && not $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
62
63 my $invoice_files;
64 if ( C4::Context->preference('AcqEnableFiles') ) {
65     $invoice_files = Koha::Misc::Files->new(
66         tabletag => 'aqinvoices', recordid => $invoiceid );
67 }
68
69 if ( $op && $op eq 'close' ) {
70     CloseInvoice($invoiceid);
71     my $referer = $input->param('referer');
72     if ($referer) {
73         print $input->redirect($referer);
74         exit 0;
75     }
76 }
77 elsif ( $op && $op eq 'reopen' ) {
78     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
79         unless $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } );
80
81     ReopenInvoice($invoiceid);
82     my $referer = $input->param('referer');
83     if ($referer) {
84         print $input->redirect($referer);
85         exit 0;
86     }
87 }
88 elsif ( $op && $op eq 'mod' ) {
89     my $shipmentcost       = $input->param('shipmentcost');
90     my $shipment_budget_id = $input->param('shipment_budget_id');
91     my $invoicenumber      = $input->param('invoicenumber');
92     ModInvoice(
93         invoiceid             => $invoiceid,
94         invoicenumber         => $invoicenumber,
95         shipmentdate          => scalar output_pref( { str => scalar $input->param('shipmentdate'), dateformat => 'iso', dateonly => 1 } ),
96         billingdate           => scalar output_pref( { str => scalar $input->param('billingdate'),  dateformat => 'iso', dateonly => 1 } ),
97         shipmentcost          => $shipmentcost,
98         shipmentcost_budgetid => $shipment_budget_id
99     );
100     if ($input->param('reopen')) {
101         ReopenInvoice($invoiceid)
102             if $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } );
103     } elsif ($input->param('close')) {
104         CloseInvoice($invoiceid);
105     } elsif ($input->param('merge')) {
106         my @sources = $input->multi_param('merge');
107         MergeInvoices($invoiceid, \@sources);
108         defined($invoice_files) && $invoice_files->MergeFileRecIds(@sources);
109     }
110     $template->param( modified => 1 );
111 }
112 elsif ( $op && $op eq 'delete' ) {
113
114     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
115         unless $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } );
116
117     DelInvoice($invoiceid);
118     defined($invoice_files) && $invoice_files->DelAllFiles();
119     my $referer = $input->param('referer') || 'invoices.pl';
120     if ($referer) {
121         print $input->redirect($referer);
122         exit 0;
123     }
124 }
125 elsif ( $op && $op eq 'del_adj' ) {
126     my $adjustment_id  = $input->param('adjustment_id');
127     my $del_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id );
128     $del_adj->delete() if ($del_adj);
129 }
130 elsif ( $op && $op eq 'mod_adj' ) {
131     my @adjustment_id  = $input->multi_param('adjustment_id');
132     my @adjustment     = $input->multi_param('adjustment');
133     my @reason         = $input->multi_param('reason');
134     my @note           = $input->multi_param('note');
135     my @budget_id      = $input->multi_param('budget_id');
136     my @encumber_open  = $input->multi_param('encumber_open');
137     my %e_open = map { $_ => 1 } @encumber_open;
138
139     for( my $i=0; $i < scalar @adjustment; $i++ ){
140         if( $adjustment_id[$i] eq 'new' ){
141             next unless ( $adjustment[$i] || $reason[$i] );
142             my $new_adj = Koha::Acquisition::Invoice::Adjustment->new({
143                 invoiceid => $invoiceid,
144                 adjustment => $adjustment[$i],
145                 reason => $reason[$i],
146                 note => $note[$i],
147                 budget_id => $budget_id[$i] || undef,
148                 encumber_open => defined $e_open{ $adjustment_id[$i] } ? 1 : 0,
149             });
150             $new_adj->store();
151         }
152         else {
153             my $old_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id[$i] );
154             unless ( $old_adj->adjustment == $adjustment[$i] && $old_adj->reason eq $reason[$i] && $old_adj->budget_id == $budget_id[$i] && $old_adj->encumber_open == $e_open{$adjustment_id[$i]} && $old_adj->note eq $note[$i] ){
155                 $old_adj->timestamp(undef);
156                 $old_adj->adjustment( $adjustment[$i] );
157                 $old_adj->reason( $reason[$i] );
158                 $old_adj->note( $note[$i] );
159                 $old_adj->budget_id( $budget_id[$i] || undef );
160                 $old_adj->encumber_open( $e_open{$adjustment_id[$i]} ? 1 : 0 );
161                 $old_adj->update();
162             }
163         }
164     }
165 }
166
167 my $details = GetInvoiceDetails($invoiceid);
168 my $bookseller = Koha::Acquisition::Booksellers->find( $details->{booksellerid} );
169 my @orders_loop = ();
170 my $orders = $details->{'orders'};
171 my @foot_loop;
172 my %foot;
173 my $shipmentcost = $details->{shipmentcost} || 0;
174 my $total_quantity = 0;
175 my $total_tax_excluded = 0;
176 my $total_tax_included = 0;
177 my $total_tax_value = 0;
178 foreach my $order (@$orders) {
179     my $line = get_infos( $order, $bookseller);
180
181     $line->{total_tax_excluded} = get_rounded_price($line->{unitprice_tax_excluded}) * $line->{quantity};
182     $line->{total_tax_included} = get_rounded_price($line->{unitprice_tax_included}) * $line->{quantity};
183
184     $line->{tax_value} = $line->{tax_value_on_receiving};
185     $line->{tax_rate} = $line->{tax_rate_on_receiving};
186
187     $foot{$$line{tax_rate}}{tax_rate} = $$line{tax_rate};
188     $foot{$$line{tax_rate}}{tax_value} += get_rounded_price($$line{tax_value});
189     $total_tax_value += $$line{tax_value};
190     $foot{$$line{tax_rate}}{quantity}  += $$line{quantity};
191     $total_quantity += $$line{quantity};
192     $foot{$$line{tax_rate}}{total_tax_excluded} += get_rounded_price($$line{total_tax_excluded});
193     $total_tax_excluded += get_rounded_price($$line{total_tax_excluded});
194     $foot{$$line{tax_rate}}{total_tax_included} += get_rounded_price($$line{total_tax_included});
195     $total_tax_included += get_rounded_price($$line{total_tax_included});
196
197     $line->{orderline} = $line->{parent_ordernumber};
198     push @orders_loop, $line;
199 }
200
201 push @foot_loop, map {$_} values %foot;
202
203 my $shipmentcost_budgetid = $details->{shipmentcost_budgetid};
204
205 # build budget list
206 my $budget_loop = [];
207 my $budgets     = GetBudgetHierarchy();
208 foreach my $r ( @{$budgets} ) {
209     next unless ( CanUserUseBudget( $loggedinuser, $r, $flags ) );
210
211     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
212         next;
213     }
214
215     my $selected = $shipmentcost_budgetid ? $r->{budget_id} eq $shipmentcost_budgetid : 0;
216
217     push @{$budget_loop},
218       {
219         b_id     => $r->{budget_id},
220         b_txt    => $r->{budget_name},
221         b_active => $r->{budget_period_active},
222         selected => $selected,
223       };
224 }
225
226 @{$budget_loop} =
227   sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop};
228
229 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({ invoiceid => $details->{'invoiceid'} });
230 if ( $adjustments ) { $template->param( adjustments => $adjustments ); }
231
232 $template->param(
233     invoiceid                   => $details->{'invoiceid'},
234     invoicenumber               => $details->{'invoicenumber'},
235     suppliername                => $details->{'suppliername'},
236     booksellerid                => $details->{'booksellerid'},
237     shipmentdate                => $details->{'shipmentdate'},
238     billingdate                 => $details->{'billingdate'},
239     invoiceclosedate            => $details->{'closedate'},
240     shipmentcost                => $shipmentcost,
241     orders_loop                 => \@orders_loop,
242     foot_loop                   => \@foot_loop,
243     total_quantity              => $total_quantity,
244     total_tax_excluded          => $total_tax_excluded,
245     total_tax_included          => $total_tax_included,
246     total_tax_value             => $total_tax_value,
247     total_tax_excluded_shipment => $total_tax_excluded + $shipmentcost,
248     total_tax_included_shipment => $total_tax_included + $shipmentcost,
249     invoiceincgst               => $bookseller->invoiceincgst,
250     currency                    => Koha::Acquisition::Currencies->get_active,
251     budgets                     => $budget_loop,
252     budget                      => GetBudget( $shipmentcost_budgetid ),
253 );
254
255 defined( $invoice_files ) && $template->param( files => $invoice_files->GetFilesInfo() );
256
257 # FIXME
258 # Fonction dupplicated from basket.pl
259 # Code must to be exported. Where ??
260 sub get_infos {
261     my $order = shift;
262     my $bookseller = shift;
263     my $qty = $order->{'quantity'} || 0;
264     if ( !defined $order->{quantityreceived} ) {
265         $order->{quantityreceived} = 0;
266     }
267     my $budget = GetBudget( $order->{'budget_id'} );
268
269     my %line = %{ $order };
270     $line{order_received} = ( $qty == $order->{'quantityreceived'} );
271     $line{budget_name}    = $budget->{budget_name};
272
273     if ( $line{'title'} ) {
274         my $volume      = $order->{'volume'};
275         my $seriestitle = $order->{'seriestitle'};
276         $line{'title'} .= " / $seriestitle" if $seriestitle;
277         $line{'title'} .= " / $volume"      if $volume;
278     }
279
280     return \%line;
281 }
282
283 output_html_with_http_headers $input, $cookie, $template->output;