BankTransaction Code cleaning
[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) = @_;
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     invnumber_in_purpose        => 2,
73     own_invnumber_in_purpose    => 5,
74     # overpayment                 => -1, # either other invoice is more likely, or several invoices paid at once
75     payment_before_invoice      => -2,
76     payment_within_30_days      => 1,
77     remote_account_number       => 3,
78     skonto_exact_amount         => 5,
79     wrong_sign                  => -1,
80     sepa_export_item            => 5,
81     batch_sepa_transaction      => 20,
82   );
83
84   my ($agreement,$rule_matches);
85
86   if ( $self->is_batch_transaction && $self->{sepa_export_ok}) {
87     $agreement += $points{batch_sepa_transaction};
88     $rule_matches .= 'batch_sepa_transaction(' . $points{'batch_sepa_transaction'} . ') ';
89   }
90
91   # compare banking arrangements
92   my ($iban, $bank_code, $account_number);
93   $bank_code      = $invoice->customer->bank_code      if $invoice->is_sales;
94   $account_number = $invoice->customer->account_number if $invoice->is_sales;
95   $iban           = $invoice->customer->iban           if $invoice->is_sales;
96   $bank_code      = $invoice->vendor->bank_code        if ! $invoice->is_sales;
97   $iban           = $invoice->vendor->iban             if ! $invoice->is_sales;
98   $account_number = $invoice->vendor->account_number   if ! $invoice->is_sales;
99   if ( $bank_code eq $self->remote_bank_code && $account_number eq $self->remote_account_number ) {
100     $agreement += $points{remote_account_number};
101     $rule_matches .= 'remote_account_number(' . $points{'remote_account_number'} . ') ';
102   }
103   if ( $iban eq $self->remote_account_number ) {
104     $agreement += $points{remote_account_number};
105     $rule_matches .= 'remote_account_number(' . $points{'remote_account_number'} . ') ';
106   }
107
108   my $datediff = $self->transdate->{utc_rd_days} - $invoice->transdate->{utc_rd_days};
109   $invoice->{datediff} = $datediff;
110
111   # compare amount
112   if (abs(abs($invoice->amount) - abs($self->amount)) < 0.01) {
113     $agreement += $points{exact_amount};
114     $rule_matches .= 'exact_amount(' . $points{'exact_amount'} . ') ';
115   }
116
117   # compare open amount, preventing double points when open amount = invoice amount
118   if ( $invoice->amount != $invoice->open_amount && abs(abs($invoice->open_amount) - abs($self->amount)) < 0.01) {
119     $agreement += $points{exact_open_amount};
120     $rule_matches .= 'exact_open_amount(' . $points{'exact_open_amount'} . ') ';
121   }
122
123   if ( $invoice->skonto_date && abs(abs($invoice->amount_less_skonto) - abs($self->amount)) < 0.01) {
124     $agreement += $points{skonto_exact_amount};
125     $rule_matches .= 'skonto_exact_amount(' . $points{'skonto_exact_amount'} . ') ';
126     $invoice->{skonto_type} = 'with_skonto_pt';
127   }
128
129   #search invoice number in purpose
130   my $invnumber = $invoice->invnumber;
131   # invnumber has to have at least 3 characters
132   my $squashed_purpose = $self->purpose;
133   $squashed_purpose =~ s/ //g;
134   if (length($invnumber) > 4 && $squashed_purpose =~ /$invnumber/ && $invoice->is_sales){
135     $agreement += $points{own_invnumber_in_purpose};
136     $rule_matches .= 'own_invnumber_in_purpose(' . $points{'own_invnumber_in_purpose'} . ') ';
137   } elsif (length($invnumber) > 3 && $squashed_purpose =~ /$invnumber/ ) {
138     $agreement += $points{invnumber_in_purpose};
139     $rule_matches .= 'invnumber_in_purpose(' . $points{'invnumber_in_purpose'} . ') ';
140   }
141
142   #check sign
143   if ( $invoice->is_sales && $self->amount < 0 ) {
144     $agreement += $points{wrong_sign};
145     $rule_matches .= 'wrong_sign(' . $points{'wrong_sign'} . ') ';
146   }
147   if ( ! $invoice->is_sales && $self->amount > 0 ) {
148     $agreement += $points{wrong_sign};
149     $rule_matches .= 'wrong_sign(' . $points{'wrong_sign'} . ') ';
150   }
151
152   # search customer/vendor number in purpose
153   my $cvnumber;
154   $cvnumber = $invoice->customer->customernumber if $invoice->is_sales;
155   $cvnumber = $invoice->vendor->vendornumber     if ! $invoice->is_sales;
156   if ( $cvnumber && $self->purpose =~ /\b$cvnumber\b/i ) {
157     $agreement += $points{cust_vend_number_in_purpose};
158     $rule_matches .= 'cust_vend_number_in_purpose(' . $points{'cust_vend_number_in_purpose'} . ') ';
159   }
160
161   # search for customer/vendor name in purpose (may contain GMBH, CO KG, ...)
162   my $cvname;
163   $cvname = $invoice->customer->name if $invoice->is_sales;
164   $cvname = $invoice->vendor->name   if ! $invoice->is_sales;
165   if ( $cvname && $self->purpose =~ /\b\Q$cvname\E\b/i ) {
166     $agreement += $points{cust_vend_name_in_purpose};
167     $rule_matches .= 'cust_vend_name_in_purpose(' . $points{'cust_vend_name_in_purpose'} . ') ';
168   }
169
170   # compare depositorname, don't try to match empty depositors
171   my $depositorname;
172   $depositorname = $invoice->customer->depositor if $invoice->is_sales;
173   $depositorname = $invoice->vendor->depositor   if ! $invoice->is_sales;
174   if ( $depositorname && $self->remote_name =~ /$depositorname/ ) {
175     $agreement += $points{depositor_matches};
176     $rule_matches .= 'depositor_matches(' . $points{'depositor_matches'} . ') ';
177   }
178
179   #Check if words in remote_name appear in cvname
180   my $check_string_points = _check_string($self->remote_name,$cvname);
181   if ( $check_string_points ) {
182     $agreement += $check_string_points;
183     $rule_matches .= 'remote_name(' . $check_string_points . ') ';
184   }
185
186   # transdate prefilter: compare transdate of bank_transaction with transdate of invoice
187   if ( $datediff < -5 ) { # this might conflict with advance payments
188     $agreement += $points{payment_before_invoice};
189     $rule_matches .= 'payment_before_invoice(' . $points{'payment_before_invoice'} . ') ';
190   }
191   if ( $datediff < 30 ) {
192     $agreement += $points{payment_within_30_days};
193     $rule_matches .= 'payment_within_30_days(' . $points{'payment_within_30_days'} . ') ';
194   }
195
196   # only if we already have a good agreement, let date further change value of agreement.
197   # this is so that if there are several plausible open invoices which are all equal
198   # (rent jan, rent feb...) the one with the best date match is chosen over
199   # the others
200
201   # another way around this is to just pre-filter by periods instead of matching everything
202   if ( $agreement > 5 ) {
203     if ( $datediff == 0 ) {
204       $agreement += $points{datebonus0};
205       $rule_matches .= 'datebonus0(' . $points{'datebonus0'} . ') ';
206     } elsif  ( $datediff > 0 and $datediff <= 14 ) {
207       $agreement += $points{datebonus14};
208       $rule_matches .= 'datebonus14(' . $points{'datebonus14'} . ') ';
209     } elsif  ( $datediff >14 and $datediff < 35) {
210       $agreement += $points{datebonus35};
211       $rule_matches .= 'datebonus35(' . $points{'datebonus35'} . ') ';
212     } elsif  ( $datediff >34 and $datediff < 120) {
213       $agreement += $points{datebonus120};
214       $rule_matches .= 'datebonus120(' . $points{'datebonus120'} . ') ';
215     } elsif  ( $datediff < 0 ) {
216       $agreement += $points{datebonus_negative};
217       $rule_matches .= 'datebonus_negative(' . $points{'datebonus_negative'} . ') ';
218     } else {
219       # e.g. datediff > 120
220     }
221   }
222
223   # if there is exactly one non-executed sepa_export_item for the invoice
224   if ( my $seis = $invoice->find_sepa_export_items({ executed => 0 }) ) {
225     if (scalar @$seis == 1) {
226       my $sei = $seis->[0];
227
228       # test for amount and id matching only, sepa transfer date and bank
229       # transaction date needn't match
230       if (abs($self->amount) == ($sei->amount) && $invoice->id == $sei->arap_id) {
231         $agreement    += $points{sepa_export_item};
232         $rule_matches .= 'sepa_export_item(' . $points{'sepa_export_item'} . ') ';
233       }
234     } else {
235       # zero or more than one sepa_export_item, do nothing for this invoice
236       # zero: do nothing, no sepa_export_item exists, no match
237       # more than one: does this ever apply? Currently you can't create sepa
238       # exports for invoices that already have a non-executed sepa_export
239       # TODO: Catch the more than one case. User is allowed to split
240       # payments for one invoice item in one sepa export.
241     }
242   }
243
244   return ($agreement,$rule_matches);
245 };
246
247 sub _check_string {
248     my $bankstring = shift;
249     my $namestring = shift;
250     return 0 unless $bankstring and $namestring;
251
252     my @bankwords = grep(/^\w+$/, split(/\b/,$bankstring));
253
254     my $match = 0;
255     foreach my $bankword ( @bankwords ) {
256         # only try to match strings with more than 2 characters
257         next unless length($bankword)>2;
258         if ( $namestring =~ /\b$bankword\b/i ) {
259             $match++;
260         };
261     };
262     return $match;
263 };
264
265 1;
266
267 __END__
268
269 =pod
270
271 =head1 NAME
272
273 SL::DB::BankTransaction
274
275 =head1 FUNCTIONS
276
277 =over 4
278
279 =item C<get_agreement_with_invoice $invoice>
280
281 Using a point system this function checks whether the bank transaction matches
282 an invoices, using a variety of tests, such as
283
284 =over 2
285
286 =item * amount
287
288 =item * amount_less_skonto
289
290 =item * payment date
291
292 =item * invoice number in purpose
293
294 =item * customer or vendor name in purpose
295
296 =item * account number matches account number of customer or vendor
297
298 =back
299
300 The total number of points, and the rules that matched, are returned.
301
302 Example:
303   my $bt      = SL::DB::Manager::BankTransaction->find_by(id => 522);
304   my $invoice = SL::DB::Manager::Invoice->find_by(invnumber => '198');
305   my ($agreement,rule_matches) = $bt->get_agreement_with_invoice($invoice);
306
307 =back
308
309 =head1 AUTHOR
310
311 G. Richardson E<lt>grichardson@kivitendo-premium.de<gt>
312
313 =cut