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