Bankimport: Rundungsproblem beim Vergleich Rechnungsbetrag - Kontobetrag
[kivitendo-erp.git] / SL / DB / BankTransaction.pm
1 # This file has been auto-generated only because it didn't exist.
2 # Feel free to modify it at will; it will not be overwritten automatically.
3
4 package SL::DB::BankTransaction;
5
6 use strict;
7
8 use SL::DB::MetaSetup::BankTransaction;
9 use SL::DB::Manager::BankTransaction;
10 use SL::DB::Helper::LinkedRecords;
11 use Carp;
12
13 require SL::DB::Invoice;
14 require SL::DB::PurchaseInvoice;
15
16 __PACKAGE__->meta->initialize;
17
18
19 # Creates get_all, get_all_count, get_all_iterator, delete_all and update_all.
20 #__PACKAGE__->meta->make_manager_class;
21
22 sub compare_to {
23   my ($self, $other) = @_;
24
25   return  1 if  $self->transdate && !$other->transdate;
26   return -1 if !$self->transdate &&  $other->transdate;
27
28   my $result = 0;
29   $result    = $self->transdate <=> $other->transdate if $self->transdate;
30   return $result || ($self->id <=> $other->id);
31 }
32
33 sub linked_invoices {
34   my ($self) = @_;
35
36   #my $record_links = $self->linked_records(direction => 'both');
37
38   my @linked_invoices;
39
40   my $record_links = SL::DB::Manager::RecordLink->get_all(where => [ from_table => 'bank_transactions', from_id => $self->id ]);
41
42   foreach my $record_link (@{ $record_links }) {
43     push @linked_invoices, SL::DB::Manager::Invoice->find_by(id => $record_link->to_id)->invnumber         if $record_link->to_table eq 'ar';
44     push @linked_invoices, SL::DB::Manager::PurchaseInvoice->find_by(id => $record_link->to_id)->invnumber if $record_link->to_table eq 'ap';
45   }
46
47   return [ @linked_invoices ];
48 }
49
50 sub is_batch_transaction {
51   ($_[0]->transaction_code // '') eq "191";
52 }
53
54
55 sub get_agreement_with_invoice {
56   my ($self, $invoice, %params) = @_;
57
58   carp "get_agreement_with_invoice needs an invoice object as its first argument"
59     unless ref($invoice) eq 'SL::DB::Invoice' or ref($invoice) eq 'SL::DB::PurchaseInvoice';
60
61   my %points = (
62     cust_vend_name_in_purpose   => 1,
63     cust_vend_number_in_purpose => 1,
64     datebonus0                  => 3,
65     datebonus14                 => 2,
66     datebonus35                 => 1,
67     datebonus120                => 0,
68     datebonus_negative          => -1,
69     depositor_matches           => 2,
70     exact_amount                => 4,
71     exact_open_amount           => 4,
72     invoice_in_purpose          => 2,
73     own_invoice_in_purpose      => 5,
74     invnumber_in_purpose        => 1,
75     own_invnumber_in_purpose    => 4,
76     # overpayment                 => -1, # either other invoice is more likely, or several invoices paid at once
77     payment_before_invoice      => -2,
78     payment_within_30_days      => 1,
79     remote_account_number       => 3,
80     skonto_exact_amount         => 5,
81     wrong_sign                  => -1,
82     sepa_export_item            => 5,
83     batch_sepa_transaction      => 20,
84   );
85
86   my ($agreement,$rule_matches);
87
88   if ( $self->is_batch_transaction && $self->{sepa_export_ok}) {
89     $agreement += $points{batch_sepa_transaction};
90     $rule_matches .= 'batch_sepa_transaction(' . $points{'batch_sepa_transaction'} . ') ';
91   }
92
93   # compare banking arrangements
94   my ($iban, $bank_code, $account_number);
95   $bank_code      = $invoice->customer->bank_code      if $invoice->is_sales;
96   $account_number = $invoice->customer->account_number if $invoice->is_sales;
97   $iban           = $invoice->customer->iban           if $invoice->is_sales;
98   $bank_code      = $invoice->vendor->bank_code        if ! $invoice->is_sales;
99   $iban           = $invoice->vendor->iban             if ! $invoice->is_sales;
100   $account_number = $invoice->vendor->account_number   if ! $invoice->is_sales;
101   if ( $bank_code eq $self->remote_bank_code && $account_number eq $self->remote_account_number ) {
102     $agreement += $points{remote_account_number};
103     $rule_matches .= 'remote_account_number(' . $points{'remote_account_number'} . ') ';
104   }
105   if ( $iban eq $self->remote_account_number ) {
106     $agreement += $points{remote_account_number};
107     $rule_matches .= 'remote_account_number(' . $points{'remote_account_number'} . ') ';
108   }
109
110   my $datediff = $self->transdate->{utc_rd_days} - $invoice->transdate->{utc_rd_days};
111   $invoice->{datediff} = $datediff;
112
113   # compare amount
114   if (abs(abs($invoice->amount) - abs($self->amount)) < 0.01 &&
115         $::form->format_amount(\%::myconfig,abs($invoice->amount),2) eq
116         $::form->format_amount(\%::myconfig,abs($self->amount),2)
117       ) {
118     $agreement += $points{exact_amount};
119     $rule_matches .= 'exact_amount(' . $points{'exact_amount'} . ') ';
120   }
121
122   # compare open amount, preventing double points when open amount = invoice amount
123   if ( $invoice->amount != $invoice->open_amount && abs(abs($invoice->open_amount) - abs($self->amount)) < 0.01 &&
124          $::form->format_amount(\%::myconfig,abs($invoice->amount_less_skonto),2) eq
125          $::form->format_amount(\%::myconfig,abs($self->amount),2)
126        ) {
127     $agreement += $points{exact_open_amount};
128     $rule_matches .= 'exact_open_amount(' . $points{'exact_open_amount'} . ') ';
129   }
130
131   if ( $invoice->skonto_date && abs(abs($invoice->amount_less_skonto) - abs($self->amount)) < 0.01 &&
132          $::form->format_amount(\%::myconfig,abs($invoice->amount_less_skonto),2) eq
133          $::form->format_amount(\%::myconfig,abs($self->amount),2)
134        ) {
135     $agreement += $points{skonto_exact_amount};
136     $rule_matches .= 'skonto_exact_amount(' . $points{'skonto_exact_amount'} . ') ';
137     $invoice->{skonto_type} = 'with_skonto_pt';
138   }
139
140   #search invoice number in purpose
141   my $invnumber = $invoice->invnumber;
142   # invnumber has to have at least 3 characters
143   my $squashed_purpose = $self->purpose;
144   $squashed_purpose =~ s/ //g;
145   if (length($invnumber) > 4 && $squashed_purpose =~ /$invnumber/ && $invoice->is_sales){
146     $agreement      += $points{own_invoice_in_purpose};
147     $rule_matches   .= 'own_invoice_in_purpose(' . $points{'own_invoice_in_purpose'} . ') ';
148   } elsif (length($invnumber) > 3 && $squashed_purpose =~ /$invnumber/ ) {
149     $agreement      += $points{invoice_in_purpose};
150     $rule_matches   .= 'invoice_in_purpose(' . $points{'invoice_in_purpose'} . ') ';
151   } else {
152     # only check number part of invoice number
153     $invnumber      =~ s/[A-Za-z_]+//g;
154     if (length($invnumber) > 4 && $squashed_purpose =~ /$invnumber/ && $invoice->is_sales){
155       $agreement    += $points{own_invnumber_in_purpose};
156       $rule_matches .= 'own_invnumber_in_purpose(' . $points{'own_invnumber_in_purpose'} . ') ';
157     } elsif (length($invnumber) > 3 && $squashed_purpose =~ /$invnumber/ ) {
158       $agreement    += $points{invnumber_in_purpose};
159       $rule_matches .= 'invnumber_in_purpose(' . $points{'invnumber_in_purpose'} . ') ';
160     }
161   }
162
163   #check sign
164   if ( $invoice->is_sales && $self->amount < 0 ) {
165     $agreement += $points{wrong_sign};
166     $rule_matches .= 'wrong_sign(' . $points{'wrong_sign'} . ') ';
167   }
168   if ( ! $invoice->is_sales && $self->amount > 0 ) {
169     $agreement += $points{wrong_sign};
170     $rule_matches .= 'wrong_sign(' . $points{'wrong_sign'} . ') ';
171   }
172
173   # search customer/vendor number in purpose
174   my $cvnumber;
175   $cvnumber = $invoice->customer->customernumber if $invoice->is_sales;
176   $cvnumber = $invoice->vendor->vendornumber     if ! $invoice->is_sales;
177   if ( $cvnumber && $self->purpose =~ /\b$cvnumber\b/i ) {
178     $agreement += $points{cust_vend_number_in_purpose};
179     $rule_matches .= 'cust_vend_number_in_purpose(' . $points{'cust_vend_number_in_purpose'} . ') ';
180   }
181
182   # search for customer/vendor name in purpose (may contain GMBH, CO KG, ...)
183   my $cvname;
184   $cvname = $invoice->customer->name if $invoice->is_sales;
185   $cvname = $invoice->vendor->name   if ! $invoice->is_sales;
186   if ( $cvname && $self->purpose =~ /\b\Q$cvname\E\b/i ) {
187     $agreement += $points{cust_vend_name_in_purpose};
188     $rule_matches .= 'cust_vend_name_in_purpose(' . $points{'cust_vend_name_in_purpose'} . ') ';
189   }
190
191   # compare depositorname, don't try to match empty depositors
192   my $depositorname;
193   $depositorname = $invoice->customer->depositor if $invoice->is_sales;
194   $depositorname = $invoice->vendor->depositor   if ! $invoice->is_sales;
195   if ( $depositorname && $self->remote_name =~ /$depositorname/ ) {
196     $agreement += $points{depositor_matches};
197     $rule_matches .= 'depositor_matches(' . $points{'depositor_matches'} . ') ';
198   }
199
200   #Check if words in remote_name appear in cvname
201   my $check_string_points = _check_string($self->remote_name,$cvname);
202   if ( $check_string_points ) {
203     $agreement += $check_string_points;
204     $rule_matches .= 'remote_name(' . $check_string_points . ') ';
205   }
206
207   # transdate prefilter: compare transdate of bank_transaction with transdate of invoice
208   if ( $datediff < -5 ) { # this might conflict with advance payments
209     $agreement += $points{payment_before_invoice};
210     $rule_matches .= 'payment_before_invoice(' . $points{'payment_before_invoice'} . ') ';
211   }
212   if ( $datediff < 30 ) {
213     $agreement += $points{payment_within_30_days};
214     $rule_matches .= 'payment_within_30_days(' . $points{'payment_within_30_days'} . ') ';
215   }
216
217   # only if we already have a good agreement, let date further change value of agreement.
218   # this is so that if there are several plausible open invoices which are all equal
219   # (rent jan, rent feb...) the one with the best date match is chosen over
220   # the others
221
222   # another way around this is to just pre-filter by periods instead of matching everything
223   if ( $agreement > 5 ) {
224     if ( $datediff == 0 ) {
225       $agreement += $points{datebonus0};
226       $rule_matches .= 'datebonus0(' . $points{'datebonus0'} . ') ';
227     } elsif  ( $datediff > 0 and $datediff <= 14 ) {
228       $agreement += $points{datebonus14};
229       $rule_matches .= 'datebonus14(' . $points{'datebonus14'} . ') ';
230     } elsif  ( $datediff >14 and $datediff < 35) {
231       $agreement += $points{datebonus35};
232       $rule_matches .= 'datebonus35(' . $points{'datebonus35'} . ') ';
233     } elsif  ( $datediff >34 and $datediff < 120) {
234       $agreement += $points{datebonus120};
235       $rule_matches .= 'datebonus120(' . $points{'datebonus120'} . ') ';
236     } elsif  ( $datediff < 0 ) {
237       $agreement += $points{datebonus_negative};
238       $rule_matches .= 'datebonus_negative(' . $points{'datebonus_negative'} . ') ';
239     } else {
240       # e.g. datediff > 120
241     }
242   }
243
244   # if there is exactly one non-executed sepa_export_item for the invoice
245   my $seis = $params{sepa_export_items}
246            ? [ grep { $invoice->id == ($invoice->is_sales ? $_->ar_id : $_->ap_id) } @{ $params{sepa_export_items} } ]
247            : $invoice->find_sepa_export_items({ executed => 0 });
248   if ($seis) {
249     if (scalar @$seis == 1) {
250       my $sei = $seis->[0];
251
252       # test for amount and id matching only, sepa transfer date and bank
253       # transaction date needn't match
254       if (abs($self->amount) == ($sei->amount) && $invoice->id == $sei->arap_id) {
255         $agreement    += $points{sepa_export_item};
256         $rule_matches .= 'sepa_export_item(' . $points{'sepa_export_item'} . ') ';
257       }
258     } else {
259       # zero or more than one sepa_export_item, do nothing for this invoice
260       # zero: do nothing, no sepa_export_item exists, no match
261       # more than one: does this ever apply? Currently you can't create sepa
262       # exports for invoices that already have a non-executed sepa_export
263       # TODO: Catch the more than one case. User is allowed to split
264       # payments for one invoice item in one sepa export.
265     }
266   }
267
268   return ($agreement,$rule_matches);
269 };
270
271 sub _check_string {
272     my $bankstring = shift;
273     my $namestring = shift;
274     return 0 unless $bankstring and $namestring;
275
276     my @bankwords = grep(/^\w+$/, split(/\b/,$bankstring));
277
278     my $match = 0;
279     foreach my $bankword ( @bankwords ) {
280         # only try to match strings with more than 2 characters
281         next unless length($bankword)>2;
282         if ( $namestring =~ /\b$bankword\b/i ) {
283             $match++;
284         };
285     };
286     return $match;
287 };
288
289 1;
290
291 __END__
292
293 =pod
294
295 =head1 NAME
296
297 SL::DB::BankTransaction
298
299 =head1 FUNCTIONS
300
301 =over 4
302
303 =item C<get_agreement_with_invoice $invoice>
304
305 Using a point system this function checks whether the bank transaction matches
306 an invoices, using a variety of tests, such as
307
308 =over 2
309
310 =item * amount
311
312 =item * amount_less_skonto
313
314 =item * payment date
315
316 =item * invoice number in purpose
317
318 =item * customer or vendor name in purpose
319
320 =item * account number matches account number of customer or vendor
321
322 =back
323
324 The total number of points, and the rules that matched, are returned.
325
326 Example:
327   my $bt      = SL::DB::Manager::BankTransaction->find_by(id => 522);
328   my $invoice = SL::DB::Manager::Invoice->find_by(invnumber => '198');
329   my ($agreement,rule_matches) = $bt->get_agreement_with_invoice($invoice);
330
331 =back
332
333 =head1 AUTHOR
334
335 G. Richardson E<lt>grichardson@kivitendo-premium.de<gt>
336
337 =cut