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