Bug 24190: Add acquisition logging
[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 C4::Log qw(logaction);
37
38 use Koha::Acquisition::Booksellers;
39 use Koha::Acquisition::Currencies qw( get_active );
40 use Koha::DateUtils qw( output_pref );
41 use Koha::Misc::Files;
42 use Koha::Acquisition::Invoice::Adjustments;
43
44 my $input = CGI->new;
45 my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user(
46     {
47         template_name   => 'acqui/invoice.tt',
48         query           => $input,
49         type            => 'intranet',
50         flagsrequired   => { 'acquisition' => '*' },
51     }
52 );
53
54 my $logged_in_patron = Koha::Patrons->find( $loggedinuser );
55 my $invoiceid = $input->param('invoiceid');
56 my $op        = $input->param('op');
57
58 output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
59   if $op
60   && ! $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } )
61   && ! $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } )
62   && ! $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } )
63   && ! $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } );
64
65 my $invoice_files;
66 if ( C4::Context->preference('AcqEnableFiles') ) {
67     $invoice_files = Koha::Misc::Files->new(
68         tabletag => 'aqinvoices', recordid => $invoiceid );
69 }
70
71 if ( $op && $op eq 'close' ) {
72     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
73         unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
74     my @invoiceid = $input->multi_param('invoiceid');
75     foreach my $invoiceid ( @invoiceid ) {
76         CloseInvoice($invoiceid);
77     }
78     my $referer = $input->param('referer');
79     if ($referer) {
80         print $input->redirect($referer);
81         exit 0;
82     }
83 }
84 elsif ( $op && $op eq 'reopen' ) {
85     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
86         unless $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } );
87     my @invoiceid = $input->multi_param('invoiceid');
88     foreach my $invoiceid ( @invoiceid ) {
89         ReopenInvoice($invoiceid);
90     }
91     my $referer = $input->param('referer');
92     if ($referer) {
93         print $input->redirect($referer);
94         exit 0;
95     }
96 }
97 elsif ( $op && $op eq 'mod' ) {
98     my $shipmentcost       = $input->param('shipmentcost');
99     my $shipment_budget_id = $input->param('shipment_budget_id');
100     my $invoicenumber      = $input->param('invoicenumber');
101     ModInvoice(
102         invoiceid             => $invoiceid,
103         invoicenumber         => $invoicenumber,
104         shipmentdate          => scalar output_pref( { str => scalar $input->param('shipmentdate'), dateformat => 'iso', dateonly => 1 } ),
105         billingdate           => scalar output_pref( { str => scalar $input->param('billingdate'),  dateformat => 'iso', dateonly => 1 } ),
106         shipmentcost          => $shipmentcost,
107         shipmentcost_budgetid => $shipment_budget_id
108     );
109     if ($input->param('reopen')) {
110         ReopenInvoice($invoiceid)
111             if $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } );
112     } elsif ($input->param('close')) {
113
114         output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
115             unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
116
117         CloseInvoice($invoiceid);
118     } elsif ($input->param('merge')) {
119
120         output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
121             unless $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } );
122
123         my @sources = $input->multi_param('merge');
124         MergeInvoices($invoiceid, \@sources);
125         defined($invoice_files) && $invoice_files->MergeFileRecIds(@sources);
126     }
127     $template->param( modified => 1 );
128 }
129 elsif ( $op && $op eq 'delete' ) {
130
131     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
132         unless $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } );
133
134     DelInvoice($invoiceid);
135     defined($invoice_files) && $invoice_files->DelAllFiles();
136     my $referer = $input->param('referer') || 'invoices.pl';
137     if ($referer) {
138         print $input->redirect($referer);
139         exit 0;
140     }
141 }
142 elsif ( $op && $op eq 'del_adj' ) {
143
144     output_and_exit( $input, $cookie, $template, 'insufficient_permission' )
145         unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } );
146
147     my $adjustment_id  = $input->param('adjustment_id');
148     my $del_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id );
149     if ($del_adj) {
150         if (C4::Context->preference("AcqLog")) {
151             my $reason_length = length $del_adj->reason;
152             my $reason_padded = ( ' ' x (80 - $reason_length) ) . $del_adj->reason;
153             my $infos =
154                 sprintf("%010d", $del_adj->invoiceid) .
155                 sprintf("%010d", $del_adj->budget_id) .
156                 sprintf("%010d", $del_adj->encumber_open) .
157                 sprintf("%010.2f", $del_adj->adjustment) .
158                 $reason_padded;
159             logaction(
160                 'ACQUISITIONS',
161                 'DELETE_INVOICE_ADJUSTMENT',
162                 $adjustment_id,
163                 $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("AcqLog")) {
198                 my $infos = get_log_string($adj);
199                 logaction(
200                     'ACQUISITIONS',
201                     'CREATE_INVOICE_ADJUSTMENT',
202                     $new_adj->adjustment_id,
203                     $infos
204                 );
205             }
206         }
207         else {
208             my $old_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id[$i] );
209             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] ){
210                 # Log this modification
211                 if (C4::Context->preference("AcqLog")) {
212                     my $infos = get_log_string({
213                         adjustment        => $adjustment[$i],
214                         reason            => $reason[$i],
215                         budget_id         => $budget_id[$i],
216                         encumber_open     => $e_open{$adjustment_id[$i]},
217                         adjustment_old    => $old_adj->adjustment,
218                         reason_old        => $old_adj->reason,
219                         budget_id_old     => $old_adj->budget_id,
220                         encumber_open_old => $old_adj->encumber_open
221                     });
222                     logaction(
223                         'ACQUISITIONS',
224                         'UPDATE_INVOICE_ADJUSTMENT',
225                         $adjustment_id[$i],
226                         $infos
227                     );
228                 }
229                 $old_adj->timestamp(undef);
230                 $old_adj->adjustment( $adjustment[$i] );
231                 $old_adj->reason( $reason[$i] );
232                 $old_adj->note( $note[$i] );
233                 $old_adj->budget_id( $budget_id[$i] || undef );
234                 $old_adj->encumber_open( $e_open{$adjustment_id[$i]} ? 1 : 0 );
235                 $old_adj->update();
236             }
237         }
238     }
239 }
240
241 my $details = GetInvoiceDetails($invoiceid);
242 my $bookseller = Koha::Acquisition::Booksellers->find( $details->{booksellerid} );
243 my @orders_loop = ();
244 my $orders = $details->{'orders'};
245 my @foot_loop;
246 my %foot;
247 my $shipmentcost = $details->{shipmentcost} || 0;
248 my $total_quantity = 0;
249 my $total_tax_excluded = 0;
250 my $total_tax_included = 0;
251 my $total_tax_value = 0;
252 foreach my $order (@$orders) {
253     my $line = get_infos( $order, $bookseller);
254
255     $line->{total_tax_excluded} = get_rounded_price($line->{unitprice_tax_excluded}) * $line->{quantity};
256     $line->{total_tax_included} = get_rounded_price($line->{unitprice_tax_included}) * $line->{quantity};
257
258     $line->{tax_value} = $line->{tax_value_on_receiving};
259     $line->{tax_rate} = $line->{tax_rate_on_receiving};
260
261     $foot{$$line{tax_rate}}{tax_rate} = $$line{tax_rate};
262     $foot{$$line{tax_rate}}{tax_value} += get_rounded_price($$line{tax_value});
263     $total_tax_value += $$line{tax_value};
264     $foot{$$line{tax_rate}}{quantity}  += $$line{quantity};
265     $total_quantity += $$line{quantity};
266     $foot{$$line{tax_rate}}{total_tax_excluded} += get_rounded_price($$line{total_tax_excluded});
267     $total_tax_excluded += get_rounded_price($$line{total_tax_excluded});
268     $foot{$$line{tax_rate}}{total_tax_included} += get_rounded_price($$line{total_tax_included});
269     $total_tax_included += get_rounded_price($$line{total_tax_included});
270
271     $line->{orderline} = $line->{parent_ordernumber};
272     push @orders_loop, $line;
273 }
274
275 push @foot_loop, map {$_} values %foot;
276
277 my $shipmentcost_budgetid = $details->{shipmentcost_budgetid};
278
279 # build budget list
280 my $budget_loop = [];
281 my $budgets     = GetBudgetHierarchy();
282 foreach my $r ( @{$budgets} ) {
283     next unless ( CanUserUseBudget( $loggedinuser, $r, $flags ) );
284
285     my $selected = $shipmentcost_budgetid ? $r->{budget_id} eq $shipmentcost_budgetid : 0;
286
287     push @{$budget_loop},
288       {
289         b_id     => $r->{budget_id},
290         b_txt    => $r->{budget_name},
291         b_active => $r->{budget_period_active},
292         selected => $selected,
293       };
294 }
295
296 @{$budget_loop} =
297   sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop};
298
299 my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({ invoiceid => $details->{'invoiceid'} });
300 if ( $adjustments ) { $template->param( adjustments => $adjustments ); }
301
302 $template->param(
303     invoiceid                   => $details->{'invoiceid'},
304     invoicenumber               => $details->{'invoicenumber'},
305     suppliername                => $details->{'suppliername'},
306     booksellerid                => $details->{'booksellerid'},
307     shipmentdate                => $details->{'shipmentdate'},
308     billingdate                 => $details->{'billingdate'},
309     invoiceclosedate            => $details->{'closedate'},
310     shipmentcost                => $shipmentcost,
311     orders_loop                 => \@orders_loop,
312     foot_loop                   => \@foot_loop,
313     total_quantity              => $total_quantity,
314     total_tax_excluded          => $total_tax_excluded,
315     total_tax_included          => $total_tax_included,
316     total_tax_value             => $total_tax_value,
317     total_tax_excluded_shipment => $total_tax_excluded + $shipmentcost,
318     total_tax_included_shipment => $total_tax_included + $shipmentcost,
319     invoiceincgst               => $bookseller->invoiceincgst,
320     currency                    => Koha::Acquisition::Currencies->get_active,
321     budgets                     => $budget_loop,
322     budget                      => GetBudget( $shipmentcost_budgetid ),
323 );
324
325 defined( $invoice_files ) && $template->param( files => $invoice_files->GetFilesInfo() );
326
327 # FIXME
328 # Fonction dupplicated from basket.pl
329 # Code must to be exported. Where ??
330 sub get_infos {
331     my $order = shift;
332     my $bookseller = shift;
333     my $qty = $order->{'quantity'} || 0;
334     if ( !defined $order->{quantityreceived} ) {
335         $order->{quantityreceived} = 0;
336     }
337     my $budget = GetBudget( $order->{'budget_id'} );
338
339     my %line = %{ $order };
340     $line{order_received} = ( $qty == $order->{'quantityreceived'} );
341     $line{budget_name}    = $budget->{budget_name};
342
343     if ( $line{'title'} ) {
344         my $volume      = $order->{'volume'};
345         my $seriestitle = $order->{'seriestitle'};
346         $line{'title'} .= " / $seriestitle" if $seriestitle;
347         $line{'title'} .= " / $volume"      if $volume;
348     }
349
350     return \%line;
351 }
352
353 sub get_log_string {
354     my ($data) = @_;
355
356     # We specify the keys we're dealing for logging within an array in order
357     # to preserve order, if we just iterate the hash keys, we could get
358     # the values in any order
359     my @keys = (
360         'budget_id',
361         'encumber_open',
362         'budget_id_old',
363         'encumber_open_old'
364     );
365     # Adjustment amount
366     my $return = sprintf("%010.2f", $data->{adjustment});
367     # Left pad "reason" to the maximum length of aqinvoice_adjustments.reason
368     # (80 characters)
369     my $reason_len = length $data->{reason};
370     $return .= ( ' ' x (80 - $reason_len) ) . $data->{reason};
371     # Append the remaining fields
372     foreach my $key(@keys) {
373         $return .= sprintf("%010d", $data->{$key});
374     }
375     # Old adjustment amount
376     $return .= sprintf("%010.2f", $data->{adjustment_old});
377     # Left pad "reason_old" to the maximum length of aqinvoice_adjustments.reason
378     # (80 characters)
379     my $reason_old_len = length $data->{reason_old};
380     $return .= ( ' ' x (80 - $reason_old_len) ) . $data->{reason_old};
381     return $return;
382 }
383
384 output_html_with_http_headers $input, $cookie, $template->output;