Bug 31569: Remove GetImportRecordsRange from import_biblios_list
[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 qw( get_template_and_user );
33 use C4::Output qw( output_and_exit output_html_with_http_headers );
34 use C4::Acquisition qw( CloseInvoice ReopenInvoice ModInvoice MergeInvoices DelInvoice GetInvoice GetInvoiceDetails get_rounded_price );
35 use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget );
36 use JSON qw( encode_json );
37 use C4::Log qw(logaction);
38
39 use Koha::Acquisition::Booksellers;
40 use Koha::Acquisition::Currencies qw( get_active );
41 use Koha::DateUtils qw( output_pref );
42 use Koha::Misc::Files;
43 use Koha::Acquisition::Invoice::Adjustments;
44
45 my $input = CGI->new;
46 my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user(
47     {
48         template_name   => 'acqui/invoice.tt',
49         query           => $input,
50         type            => 'intranet',
51         flagsrequired   => { 'acquisition' => '*' },
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   && ! $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } )
62   && ! $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } )
63   && ! $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } )
64   && ! $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } );
65
66 my $invoice_files;
67 if ( C4::Context->preference('AcqEnableFiles') ) {
68     $invoice_files = Koha::Misc::Files->new(
69         tabletag => 'aqinvoices', recordid => $invoiceid );
70 }
71
72 if ( $op && $op eq 'close' ) {
73     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
74         unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
75     my @invoiceid = $input->multi_param('invoiceid');
76     foreach my $invoiceid ( @invoiceid ) {
77         CloseInvoice($invoiceid);
78     }
79     my $referer = $input->param('referer');
80     if ($referer) {
81         print $input->redirect($referer);
82         exit 0;
83     }
84 }
85 elsif ( $op && $op eq 'reopen' ) {
86     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
87         unless $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } );
88     my @invoiceid = $input->multi_param('invoiceid');
89     foreach my $invoiceid ( @invoiceid ) {
90         ReopenInvoice($invoiceid);
91     }
92     my $referer = $input->param('referer');
93     if ($referer) {
94         print $input->redirect($referer);
95         exit 0;
96     }
97 }
98 elsif ( $op && $op eq 'mod' ) {
99     my $shipmentcost       = $input->param('shipmentcost');
100     my $shipment_budget_id = $input->param('shipment_budget_id');
101     my $invoicenumber      = $input->param('invoicenumber');
102     ModInvoice(
103         invoiceid             => $invoiceid,
104         invoicenumber         => $invoicenumber,
105         shipmentdate          => scalar $input->param('shipmentdate'),
106         billingdate           => scalar $input->param('billingdate'),
107         shipmentcost          => $shipmentcost,
108         shipmentcost_budgetid => $shipment_budget_id
109     );
110     if ($input->param('reopen')) {
111         ReopenInvoice($invoiceid)
112             if $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } );
113     } elsif ($input->param('close')) {
114
115         output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
116             unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
117
118         CloseInvoice($invoiceid);
119     } elsif ($input->param('merge')) {
120
121         output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
122             unless $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } );
123
124         my @sources = $input->multi_param('merge');
125         MergeInvoices($invoiceid, \@sources);
126         defined($invoice_files) && $invoice_files->MergeFileRecIds(@sources);
127     }
128     $template->param( modified => 1 );
129 }
130 elsif ( $op && $op eq 'delete' ) {
131
132     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
133         unless $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } );
134
135     DelInvoice($invoiceid);
136     defined($invoice_files) && $invoice_files->DelAllFiles();
137     my $referer = $input->param('referer') || 'invoices.pl';
138     if ($referer) {
139         print $input->redirect($referer);
140         exit 0;
141     }
142 }
143 elsif ( $op && $op eq 'del_adj' ) {
144
145     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
146         unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
147
148     my $adjustment_id  = $input->param('adjustment_id');
149     my $del_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id );
150     if ($del_adj) {
151         if (C4::Context->preference("AcquisitionLog")) {
152             my $infos = {
153                 invoiceid     => $del_adj->invoiceid,
154                 budget_id     => $del_adj->budget_id,
155                 encumber_open => $del_adj->encumber_open,
156                 adjustment    => $del_adj->adjustment,
157                 reason        => $del_adj->reason
158             };
159             logaction(
160                 'ACQUISITIONS',
161                 'DELETE_INVOICE_ADJUSTMENT',
162                 $adjustment_id,
163                 encode_json($infos)
164             );
165         }
166         $del_adj->delete();
167     }
168 }
169 elsif ( $op && $op eq 'mod_adj' ) {
170
171     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
172         unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
173
174     my @adjustment_id  = $input->multi_param('adjustment_id');
175     my @adjustment     = $input->multi_param('adjustment');
176     my @reason         = $input->multi_param('reason');
177     my @note           = $input->multi_param('note');
178     my @budget_id      = $input->multi_param('budget_id');
179     my @encumber_open  = $input->multi_param('encumber_open');
180     my %e_open = map { $_ => 1 } @encumber_open;
181
182     my @keys = ('adjustment', 'reason', 'budget_id', 'encumber_open');
183     for( my $i=0; $i < scalar @adjustment; $i++ ){
184         if( $adjustment_id[$i] eq 'new' ){
185             next unless ( $adjustment[$i] || $reason[$i] );
186             my $adj = {
187                 invoiceid => $invoiceid,
188                 adjustment => $adjustment[$i],
189                 reason => $reason[$i],
190                 note => $note[$i],
191                 budget_id => $budget_id[$i] || undef,
192                 encumber_open => defined $e_open{ $adjustment_id[$i] } ? 1 : 0,
193             };
194             my $new_adj = Koha::Acquisition::Invoice::Adjustment->new($adj);
195             $new_adj->store();
196             # Log this addition
197             if (C4::Context->preference("AcquisitionLog")) {
198                 logaction(
199                     'ACQUISITIONS',
200                     'CREATE_INVOICE_ADJUSTMENT',
201                     $new_adj->adjustment_id,
202                     encode_json($adj)
203                 );
204             }
205         }
206         else {
207             my $old_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id[$i] );
208             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] ){
209                 # Log this modification
210                 if (C4::Context->preference("AcquisitionLog")) {
211                     my $infos = {
212                         adjustment        => $adjustment[$i],
213                         reason            => $reason[$i],
214                         budget_id         => $budget_id[$i],
215                         encumber_open     => $e_open{$adjustment_id[$i]},
216                         adjustment_old    => $old_adj->adjustment,
217                         reason_old        => $old_adj->reason,
218                         budget_id_old     => $old_adj->budget_id,
219                         encumber_open_old => $old_adj->encumber_open
220                     };
221                     logaction(
222                         'ACQUISITIONS',
223                         'UPDATE_INVOICE_ADJUSTMENT',
224                         $adjustment_id[$i],
225                         encode_json($infos)
226                     );
227                 }
228                 $old_adj->timestamp(undef);
229                 $old_adj->adjustment( $adjustment[$i] );
230                 $old_adj->reason( $reason[$i] );
231                 $old_adj->note( $note[$i] );
232                 $old_adj->budget_id( $budget_id[$i] || undef );
233                 $old_adj->encumber_open( $e_open{$adjustment_id[$i]} ? 1 : 0 );
234                 $old_adj->update();
235             }
236         }
237     }
238 }
239
240 my $details = GetInvoiceDetails($invoiceid);
241 my $bookseller = Koha::Acquisition::Booksellers->find( $details->{booksellerid} );
242 my @orders_loop = ();
243 my $orders = $details->{'orders'};
244 my @foot_loop;
245 my %foot;
246 my $shipmentcost = $details->{shipmentcost} || 0;
247 my $total_quantity = 0;
248 my $total_tax_excluded = 0;
249 my $total_tax_included = 0;
250 my $total_tax_value = 0;
251 foreach my $order (@$orders) {
252     my $line = get_infos( $order, $bookseller);
253
254     $line->{total_tax_excluded} = get_rounded_price($line->{unitprice_tax_excluded}) * $line->{quantity};
255     $line->{total_tax_included} = get_rounded_price($line->{unitprice_tax_included}) * $line->{quantity};
256
257     $line->{tax_value} = $line->{tax_value_on_receiving};
258     $line->{tax_rate} = $line->{tax_rate_on_receiving};
259
260     $foot{$$line{tax_rate}}{tax_rate} = $$line{tax_rate};
261     $foot{$$line{tax_rate}}{tax_value} += get_rounded_price($$line{tax_value});
262     $total_tax_value += $$line{tax_value};
263     $foot{$$line{tax_rate}}{quantity}  += $$line{quantity};
264     $total_quantity += $$line{quantity};
265     $foot{$$line{tax_rate}}{total_tax_excluded} += get_rounded_price($$line{total_tax_excluded});
266     $total_tax_excluded += get_rounded_price($$line{total_tax_excluded});
267     $foot{$$line{tax_rate}}{total_tax_included} += get_rounded_price($$line{total_tax_included});
268     $total_tax_included += get_rounded_price($$line{total_tax_included});
269
270     $line->{orderline} = $line->{parent_ordernumber};
271     push @orders_loop, $line;
272 }
273
274 push @foot_loop, map {$_} values %foot;
275
276 my $shipmentcost_budgetid = $details->{shipmentcost_budgetid};
277
278 # build budget list
279 my $budget_loop = [];
280 my $budgets     = GetBudgetHierarchy();
281 foreach my $r ( @{$budgets} ) {
282     next unless ( CanUserUseBudget( $loggedinuser, $r, $flags ) );
283
284     my $selected = $shipmentcost_budgetid ? $r->{budget_id} eq $shipmentcost_budgetid : 0;
285
286     push @{$budget_loop},
287       {
288         b_id     => $r->{budget_id},
289         b_txt    => $r->{budget_name},
290         b_active => $r->{budget_period_active},
291         selected => $selected,
292       };
293 }
294
295 @{$budget_loop} =
296   sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop};
297
298 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({ invoiceid => $details->{'invoiceid'} });
299 if ( $adjustments ) { $template->param( adjustments => $adjustments ); }
300
301 $template->param(
302     invoiceid                   => $details->{'invoiceid'},
303     invoicenumber               => $details->{'invoicenumber'},
304     suppliername                => $details->{'suppliername'},
305     booksellerid                => $details->{'booksellerid'},
306     shipmentdate                => $details->{'shipmentdate'},
307     billingdate                 => $details->{'billingdate'},
308     invoiceclosedate            => $details->{'closedate'},
309     shipmentcost                => $shipmentcost,
310     orders_loop                 => \@orders_loop,
311     foot_loop                   => \@foot_loop,
312     total_quantity              => $total_quantity,
313     total_tax_excluded          => $total_tax_excluded,
314     total_tax_included          => $total_tax_included,
315     total_tax_value             => $total_tax_value,
316     total_tax_excluded_shipment => $total_tax_excluded + $shipmentcost,
317     total_tax_included_shipment => $total_tax_included + $shipmentcost,
318     invoiceincgst               => $bookseller->invoiceincgst,
319     currency                    => Koha::Acquisition::Currencies->get_active,
320     budgets                     => $budget_loop,
321     budget                      => GetBudget( $shipmentcost_budgetid ),
322 );
323
324 defined( $invoice_files ) && $template->param( files => $invoice_files->GetFilesInfo() );
325
326 # FIXME
327 # Fonction dupplicated from basket.pl
328 # Code must to be exported. Where ??
329 sub get_infos {
330     my $order = shift;
331     my $bookseller = shift;
332     my $qty = $order->{'quantity'} || 0;
333     if ( !defined $order->{quantityreceived} ) {
334         $order->{quantityreceived} = 0;
335     }
336     my $budget = GetBudget( $order->{'budget_id'} );
337
338     my %line = %{ $order };
339     $line{order_received} = ( $qty == $order->{'quantityreceived'} );
340     $line{budget_name}    = $budget->{budget_name};
341
342     if ( $line{'title'} ) {
343         my $volume      = $order->{'volume'};
344         my $seriestitle = $order->{'seriestitle'};
345         $line{'title'} .= " / $seriestitle" if $seriestitle;
346         $line{'title'} .= " / $volume"      if $volume;
347     }
348
349     return \%line;
350 }
351
352 output_html_with_http_headers $input, $cookie, $template->output;