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