bbe4edf2c58bd7e5913e51036fabe96368d6193a
[kivitendo-erp.git] / SL / Controller / BankTransaction.pm
1 package SL::Controller::BankTransaction;
2
3 # idee- möglichkeit bankdaten zu übernehmen in stammdaten
4 # erst Kontenabgleich, um alle gl-Einträge wegzuhaben
5 use strict;
6
7 use parent qw(SL::Controller::Base);
8
9 use SL::Controller::Helper::GetModels;
10 use SL::Controller::Helper::ReportGenerator;
11 use SL::ReportGenerator;
12
13 use SL::DB::BankTransaction;
14 use SL::Helper::Flash;
15 use SL::Locale::String;
16 use SL::SEPA;
17 use SL::DB::Invoice;
18 use SL::DB::PurchaseInvoice;
19 use SL::DB::RecordLink;
20 use SL::JSON;
21 use SL::DB::Chart;
22 use SL::DB::AccTransaction;
23 use SL::DB::Tax;
24 use SL::DB::Draft;
25 use SL::DB::BankAccount;
26 use SL::Presenter;
27 use List::Util qw(max);
28
29 use Rose::Object::MakeMethods::Generic
30 (
31  'scalar --get_set_init' => [ qw(models) ],
32 );
33
34 __PACKAGE__->run_before('check_auth');
35
36
37 #
38 # actions
39 #
40
41 sub action_search {
42   my ($self) = @_;
43
44   my $bank_accounts = SL::DB::Manager::BankAccount->get_all_sorted( query => [ obsolete => 0 ] );
45
46   $self->render('bank_transactions/search',
47                  BANK_ACCOUNTS => $bank_accounts);
48 }
49
50 sub action_list_all {
51   my ($self) = @_;
52
53   $self->make_filter_summary;
54   $self->prepare_report;
55
56   $self->report_generator_list_objects(report => $self->{report}, objects => $self->models->get);
57 }
58
59 sub action_list {
60   my ($self) = @_;
61
62   if (!$::form->{filter}{bank_account}) {
63     flash('error', t8('No bank account chosen!'));
64     $self->action_search;
65     return;
66   }
67
68   my $sort_by = $::form->{sort_by} || 'transdate';
69   $sort_by = 'transdate' if $sort_by eq 'proposal';
70   $sort_by .= $::form->{sort_dir} ? ' DESC' : ' ASC';
71
72   my $fromdate = $::locale->parse_date_to_object($::form->{filter}->{fromdate});
73   my $todate   = $::locale->parse_date_to_object($::form->{filter}->{todate});
74   $todate->add( days => 1 ) if $todate;
75
76   my @where = ();
77   push @where, (transdate => { ge => $fromdate }) if ($fromdate);
78   push @where, (transdate => { lt => $todate })   if ($todate);
79   my $bank_account = SL::DB::Manager::BankAccount->find_by( id => $::form->{filter}{bank_account} );
80   # bank_transactions no younger than starting date,
81   # but OPEN invoices to be matched may be from before
82   if ( $bank_account->reconciliation_starting_date ) {
83     push @where, (transdate => { gt => $bank_account->reconciliation_starting_date });
84   };
85
86   my $bank_transactions = SL::DB::Manager::BankTransaction->get_all(where => [ amount => {ne => \'invoice_amount'},
87                                                                                local_bank_account_id => $::form->{filter}{bank_account},
88                                                                                @where ],
89                                                                     with_objects => [ 'local_bank_account', 'currency' ],
90                                                                     sort_by => $sort_by, limit => 10000);
91
92   my $all_open_ar_invoices = SL::DB::Manager::Invoice->get_all(where => [amount => { gt => \'paid' }], with_objects => 'customer');
93   my $all_open_ap_invoices = SL::DB::Manager::PurchaseInvoice->get_all(where => [amount => { gt => \'paid' }], with_objects => 'vendor');
94
95   my @all_open_invoices;
96   # filter out invoices with less than 1 cent outstanding
97   push @all_open_invoices, grep { abs($_->amount - $_->paid) >= 0.01 } @{ $all_open_ar_invoices };
98   push @all_open_invoices, grep { abs($_->amount - $_->paid) >= 0.01 } @{ $all_open_ap_invoices };
99
100   # try to match each bank_transaction with each of the possible open invoices
101   # by awarding points
102
103   foreach my $bt (@{ $bank_transactions }) {
104     next unless $bt->{remote_name};  # bank has no name, usually fees, use create invoice to assign
105
106     $bt->{remote_name} .= $bt->{remote_name_1} if $bt->{remote_name_1};
107
108     # try to match the current $bt to each of the open_invoices, saving the
109     # results of get_agreement_with_invoice in $open_invoice->{agreement} and
110     # $open_invoice->{rule_matches}.
111
112     # The values are overwritten each time a new bt is checked, so at the end
113     # of each bt the likely results are filtered and those values are stored in
114     # the arrays $bt->{proposals} and $bt->{rule_matches}, and the agreement
115     # score is stored in $bt->{agreement}
116
117     foreach my $open_invoice (@all_open_invoices){
118       ($open_invoice->{agreement}, $open_invoice->{rule_matches}) = $bt->get_agreement_with_invoice($open_invoice);
119     };
120
121     $bt->{proposals} = [];
122
123     my $agreement = 15;
124     my $min_agreement = 3; # suggestions must have at least this score
125
126     my $max_agreement = max map { $_->{agreement} } @all_open_invoices;
127
128     # add open_invoices with highest agreement into array $bt->{proposals}
129     if ( $max_agreement >= $min_agreement ) {
130       $bt->{proposals} = [ grep { $_->{agreement} == $max_agreement } @all_open_invoices ];
131       $bt->{agreement} = $max_agreement; #scalar @{ $bt->{proposals} } ? $agreement + 1 : '';
132
133       # store the rule_matches in a separate array, so they can be displayed in template
134       foreach ( @{ $bt->{proposals} } ) {
135         push(@{$bt->{rule_matches}}, $_->{rule_matches});
136       };
137     };
138   }  # finished one bt
139   # finished all bt
140
141   # separate filter for proposals (second tab, agreement >= 5 and exactly one match)
142   # to qualify as a proposal there has to be
143   # * agreement >= 5  TODO: make threshold configurable in configuration
144   # * there must be only one exact match
145   # * depending on whether sales or purchase the amount has to have the correct sign (so Gutschriften don't work?)
146   my $proposal_threshold = 5;
147   my @proposals = grep { $_->{agreement} >= $proposal_threshold
148                          and 1 == scalar @{ $_->{proposals} }
149                          and (@{ $_->{proposals} }[0]->is_sales ? abs(@{ $_->{proposals} }[0]->amount - $_->amount) < 0.01  : abs(@{ $_->{proposals} }[0]->amount + $_->amount) < 0.01) } @{ $bank_transactions };
150
151   # sort bank transaction proposals by quality (score) of proposal
152   $bank_transactions = [ sort { $a->{agreement} <=> $b->{agreement} } @{ $bank_transactions } ] if $::form->{sort_by} eq 'proposal' and $::form->{sort_dir} == 1;
153   $bank_transactions = [ sort { $b->{agreement} <=> $a->{agreement} } @{ $bank_transactions } ] if $::form->{sort_by} eq 'proposal' and $::form->{sort_dir} == 0;
154
155
156   $self->render('bank_transactions/list',
157                 title             => t8('Bank transactions MT940'),
158                 BANK_TRANSACTIONS => $bank_transactions,
159                 PROPOSALS         => \@proposals,
160                 bank_account      => $bank_account );
161 }
162
163 sub action_assign_invoice {
164   my ($self) = @_;
165
166   $self->{transaction} = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
167
168   $self->render('bank_transactions/assign_invoice', { layout  => 0 },
169                 title      => t8('Assign invoice'),);
170 }
171
172 sub action_create_invoice {
173   my ($self) = @_;
174   my %myconfig = %main::myconfig;
175
176   $self->{transaction} = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
177   my $vendor_of_transaction = SL::DB::Manager::Vendor->find_by(account_number => $self->{transaction}->{remote_account_number});
178
179   my $drafts = SL::DB::Manager::Draft->get_all(where => [ module => 'ap'] , with_objects => 'employee');
180
181   my @filtered_drafts;
182
183   foreach my $draft ( @{ $drafts } ) {
184     my $draft_as_object = YAML::Load($draft->form);
185     my $vendor = SL::DB::Manager::Vendor->find_by(id => $draft_as_object->{vendor_id});
186     $draft->{vendor} = $vendor->name;
187     $draft->{vendor_id} = $vendor->id;
188     push @filtered_drafts, $draft;
189   }
190
191   #Filter drafts
192   @filtered_drafts = grep { $_->{vendor_id} == $vendor_of_transaction->id } @filtered_drafts if $vendor_of_transaction;
193
194   my $all_vendors = SL::DB::Manager::Vendor->get_all();
195
196   $self->render('bank_transactions/create_invoice', { layout  => 0 },
197       title      => t8('Create invoice'),
198       DRAFTS     => \@filtered_drafts,
199       vendor_id  => $vendor_of_transaction ? $vendor_of_transaction->id : undef,
200       vendor_name => $vendor_of_transaction ? $vendor_of_transaction->name : undef,
201       ALL_VENDORS => $all_vendors,
202       limit      => $myconfig{vclimit},
203       callback   => $self->url_for(action                => 'list',
204                                    'filter.bank_account' => $::form->{filter}->{bank_account},
205                                    'filter.todate'       => $::form->{filter}->{todate},
206                                    'filter.fromdate'     => $::form->{filter}->{fromdate}),
207       );
208 }
209
210 sub action_ajax_payment_suggestion {
211   my ($self) = @_;
212
213   # based on a BankTransaction ID and a Invoice or PurchaseInvoice ID passed via $::form,
214   # create an HTML blob to be used by the js function add_invoices in templates/webpages/bank_transactions/list.html
215   # and return encoded as JSON
216
217   my $bt = SL::DB::Manager::BankTransaction->find_by( id => $::form->{bt_id} );
218   my $invoice = SL::DB::Manager::Invoice->find_by( id => $::form->{prop_id} );
219   $invoice = SL::DB::Manager::PurchaseInvoice->find_by( id => $::form->{prop_id} ) unless $invoice;
220
221   die unless $bt and $invoice;
222
223   my @select_options = $invoice->get_payment_select_options_for_bank_transaction($::form->{bt_id});
224
225   my $html;
226   $html .= SL::Presenter->input_tag('invoice_ids.' . $::form->{bt_id} . '[]', $::form->{prop_id} , type => 'hidden');
227   $html .= SL::Presenter->escape( $invoice->invnumber );
228   $html .= SL::Presenter->select_tag('invoice_skontos.' . $::form->{bt_id} . '[]', \@select_options,
229                                               value_key => 'payment_type',
230                                               title_key => 'display' ) if @select_options;
231   $html .= '<a href=# onclick="delete_invoice(' . $::form->{bt_id} . ',' . $::form->{prop_id} . ');">x</a>';
232   $html = SL::Presenter->html_tag('div', $html, id => $::form->{bt_id} . '.' . $::form->{prop_id});
233
234   $self->render(\ SL::JSON::to_json( { 'html' => $html } ), { layout => 0, type => 'json', process => 0 });
235 };
236
237 sub action_filter_drafts {
238   my ($self) = @_;
239
240   $self->{transaction} = SL::DB::Manager::BankTransaction->find_by(id => $::form->{bt_id});
241   my $vendor_of_transaction = SL::DB::Manager::Vendor->find_by(account_number => $self->{transaction}->{remote_account_number});
242
243   my $drafts = SL::DB::Manager::Draft->get_all(with_objects => 'employee');
244
245   my @filtered_drafts;
246
247   foreach my $draft ( @{ $drafts } ) {
248     my $draft_as_object = YAML::Load($draft->form);
249     my $vendor = SL::DB::Manager::Vendor->find_by(id => $draft_as_object->{vendor_id});
250     $draft->{vendor} = $vendor->name;
251     $draft->{vendor_id} = $vendor->id;
252     push @filtered_drafts, $draft;
253   }
254
255   my $vendor_name = $::form->{vendor};
256   my $vendor_id = $::form->{vendor_id};
257
258   #Filter drafts
259   @filtered_drafts = grep { $_->{vendor_id} == $vendor_id } @filtered_drafts if $vendor_id;
260   @filtered_drafts = grep { $_->{vendor} =~ /$vendor_name/i } @filtered_drafts if $vendor_name;
261
262   my $output  = $self->render(
263       'bank_transactions/filter_drafts',
264       { output      => 0 },
265       DRAFTS => \@filtered_drafts,
266       );
267
268   my %result = ( count => 0, html => $output );
269
270   $self->render(\to_json(\%result), { type => 'json', process => 0 });
271 }
272
273 sub action_ajax_add_list {
274   my ($self) = @_;
275
276   my @where_sale     = (amount => { ne => \'paid' });
277   my @where_purchase = (amount => { ne => \'paid' });
278
279   if ($::form->{invnumber}) {
280     push @where_sale,     (invnumber => { ilike => '%' . $::form->{invnumber} . '%'});
281     push @where_purchase, (invnumber => { ilike => '%' . $::form->{invnumber} . '%'});
282   }
283
284   if ($::form->{amount}) {
285     push @where_sale,     (amount => $::form->parse_amount(\%::myconfig, $::form->{amount}));
286     push @where_purchase, (amount => $::form->parse_amount(\%::myconfig, $::form->{amount}));
287   }
288
289   if ($::form->{vcnumber}) {
290     push @where_sale,     ('customer.customernumber' => { ilike => '%' . $::form->{vcnumber} . '%'});
291     push @where_purchase, ('vendor.vendornumber'     => { ilike => '%' . $::form->{vcnumber} . '%'});
292   }
293
294   if ($::form->{vcname}) {
295     push @where_sale,     ('customer.name' => { ilike => '%' . $::form->{vcname} . '%'});
296     push @where_purchase, ('vendor.name'   => { ilike => '%' . $::form->{vcname} . '%'});
297   }
298
299   if ($::form->{transdatefrom}) {
300     my $fromdate = $::locale->parse_date_to_object($::form->{transdatefrom});
301     if ( ref($fromdate) eq 'DateTime' ) {
302       push @where_sale,     ('transdate' => { ge => $fromdate});
303       push @where_purchase, ('transdate' => { ge => $fromdate});
304     };
305   }
306
307   if ($::form->{transdateto}) {
308     my $todate = $::locale->parse_date_to_object($::form->{transdateto});
309     if ( ref($todate) eq 'DateTime' ) {
310       $todate->add(days => 1);
311       push @where_sale,     ('transdate' => { lt => $todate});
312       push @where_purchase, ('transdate' => { lt => $todate});
313     };
314   }
315
316   my $all_open_ar_invoices = SL::DB::Manager::Invoice->get_all(where => \@where_sale, with_objects => 'customer');
317   my $all_open_ap_invoices = SL::DB::Manager::PurchaseInvoice->get_all(where => \@where_purchase, with_objects => 'vendor');
318
319   my @all_open_invoices = @{ $all_open_ar_invoices };
320   # add ap invoices, filtering out subcent open amounts
321   push @all_open_invoices, grep { abs($_->amount - $_->paid) >= 0.01 } @{ $all_open_ap_invoices };
322
323   @all_open_invoices = sort { $a->id <=> $b->id } @all_open_invoices;
324
325   my $output  = $self->render(
326       'bank_transactions/add_list',
327       { output      => 0 },
328       INVOICES => \@all_open_invoices,
329       );
330
331   my %result = ( count => 0, html => $output );
332
333   $self->render(\to_json(\%result), { type => 'json', process => 0 });
334 }
335
336 sub action_ajax_accept_invoices {
337   my ($self) = @_;
338
339   my @selected_invoices;
340   foreach my $invoice_id (@{ $::form->{invoice_id} || [] }) {
341     my $invoice_object = SL::DB::Manager::Invoice->find_by(id => $invoice_id);
342     $invoice_object ||= SL::DB::Manager::PurchaseInvoice->find_by(id => $invoice_id);
343
344     push @selected_invoices, $invoice_object;
345   }
346
347   $self->render('bank_transactions/invoices', { layout => 0 },
348                 INVOICES => \@selected_invoices,
349                 bt_id    => $::form->{bt_id} );
350 }
351
352 sub action_save_invoices {
353   my ($self) = @_;
354
355   my $invoice_hash = delete $::form->{invoice_ids}; # each key (the bt line with a bt_id) contains an array of invoice_ids
356   my $skonto_hash  = delete $::form->{invoice_skontos} || {}; # array containing the payment type, could be empty
357
358   # a bank_transaction may be assigned to several invoices, i.e. a customer
359   # might pay several open invoices with one transaction
360
361   while ( my ($bt_id, $invoice_ids) = each(%$invoice_hash) ) {
362     my $bank_transaction = SL::DB::Manager::BankTransaction->find_by(id => $bt_id);
363     my $sign = $bank_transaction->amount < 0 ? -1 : 1;
364     my $amount_of_transaction = $sign * $bank_transaction->amount;
365
366     my @invoices;
367     foreach my $invoice_id (@{ $invoice_ids }) {
368       push @invoices, (SL::DB::Manager::Invoice->find_by(id => $invoice_id) || SL::DB::Manager::PurchaseInvoice->find_by(id => $invoice_id));
369     }
370     @invoices = sort { return 1 if ($a->is_sales and $a->amount > 0);
371                           return 1 if (!$a->is_sales and $a->amount < 0);
372                           return -1; } @invoices                if $bank_transaction->amount > 0;
373     @invoices = sort { return -1 if ($a->is_sales and $a->amount > 0);
374                        return -1 if (!$a->is_sales and $a->amount < 0);
375                        return 1; } @invoices                    if $bank_transaction->amount < 0;
376
377     foreach my $invoice (@invoices) {
378
379       # Check if bank_transaction already has a link to the invoice, may only be linked once per invoice
380       # This might be caused by the user reloading a page and resending the form
381       die t8("Bank transaction with id #1 has already been linked to #2.", $bank_transaction->id, $invoice->displayable_name)
382         if _existing_record_link($bank_transaction, $invoice);
383
384       my $payment_type;
385       if ( defined $skonto_hash->{"$bt_id"} ) {
386         $payment_type = shift(@{ $skonto_hash->{"$bt_id"} });
387       } else {
388         $payment_type = 'without_skonto';
389       };
390       if ($amount_of_transaction == 0) {
391         flash('warning',  $::locale->text('There are invoices which could not be paid by bank transaction #1 (Account number: #2, bank code: #3)!',
392                                             $bank_transaction->purpose,
393                                             $bank_transaction->remote_account_number,
394                                             $bank_transaction->remote_bank_code));
395         last;
396       }
397       # pay invoice or go to the next bank transaction if the amount is not sufficiently high
398       if ($invoice->amount <= $amount_of_transaction) {
399         $invoice->pay_invoice(chart_id     => $bank_transaction->local_bank_account->chart_id,
400                               trans_id     => $invoice->id,
401                               amount       => $invoice->amount,
402                               payment_type => $payment_type,
403                               transdate    => $bank_transaction->transdate->to_kivitendo);
404         if ($invoice->is_sales) {
405           $amount_of_transaction -= $sign * $invoice->amount;
406           $bank_transaction->invoice_amount($bank_transaction->invoice_amount + $invoice->amount);
407         } else {
408           $amount_of_transaction += $sign * $invoice->amount if (!$invoice->is_sales);
409           $bank_transaction->invoice_amount($bank_transaction->invoice_amount - $invoice->amount);
410         }
411       } else {
412         $invoice->pay_invoice(chart_id     => $bank_transaction->local_bank_account->chart_id,
413                               trans_id     => $invoice->id,
414                               amount       => $amount_of_transaction,
415                               payment_type => $payment_type,
416                               transdate    => $bank_transaction->transdate->to_kivitendo);
417         $bank_transaction->invoice_amount($bank_transaction->amount) if $invoice->is_sales;
418         $bank_transaction->invoice_amount($bank_transaction->amount) if !$invoice->is_sales;
419         $amount_of_transaction = 0;
420       }
421
422       # Record a record link from the bank transaction to the invoice
423       my @props = (
424           from_table => 'bank_transactions',
425           from_id    => $bt_id,
426           to_table   => $invoice->is_sales ? 'ar' : 'ap',
427           to_id      => $invoice->id,
428           );
429
430       SL::DB::RecordLink->new(@props)->save;
431     }
432     $bank_transaction->save;
433   }
434
435   $self->action_list();
436 }
437
438 sub action_save_proposals {
439   my ($self) = @_;
440
441   foreach my $bt_id (@{ $::form->{proposal_ids} }) {
442     my $bt = SL::DB::Manager::BankTransaction->find_by(id => $bt_id);
443
444     my $arap = SL::DB::Manager::Invoice->find_by(id => $::form->{"proposed_invoice_$bt_id"});
445     $arap    = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{"proposed_invoice_$bt_id"}) if not defined $arap;
446
447     # check for existing record_link for that $bt and $arap
448     # do this before any changes to $bt are made
449     die t8("Bank transaction with id #1 has already been linked to #2.", $bt->id, $arap->displayable_name)
450       if _existing_record_link($bt, $arap);
451
452     #mark bt as booked
453     $bt->invoice_amount($bt->amount);
454     $bt->save;
455
456     #pay invoice
457     $arap->pay_invoice(chart_id  => $bt->local_bank_account->chart_id,
458                        trans_id  => $arap->id,
459                        amount    => $arap->amount,
460                        transdate => $bt->transdate->to_kivitendo);
461     $arap->save;
462
463     #create record link
464     my @props = (
465         from_table => 'bank_transactions',
466         from_id    => $bt_id,
467         to_table   => $arap->is_sales ? 'ar' : 'ap',
468         to_id      => $arap->id,
469         );
470
471     SL::DB::RecordLink->new(@props)->save;
472   }
473
474   flash('ok', t8('#1 proposal(s) saved.', scalar @{ $::form->{proposal_ids} }));
475
476   $self->action_list();
477 }
478
479 #
480 # filters
481 #
482
483 sub check_auth {
484   $::auth->assert('bank_transaction');
485 }
486
487 #
488 # helpers
489 #
490
491 sub make_filter_summary {
492   my ($self) = @_;
493
494   my $filter = $::form->{filter} || {};
495   my @filter_strings;
496
497   my @filters = (
498     [ $filter->{"transdate:date::ge"},  $::locale->text('Transdate')  . " " . $::locale->text('From Date') ],
499     [ $filter->{"transdate:date::le"},  $::locale->text('Transdate')  . " " . $::locale->text('To Date')   ],
500     [ $filter->{"valutadate:date::ge"}, $::locale->text('Valutadate') . " " . $::locale->text('From Date') ],
501     [ $filter->{"valutadate:date::le"}, $::locale->text('Valutadate') . " " . $::locale->text('To Date')   ],
502     [ $filter->{"amount:number"},       $::locale->text('Amount')                                          ],
503     [ $filter->{"bank_account_id:integer"}, $::locale->text('Local bank account')                          ],
504   );
505
506   for (@filters) {
507     push @filter_strings, "$_->[1]: $_->[0]" if $_->[0];
508   }
509
510   $self->{filter_summary} = join ', ', @filter_strings;
511 }
512
513 sub prepare_report {
514   my ($self)      = @_;
515
516   my $callback    = $self->models->get_callback;
517
518   my $report      = SL::ReportGenerator->new(\%::myconfig, $::form);
519   $self->{report} = $report;
520
521   my @columns     = qw(local_bank_name transdate valudate remote_name remote_account_number remote_bank_code amount invoice_amount invoices currency purpose local_account_number local_bank_code id);
522   my @sortable    = qw(local_bank_name transdate valudate remote_name remote_account_number remote_bank_code amount                                  purpose local_account_number local_bank_code);
523
524   my %column_defs = (
525     transdate             => { sub => sub { $_[0]->transdate_as_date } },
526     valutadate            => { sub => sub { $_[0]->valutadate_as_date } },
527     remote_name           => { },
528     remote_account_number => { },
529     remote_bank_code      => { },
530     amount                => { sub => sub { $_[0]->amount_as_number },
531                                align => 'right' },
532     invoice_amount        => { sub => sub { $_[0]->invoice_amount_as_number },
533                                align => 'right' },
534     invoices              => { sub => sub { $_[0]->linked_invoices } },
535     currency              => { sub => sub { $_[0]->currency->name } },
536     purpose               => { },
537     local_account_number  => { sub => sub { $_[0]->local_bank_account->account_number } },
538     local_bank_code       => { sub => sub { $_[0]->local_bank_account->bank_code } },
539     local_bank_name       => { sub => sub { $_[0]->local_bank_account->name } },
540     id                    => {},
541   );
542
543   map { $column_defs{$_}->{text} ||= $::locale->text( $self->models->get_sort_spec->{$_}->{title} ) } keys %column_defs;
544
545   $report->set_options(
546     std_column_visibility => 1,
547     controller_class      => 'BankTransaction',
548     output_format         => 'HTML',
549     top_info_text         => $::locale->text('Bank transactions'),
550     title                 => $::locale->text('Bank transactions'),
551     allow_pdf_export      => 1,
552     allow_csv_export      => 1,
553   );
554   $report->set_columns(%column_defs);
555   $report->set_column_order(@columns);
556   $report->set_export_options(qw(list_all filter));
557   $report->set_options_from_form;
558   $self->models->disable_plugin('paginated') if $report->{options}{output_format} =~ /^(pdf|csv)$/i;
559   $self->models->set_report_generator_sort_options(report => $report, sortable_columns => \@sortable);
560
561   my $bank_accounts = SL::DB::Manager::BankAccount->get_all_sorted();
562
563   $report->set_options(
564     raw_top_info_text     => $self->render('bank_transactions/report_top',    { output => 0 }, BANK_ACCOUNTS => $bank_accounts),
565     raw_bottom_info_text  => $self->render('bank_transactions/report_bottom', { output => 0 }),
566   );
567 }
568
569 sub _existing_record_link {
570   my ($bt, $invoice) = @_;
571
572   # check whether a record link from banktransaction $bt already exists to
573   # invoice $invoice, returns 1 if that is the case
574
575   die unless $bt->isa("SL::DB::BankTransaction") && ( $invoice->isa("SL::DB::Invoice") || $invoice->isa("SL::DB::PurchaseInvoice") );
576
577   my $linked_record_to_table = $invoice->is_sales ? 'Invoice' : 'PurchaseInvoice';
578   my $linked_records = $bt->linked_records( direction => 'to', to => $linked_record_to_table, query => [ id => $invoice->id ]  );
579
580   return @$linked_records ? 1 : 0;
581 };
582
583
584 sub init_models {
585   my ($self) = @_;
586
587   SL::Controller::Helper::GetModels->new(
588     controller => $self,
589     sorted => {
590       _default => {
591         by    => 'transdate',
592         dir   => 0,   # 1 = ASC, 0 = DESC : default sort is newest at top
593       },
594       transdate             => t8('Transdate'),
595       remote_name           => t8('Remote name'),
596       amount                => t8('Amount'),
597       invoice_amount        => t8('Assigned'),
598       invoices              => t8('Linked invoices'),
599       valutadate            => t8('Valutadate'),
600       remote_account_number => t8('Remote account number'),
601       remote_bank_code      => t8('Remote bank code'),
602       currency              => t8('Currency'),
603       purpose               => t8('Purpose'),
604       local_account_number  => t8('Local account number'),
605       local_bank_code       => t8('Local bank code'),
606       local_bank_name       => t8('Bank account'),
607     },
608     with_objects => [ 'local_bank_account', 'currency' ],
609   );
610 }
611
612 1;