Bug 24157: New permission - merge_invoices
[srvgit] / 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
107         output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
108             unless $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } );
109
110         my @sources = $input->multi_param('merge');
111         MergeInvoices($invoiceid, \@sources);
112         defined($invoice_files) && $invoice_files->MergeFileRecIds(@sources);
113     }
114     $template->param( modified => 1 );
115 }
116 elsif ( $op && $op eq 'delete' ) {
117
118     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
119         unless $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } );
120
121     DelInvoice($invoiceid);
122     defined($invoice_files) && $invoice_files->DelAllFiles();
123     my $referer = $input->param('referer') || 'invoices.pl';
124     if ($referer) {
125         print $input->redirect($referer);
126         exit 0;
127     }
128 }
129 elsif ( $op && $op eq 'del_adj' ) {
130     my $adjustment_id  = $input->param('adjustment_id');
131     my $del_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id );
132     $del_adj->delete() if ($del_adj);
133 }
134 elsif ( $op && $op eq 'mod_adj' ) {
135     my @adjustment_id  = $input->multi_param('adjustment_id');
136     my @adjustment     = $input->multi_param('adjustment');
137     my @reason         = $input->multi_param('reason');
138     my @note           = $input->multi_param('note');
139     my @budget_id      = $input->multi_param('budget_id');
140     my @encumber_open  = $input->multi_param('encumber_open');
141     my %e_open = map { $_ => 1 } @encumber_open;
142
143     for( my $i=0; $i < scalar @adjustment; $i++ ){
144         if( $adjustment_id[$i] eq 'new' ){
145             next unless ( $adjustment[$i] || $reason[$i] );
146             my $new_adj = Koha::Acquisition::Invoice::Adjustment->new({
147                 invoiceid => $invoiceid,
148                 adjustment => $adjustment[$i],
149                 reason => $reason[$i],
150                 note => $note[$i],
151                 budget_id => $budget_id[$i] || undef,
152                 encumber_open => defined $e_open{ $adjustment_id[$i] } ? 1 : 0,
153             });
154             $new_adj->store();
155         }
156         else {
157             my $old_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id[$i] );
158             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] ){
159                 $old_adj->timestamp(undef);
160                 $old_adj->adjustment( $adjustment[$i] );
161                 $old_adj->reason( $reason[$i] );
162                 $old_adj->note( $note[$i] );
163                 $old_adj->budget_id( $budget_id[$i] || undef );
164                 $old_adj->encumber_open( $e_open{$adjustment_id[$i]} ? 1 : 0 );
165                 $old_adj->update();
166             }
167         }
168     }
169 }
170
171 my $details = GetInvoiceDetails($invoiceid);
172 my $bookseller = Koha::Acquisition::Booksellers->find( $details->{booksellerid} );
173 my @orders_loop = ();
174 my $orders = $details->{'orders'};
175 my @foot_loop;
176 my %foot;
177 my $shipmentcost = $details->{shipmentcost} || 0;
178 my $total_quantity = 0;
179 my $total_tax_excluded = 0;
180 my $total_tax_included = 0;
181 my $total_tax_value = 0;
182 foreach my $order (@$orders) {
183     my $line = get_infos( $order, $bookseller);
184
185     $line->{total_tax_excluded} = get_rounded_price($line->{unitprice_tax_excluded}) * $line->{quantity};
186     $line->{total_tax_included} = get_rounded_price($line->{unitprice_tax_included}) * $line->{quantity};
187
188     $line->{tax_value} = $line->{tax_value_on_receiving};
189     $line->{tax_rate} = $line->{tax_rate_on_receiving};
190
191     $foot{$$line{tax_rate}}{tax_rate} = $$line{tax_rate};
192     $foot{$$line{tax_rate}}{tax_value} += get_rounded_price($$line{tax_value});
193     $total_tax_value += $$line{tax_value};
194     $foot{$$line{tax_rate}}{quantity}  += $$line{quantity};
195     $total_quantity += $$line{quantity};
196     $foot{$$line{tax_rate}}{total_tax_excluded} += get_rounded_price($$line{total_tax_excluded});
197     $total_tax_excluded += get_rounded_price($$line{total_tax_excluded});
198     $foot{$$line{tax_rate}}{total_tax_included} += get_rounded_price($$line{total_tax_included});
199     $total_tax_included += get_rounded_price($$line{total_tax_included});
200
201     $line->{orderline} = $line->{parent_ordernumber};
202     push @orders_loop, $line;
203 }
204
205 push @foot_loop, map {$_} values %foot;
206
207 my $shipmentcost_budgetid = $details->{shipmentcost_budgetid};
208
209 # build budget list
210 my $budget_loop = [];
211 my $budgets     = GetBudgetHierarchy();
212 foreach my $r ( @{$budgets} ) {
213     next unless ( CanUserUseBudget( $loggedinuser, $r, $flags ) );
214
215     if ( !defined $r->{budget_amount} || $r->{budget_amount} == 0 ) {
216         next;
217     }
218
219     my $selected = $shipmentcost_budgetid ? $r->{budget_id} eq $shipmentcost_budgetid : 0;
220
221     push @{$budget_loop},
222       {
223         b_id     => $r->{budget_id},
224         b_txt    => $r->{budget_name},
225         b_active => $r->{budget_period_active},
226         selected => $selected,
227       };
228 }
229
230 @{$budget_loop} =
231   sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop};
232
233 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({ invoiceid => $details->{'invoiceid'} });
234 if ( $adjustments ) { $template->param( adjustments => $adjustments ); }
235
236 $template->param(
237     invoiceid                   => $details->{'invoiceid'},
238     invoicenumber               => $details->{'invoicenumber'},
239     suppliername                => $details->{'suppliername'},
240     booksellerid                => $details->{'booksellerid'},
241     shipmentdate                => $details->{'shipmentdate'},
242     billingdate                 => $details->{'billingdate'},
243     invoiceclosedate            => $details->{'closedate'},
244     shipmentcost                => $shipmentcost,
245     orders_loop                 => \@orders_loop,
246     foot_loop                   => \@foot_loop,
247     total_quantity              => $total_quantity,
248     total_tax_excluded          => $total_tax_excluded,
249     total_tax_included          => $total_tax_included,
250     total_tax_value             => $total_tax_value,
251     total_tax_excluded_shipment => $total_tax_excluded + $shipmentcost,
252     total_tax_included_shipment => $total_tax_included + $shipmentcost,
253     invoiceincgst               => $bookseller->invoiceincgst,
254     currency                    => Koha::Acquisition::Currencies->get_active,
255     budgets                     => $budget_loop,
256     budget                      => GetBudget( $shipmentcost_budgetid ),
257 );
258
259 defined( $invoice_files ) && $template->param( files => $invoice_files->GetFilesInfo() );
260
261 # FIXME
262 # Fonction dupplicated from basket.pl
263 # Code must to be exported. Where ??
264 sub get_infos {
265     my $order = shift;
266     my $bookseller = shift;
267     my $qty = $order->{'quantity'} || 0;
268     if ( !defined $order->{quantityreceived} ) {
269         $order->{quantityreceived} = 0;
270     }
271     my $budget = GetBudget( $order->{'budget_id'} );
272
273     my %line = %{ $order };
274     $line{order_received} = ( $qty == $order->{'quantityreceived'} );
275     $line{budget_name}    = $budget->{budget_name};
276
277     if ( $line{'title'} ) {
278         my $volume      = $order->{'volume'};
279         my $seriestitle = $order->{'seriestitle'};
280         $line{'title'} .= " / $seriestitle" if $seriestitle;
281         $line{'title'} .= " / $volume"      if $volume;
282     }
283
284     return \%line;
285 }
286
287 output_html_with_http_headers $input, $cookie, $template->output;