Bankimport: Behandlung von Sammelüberweisungen
[kivitendo-erp.git] / SL / SEPA.pm
1 package SL::SEPA;
2
3 use strict;
4
5 use POSIX qw(strftime);
6
7 use Data::Dumper;
8 use SL::DBUtils;
9 use SL::DB::Invoice;
10 use SL::DB::PurchaseInvoice;
11 use SL::DB;
12 use SL::Locale::String qw(t8);
13 use DateTime;
14
15 sub retrieve_open_invoices {
16   $main::lxdebug->enter_sub();
17
18   my $self     = shift;
19   my %params   = @_;
20
21   my $myconfig = \%main::myconfig;
22   my $form     = $main::form;
23
24   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
25   my $arap     = $params{vc} eq 'customer' ? 'ar'       : 'ap';
26   my $vc       = $params{vc} eq 'customer' ? 'customer' : 'vendor';
27
28   my $mandate  = $params{vc} eq 'customer' ? " AND COALESCE(vc.mandator_id, '') <> '' AND vc.mandate_date_of_signature IS NOT NULL " : '';
29
30   # in query: for customers, use payment terms from invoice, for vendors use
31   # payment terms from vendor settings
32   # currently there is no option in vendor invoices for setting payment terms,
33   # so the vendor settings are always used
34
35   my $payment_term_type = $params{vc} eq 'customer' ? "${arap}" : 'vc';
36
37   # open_amount is not the current open amount according to bookkeeping, but
38   # the open amount minus the SEPA transfer amounts that haven't been closed yet
39   my $query =
40     qq|
41        SELECT ${arap}.id, ${arap}.invnumber, ${arap}.transdate, ${arap}.${vc}_id as vc_id, ${arap}.amount AS invoice_amount, ${arap}.invoice,
42          (${arap}.transdate + pt.terms_skonto) as skonto_date, (pt.percent_skonto * 100) as percent_skonto,
43          (${arap}.amount - (${arap}.amount * pt.percent_skonto)) as amount_less_skonto,
44          (${arap}.amount * pt.percent_skonto) as skonto_amount,
45          vc.name AS vcname, vc.language_id, ${arap}.duedate as duedate, ${arap}.direct_debit,
46
47          COALESCE(vc.iban, '') <> '' AND COALESCE(vc.bic, '') <> '' ${mandate} AS vc_bank_info_ok,
48
49          ${arap}.amount - ${arap}.paid - COALESCE(open_transfers.amount, 0) AS open_amount,
50          COALESCE(open_transfers.amount, 0) AS transfer_amount,
51          pt.description as pt_description
52
53        FROM ${arap}
54        LEFT JOIN ${vc} vc ON (${arap}.${vc}_id = vc.id)
55        LEFT JOIN (SELECT sei.${arap}_id, SUM(sei.amount) + SUM(COALESCE(sei.skonto_amount,0)) AS amount
56                   FROM sepa_export_items sei
57                   LEFT JOIN sepa_export se ON (sei.sepa_export_id = se.id)
58                   WHERE NOT se.closed
59                     AND (se.vc = '${vc}')
60                   GROUP BY sei.${arap}_id)
61          AS open_transfers ON (${arap}.id = open_transfers.${arap}_id)
62
63        LEFT JOIN payment_terms pt ON (${payment_term_type}.payment_id = pt.id)
64
65        WHERE ${arap}.amount > (COALESCE(open_transfers.amount, 0) + ${arap}.paid)
66
67        ORDER BY lower(vc.name) ASC, lower(${arap}.invnumber) ASC
68 |;
69     #  $main::lxdebug->message(LXDebug->DEBUG2(),"sepa add query:".$query);
70
71   my $results = selectall_hashref_query($form, $dbh, $query);
72
73   # add some more data to $results:
74   # create drop-down data for payment types and suggest amount to be paid according
75   # to open amount or skonto
76
77   foreach my $result ( @$results ) {
78     my $invoice = $vc eq 'customer' ? SL::DB::Manager::Invoice->find_by(         id => $result->{id} )
79                                     : SL::DB::Manager::PurchaseInvoice->find_by( id => $result->{id} );
80
81     $invoice->get_payment_suggestions(sepa => 1); # consider amounts of open entries in sepa_export_items
82     $result->{skonto_amount}             = $invoice->skonto_amount;
83     $result->{within_skonto_period}      = $invoice->within_skonto_period;
84     $result->{invoice_amount_suggestion} = $invoice->{invoice_amount_suggestion};
85     $result->{payment_select_options}    = $invoice->{payment_select_options};
86   };
87
88   $main::lxdebug->leave_sub();
89
90   return $results;
91 }
92
93 sub create_export {
94   my ($self, %params) = @_;
95   $main::lxdebug->enter_sub();
96
97   my $rc = SL::DB->client->with_transaction(\&_create_export, $self, %params);
98
99   $::lxdebug->leave_sub;
100   return $rc;
101 }
102
103 sub _create_export {
104   my $self     = shift;
105   my %params   = @_;
106
107   Common::check_params(\%params, qw(employee bank_transfers vc));
108
109   my $myconfig = \%main::myconfig;
110   my $form     = $main::form;
111   my $arap     = $params{vc} eq 'customer' ? 'ar'       : 'ap';
112   my $vc       = $params{vc} eq 'customer' ? 'customer' : 'vendor';
113   my $ARAP     = uc $arap;
114
115   my $dbh      = $params{dbh} || SL::DB->client->dbh;
116
117   my ($export_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('sepa_export_id_seq')|);
118   my $query       =
119     qq|INSERT INTO sepa_export (id, employee_id, vc)
120        VALUES (?, (SELECT id
121                    FROM employee
122                    WHERE login = ?), ?)|;
123   do_query($form, $dbh, $query, $export_id, $params{employee}, $vc);
124
125   my $q_item_id = qq|SELECT nextval('id')|;
126   my $h_item_id = prepare_query($form, $dbh, $q_item_id);
127   my $c_mandate = $params{vc} eq 'customer' ? ', vc_mandator_id, vc_mandate_date_of_signature' : '';
128   my $p_mandate = $params{vc} eq 'customer' ? ', ?, ?' : '';
129
130   my $q_insert =
131     qq|INSERT INTO sepa_export_items (id,          sepa_export_id,           ${arap}_id,  chart_id,
132                                       amount,      requested_execution_date, reference,   end_to_end_id,
133                                       our_iban,    our_bic,                  vc_iban,     vc_bic,
134                                       skonto_amount, payment_type ${c_mandate})
135        VALUES                        (?,           ?,                        ?,           ?,
136                                       ?,           ?,                        ?,           ?,
137                                       ?,           ?,                        ?,           ?,
138                                       ?,           ? ${p_mandate})|;
139   my $h_insert = prepare_query($form, $dbh, $q_insert);
140
141   my $q_reference =
142     qq|SELECT arap.invnumber,
143          (SELECT COUNT(at.*)
144           FROM acc_trans at
145           LEFT JOIN chart c ON (at.chart_id = c.id)
146           WHERE (at.trans_id = ?)
147             AND (c.link LIKE '%${ARAP}_paid%'))
148          +
149          (SELECT COUNT(sei.*)
150           FROM sepa_export_items sei
151           WHERE (sei.ap_id = ?))
152          AS num_payments
153        FROM ${arap} arap
154        WHERE id = ?|;
155   my $h_reference = prepare_query($form, $dbh, $q_reference);
156
157   my @now         = localtime;
158
159   foreach my $transfer (@{ $params{bank_transfers} }) {
160     if (!$transfer->{reference}) {
161       do_statement($form, $h_reference, $q_reference, (conv_i($transfer->{"${arap}_id"})) x 3);
162
163       my ($invnumber, $num_payments) = $h_reference->fetchrow_array();
164       $num_payments++;
165
166       $transfer->{reference} = "${invnumber}-${num_payments}";
167     }
168
169     $h_item_id->execute();
170     my ($item_id)      = $h_item_id->fetchrow_array();
171
172     my $end_to_end_id  = strftime "LXO%Y%m%d%H%M%S", localtime;
173     my $item_id_len    = length "$item_id";
174     my $num_zeroes     = 35 - $item_id_len - length $end_to_end_id;
175     $end_to_end_id    .= '0' x $num_zeroes if (0 < $num_zeroes);
176     $end_to_end_id    .= $item_id;
177     $end_to_end_id     = substr $end_to_end_id, 0, 35;
178
179     my @values = ($item_id,                          $export_id,
180                   conv_i($transfer->{"${arap}_id"}), conv_i($transfer->{chart_id}),
181                   $transfer->{amount},               conv_date($transfer->{requested_execution_date}),
182                   $transfer->{reference},            $end_to_end_id,
183                   map { my $pfx = $_; map { $transfer->{"${pfx}_${_}"} } qw(iban bic) } qw(our vc));
184     # save value of skonto_amount and payment_type
185     if ( $transfer->{payment_type} eq 'without_skonto' ) {
186       push(@values, 0);
187     } elsif ($transfer->{payment_type} eq 'difference_as_skonto' ) {
188       push(@values, $transfer->{amount});
189     } elsif ($transfer->{payment_type} eq 'with_skonto_pt' ) {
190       push(@values, $transfer->{skonto_amount});
191     } else {
192       die "illegal payment_type: " . $transfer->{payment_type} . "\n";
193     };
194     push(@values, $transfer->{payment_type});
195
196     push @values, $transfer->{vc_mandator_id}, conv_date($transfer->{vc_mandate_date_of_signature}) if $params{vc} eq 'customer';
197
198     do_statement($form, $h_insert, $q_insert, @values);
199   }
200
201   $h_insert->finish();
202   $h_item_id->finish();
203
204   return $export_id;
205 }
206
207 sub retrieve_export {
208   $main::lxdebug->enter_sub();
209
210   my $self     = shift;
211   my %params   = @_;
212
213   Common::check_params(\%params, qw(id vc));
214
215   my $myconfig = \%main::myconfig;
216   my $form     = $main::form;
217   my $vc       = $params{vc} eq 'customer' ? 'customer' : 'vendor';
218   my $arap     = $params{vc} eq 'customer' ? 'ar'       : 'ap';
219
220   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
221
222   my ($joins, $columns);
223
224   if ($params{details}) {
225     $columns = ', arap.invoice';
226     $joins   = "LEFT JOIN ${arap} arap ON (se.${arap}_id = arap.id)";
227   }
228
229   my $query =
230     qq|SELECT se.*,
231          CASE WHEN COALESCE(e.name, '') <> '' THEN e.name ELSE e.login END AS employee
232        FROM sepa_export se
233        LEFT JOIN employee e ON (se.employee_id = e.id)
234        WHERE se.id = ?|;
235
236   my $export = selectfirst_hashref_query($form, $dbh, $query, conv_i($params{id}));
237
238   if ($export->{id}) {
239     my ($columns, $joins);
240
241     my $mandator_id = $params{vc} eq 'customer' ? ', mandator_id, mandate_date_of_signature' : '';
242
243     if ($params{details}) {
244       $columns = qq|, arap.invnumber, arap.invoice, arap.transdate AS reference_date, vc.name AS vc_name, vc.${vc}number AS vc_number, c.accno AS chart_accno, c.description AS chart_description ${mandator_id}|;
245       $joins   = qq|LEFT JOIN ${arap} arap ON (sei.${arap}_id = arap.id)
246                     LEFT JOIN ${vc} vc     ON (arap.${vc}_id  = vc.id)
247                     LEFT JOIN chart c      ON (sei.chart_id   = c.id)|;
248     }
249
250     $query = qq|SELECT sei.*
251                   $columns
252                 FROM sepa_export_items sei
253                 $joins
254                 WHERE sei.sepa_export_id = ?|;
255
256     $export->{items} = selectall_hashref_query($form, $dbh, $query, conv_i($params{id}));
257
258   } else {
259     $export->{items} = [];
260   }
261
262   $main::lxdebug->leave_sub();
263
264   return $export;
265 }
266
267 sub close_export {
268   $main::lxdebug->enter_sub();
269
270   my $self     = shift;
271   my %params   = @_;
272
273   Common::check_params(\%params, qw(id));
274
275   my $myconfig = \%main::myconfig;
276   my $form     = $main::form;
277
278   SL::DB->client->with_transaction(sub {
279     my $dbh      = $params{dbh} || SL::DB->client->dbh;
280
281     my @ids          = ref $params{id} eq 'ARRAY' ? @{ $params{id} } : ($params{id});
282     my $placeholders = join ', ', ('?') x scalar @ids;
283     my $query        = qq|UPDATE sepa_export SET closed = TRUE WHERE id IN ($placeholders)|;
284
285     do_query($form, $dbh, $query, map { conv_i($_) } @ids);
286     1;
287   }) or do { die SL::DB->client->error };
288
289   $main::lxdebug->leave_sub();
290 }
291
292 sub list_exports {
293   $main::lxdebug->enter_sub();
294
295   my $self     = shift;
296   my %params   = @_;
297
298   my $myconfig = \%main::myconfig;
299   my $form     = $main::form;
300   my $vc       = $params{vc} eq 'customer' ? 'customer' : 'vendor';
301   my $arap     = $params{vc} eq 'customer' ? 'ar'       : 'ap';
302
303   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
304
305   my %sort_columns = (
306     'id'          => [ 'se.id',                ],
307     'export_date' => [ 'se.itime',             ],
308     'employee'    => [ 'e.name',      'se.id', ],
309     'executed'    => [ 'se.executed', 'se.id', ],
310     'closed'      => [ 'se.closed',   'se.id', ],
311     );
312
313   my %sort_spec = create_sort_spec('defs' => \%sort_columns, 'default' => 'id', 'column' => $params{sortorder}, 'dir' => $params{sortdir});
314
315   my (@where, @values, @where_sub, @values_sub, %joins_sub);
316
317   my $filter = $params{filter} || { };
318
319   foreach (qw(executed closed)) {
320     push @where, $filter->{$_} ? "se.$_" : "NOT se.$_" if (exists $filter->{$_});
321   }
322
323   my %operators = ('from' => '>=',
324                    'to'   => '<=');
325
326   foreach my $dir (qw(from to)) {
327     next unless ($filter->{"export_date_${dir}"});
328     push @where,  "se.itime $operators{$dir} ?::date";
329     push @values, $filter->{"export_date_${dir}"};
330   }
331
332   if ($filter->{invnumber}) {
333     push @where_sub,  "arap.invnumber ILIKE ?";
334     push @values_sub, like($filter->{invnumber});
335     $joins_sub{$arap} = 1;
336   }
337
338   if ($filter->{message_id}) {
339     push @values, like($filter->{message_id});
340     push @where,  <<SQL;
341       se.id IN (
342         SELECT sepa_export_id
343         FROM sepa_export_message_ids
344         WHERE message_id ILIKE ?
345       )
346 SQL
347   }
348
349   if ($filter->{vc}) {
350     push @where_sub,  "vc.name ILIKE ?";
351     push @values_sub, like($filter->{vc});
352     $joins_sub{$arap} = 1;
353     $joins_sub{vc}    = 1;
354   }
355
356   foreach my $type (qw(requested_execution execution)) {
357     foreach my $dir (qw(from to)) {
358       next unless ($filter->{"${type}_date_${dir}"});
359       push @where_sub,  "(items.${type}_date IS NOT NULL) AND (items.${type}_date $operators{$dir} ?)";
360       push @values_sub, $filter->{"${type}_date_${_}"};
361     }
362   }
363
364   if (@where_sub) {
365     my $joins_sub  = '';
366     $joins_sub    .= " LEFT JOIN ${arap} arap ON (items.${arap}_id = arap.id)" if ($joins_sub{$arap});
367     $joins_sub    .= " LEFT JOIN ${vc} vc      ON (arap.${vc}_id   = vc.id)"   if ($joins_sub{vc});
368
369     my $where_sub  = join(' AND ', map { "(${_})" } @where_sub);
370
371     my $query_sub  = qq|se.id IN (SELECT items.sepa_export_id
372                                   FROM sepa_export_items items
373                                   $joins_sub
374                                   WHERE $where_sub)|;
375
376     push @where,  $query_sub;
377     push @values, @values_sub;
378   }
379
380   push @where,  'se.vc = ?';
381   push @values, $vc;
382
383   my $where = @where ? ' WHERE ' . join(' AND ', map { "(${_})" } @where) : '';
384
385   my $query =
386     qq|SELECT se.id, se.employee_id, se.executed, se.closed, itime::date AS export_date,
387          (SELECT COUNT(*)
388           FROM sepa_export_items sei
389           WHERE (sei.sepa_export_id = se.id)) AS num_invoices,
390          (SELECT SUM(sei.amount)
391           FROM sepa_export_items sei
392           WHERE (sei.sepa_export_id = se.id)) AS sum_amounts,
393          (SELECT string_agg(semi.message_id, ', ')
394           FROM sepa_export_message_ids semi
395           WHERE semi.sepa_export_id = se.id) AS message_ids,
396          e.name AS employee
397        FROM sepa_export se
398        LEFT JOIN (
399          SELECT emp.id,
400            CASE WHEN COALESCE(emp.name, '') <> '' THEN emp.name ELSE emp.login END AS name
401          FROM employee emp
402        ) AS e ON (se.employee_id = e.id)
403        $where
404        ORDER BY $sort_spec{sql}|;
405
406   my $results = selectall_hashref_query($form, $dbh, $query, @values);
407
408   $main::lxdebug->leave_sub();
409
410   return $results;
411 }
412
413 sub post_payment {
414   my ($self, %params) = @_;
415   $main::lxdebug->enter_sub();
416
417   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, %params);
418
419   $::lxdebug->leave_sub;
420   return $rc;
421 }
422
423 sub _post_payment {
424   my $self     = shift;
425   my %params   = @_;
426
427   Common::check_params(\%params, qw(items));
428
429   my $myconfig = \%main::myconfig;
430   my $form     = $main::form;
431   my $vc       = $params{vc} eq 'customer' ? 'customer' : 'vendor';
432   my $arap     = $params{vc} eq 'customer' ? 'ar'       : 'ap';
433   my $mult     = $params{vc} eq 'customer' ? -1         : 1;
434   my $ARAP     = uc $arap;
435
436   my $dbh      = $params{dbh} || SL::DB->client->dbh;
437
438   my @items    = ref $params{items} eq 'ARRAY' ? @{ $params{items} } : ($params{items});
439
440   my %handles  = (
441     'get_item'       => [ qq|SELECT sei.*
442                              FROM sepa_export_items sei
443                              WHERE sei.id = ?| ],
444
445     'get_arap'       => [ qq|SELECT at.chart_id
446                              FROM acc_trans at
447                              LEFT JOIN chart c ON (at.chart_id = c.id)
448                              WHERE (trans_id = ?)
449                                AND ((c.link LIKE '%:${ARAP}') OR (c.link LIKE '${ARAP}:%') OR (c.link = '${ARAP}'))
450                              LIMIT 1| ],
451
452     'add_acc_trans'  => [ qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate,       source, memo, taxkey, tax_id ,                                     chart_link)
453                              VALUES                (?,        ?,        ?,      ?,         current_date, ?,      '',   0,      (SELECT id FROM tax WHERE taxkey=0 LIMIT 1), (SELECT link FROM chart WHERE id=?))| ],
454
455     'update_arap'    => [ qq|UPDATE ${arap}
456                              SET paid = paid + ?
457                              WHERE id = ?| ],
458
459     'finish_item'    => [ qq|UPDATE sepa_export_items
460                              SET execution_date = ?, executed = TRUE
461                              WHERE id = ?| ],
462
463     'has_unexecuted' => [ qq|SELECT sei1.id
464                              FROM sepa_export_items sei1
465                              WHERE (sei1.sepa_export_id = (SELECT sei2.sepa_export_id
466                                                            FROM sepa_export_items sei2
467                                                            WHERE sei2.id = ?))
468                                AND NOT COALESCE(sei1.executed, FALSE)
469                              LIMIT 1| ],
470
471     'do_close'       => [ qq|UPDATE sepa_export
472                              SET executed = TRUE, closed = TRUE
473                              WHERE (id = ?)| ],
474     );
475
476   map { unshift @{ $_ }, prepare_query($form, $dbh, $_->[0]) } values %handles;
477
478   foreach my $item (@items) {
479
480     my $item_id = conv_i($item->{id});
481
482     # Retrieve the item data belonging to the ID.
483     do_statement($form, @{ $handles{get_item} }, $item_id);
484     my $orig_item = $handles{get_item}->[0]->fetchrow_hashref();
485
486     next if (!$orig_item);
487
488     # fetch item_id via Rose (same id as orig_item)
489     my $sepa_export_item = SL::DB::Manager::SepaExportItem->find_by( id => $item_id);
490
491     my $invoice;
492
493     if ( $sepa_export_item->ar_id ) {
494       $invoice = SL::DB::Manager::Invoice->find_by( id => $sepa_export_item->ar_id);
495     } elsif ( $sepa_export_item->ap_id ) {
496       $invoice = SL::DB::Manager::PurchaseInvoice->find_by( id => $sepa_export_item->ap_id);
497     } else {
498       die "sepa_export_item needs either ar_id or ap_id\n";
499     };
500
501     $invoice->pay_invoice(amount       => $sepa_export_item->amount,
502                           payment_type => $sepa_export_item->payment_type,
503                           chart_id     => $sepa_export_item->chart_id,
504                           source       => $sepa_export_item->reference,
505                           transdate    => $item->{execution_date},  # value from user form
506                          );
507
508     # Update the item to reflect that it has been posted.
509     do_statement($form, @{ $handles{finish_item} }, $item->{execution_date}, $item_id);
510
511     # Check whether or not we can close the export itself if there are no unexecuted items left.
512     do_statement($form, @{ $handles{has_unexecuted} }, $item_id);
513     my ($has_unexecuted) = $handles{has_unexecuted}->[0]->fetchrow_array();
514
515     if (!$has_unexecuted) {
516       do_statement($form, @{ $handles{do_close} }, $orig_item->{sepa_export_id});
517     }
518   }
519
520   map { $_->[0]->finish() } values %handles;
521
522   return 1;
523 }
524
525 1;