DATEV: single-dbh
[kivitendo-erp.git] / SL / DATEV.pm
1 #=====================================================================
2 # kivitendo ERP
3 # Copyright (c) 2004
4 #
5 #  Author: Philip Reetz
6 #   Email: p.reetz@linet-services.de
7 #     Web: http://www.lx-office.org
8 #
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #======================================================================
23 #
24 # Datev export module
25 #======================================================================
26
27 package SL::DATEV;
28
29 use utf8;
30 use strict;
31
32 use SL::DBUtils;
33 use SL::DATEV::KNEFile;
34 use SL::DB;
35
36 use Data::Dumper;
37 use DateTime;
38 use Exporter qw(import);
39 use File::Path;
40 use List::Util qw(max sum);
41 use Time::HiRes qw(gettimeofday);
42
43 {
44   my $i = 0;
45   use constant {
46     DATEV_ET_BUCHUNGEN => $i++,
47     DATEV_ET_STAMM     => $i++,
48
49     DATEV_FORMAT_KNE   => $i++,
50     DATEV_FORMAT_OBE   => $i++,
51   };
52 }
53
54 my @export_constants = qw(DATEV_ET_BUCHUNGEN DATEV_ET_STAMM DATEV_FORMAT_KNE DATEV_FORMAT_OBE);
55 our @EXPORT_OK = (@export_constants);
56 our %EXPORT_TAGS = (CONSTANTS => [ @export_constants ]);
57
58
59 sub new {
60   my $class = shift;
61   my %data  = @_;
62
63   my $obj = bless {}, $class;
64
65   $obj->$_($data{$_}) for keys %data;
66
67   $obj;
68 }
69
70 sub exporttype {
71   my $self = shift;
72   $self->{exporttype} = $_[0] if @_;
73   return $self->{exporttype};
74 }
75
76 sub has_exporttype {
77   defined $_[0]->{exporttype};
78 }
79
80 sub format {
81   my $self = shift;
82   $self->{format} = $_[0] if @_;
83   return $self->{format};
84 }
85
86 sub has_format {
87   defined $_[0]->{format};
88 }
89
90 sub _get_export_path {
91   $main::lxdebug->enter_sub();
92
93   my ($a, $b) = gettimeofday();
94   my $path    = _get_path_for_download_token("${a}-${b}-${$}");
95
96   mkpath($path) unless (-d $path);
97
98   $main::lxdebug->leave_sub();
99
100   return $path;
101 }
102
103 sub _get_path_for_download_token {
104   $main::lxdebug->enter_sub();
105
106   my $token = shift || '';
107   my $path;
108
109   if ($token =~ m|^(\d+)-(\d+)-(\d+)$|) {
110     $path = $::lx_office_conf{paths}->{userspath} . "/datev-export-${1}-${2}-${3}/";
111   }
112
113   $main::lxdebug->leave_sub();
114
115   return $path;
116 }
117
118 sub _get_download_token_for_path {
119   $main::lxdebug->enter_sub();
120
121   my $path = shift;
122   my $token;
123
124   if ($path =~ m|.*datev-export-(\d+)-(\d+)-(\d+)/?$|) {
125     $token = "${1}-${2}-${3}";
126   }
127
128   $main::lxdebug->leave_sub();
129
130   return $token;
131 }
132
133 sub download_token {
134   my $self = shift;
135   $self->{download_token} = $_[0] if @_;
136   return $self->{download_token} ||= _get_download_token_for_path($self->export_path);
137 }
138
139 sub export_path {
140   my ($self) = @_;
141
142   return  $self->{export_path} ||= _get_path_for_download_token($self->{download_token}) || _get_export_path();
143 }
144
145 sub add_filenames {
146   my $self = shift;
147   push @{ $self->{filenames} ||= [] }, @_;
148 }
149
150 sub filenames {
151   return @{ $_[0]{filenames} || [] };
152 }
153
154 sub add_error {
155   my $self = shift;
156   push @{ $self->{errors} ||= [] }, @_;
157 }
158
159 sub errors {
160   return @{ $_[0]{errors} || [] };
161 }
162
163 sub add_net_gross_differences {
164   my $self = shift;
165   push @{ $self->{net_gross_differences} ||= [] }, @_;
166 }
167
168 sub net_gross_differences {
169   return @{ $_[0]{net_gross_differences} || [] };
170 }
171
172 sub sum_net_gross_differences {
173   return sum $_[0]->net_gross_differences;
174 }
175
176 sub from {
177  my $self = shift;
178
179  if (@_) {
180    $self->{from} = $_[0];
181  }
182
183  return $self->{from};
184 }
185
186 sub to {
187  my $self = shift;
188
189  if (@_) {
190    $self->{to} = $_[0];
191  }
192
193  return $self->{to};
194 }
195
196 sub trans_id {
197   my $self = shift;
198
199   if (@_) {
200     $self->{trans_id} = $_[0];
201   }
202
203   die "illegal trans_id passed for DATEV export: " . $self->{trans_id} . "\n" unless $self->{trans_id} =~ m/^\d+$/;
204
205   return $self->{trans_id};
206 }
207
208 sub accnofrom {
209  my $self = shift;
210
211  if (@_) {
212    $self->{accnofrom} = $_[0];
213  }
214
215  return $self->{accnofrom};
216 }
217
218 sub accnoto {
219  my $self = shift;
220
221  if (@_) {
222    $self->{accnoto} = $_[0];
223  }
224
225  return $self->{accnoto};
226 }
227
228
229 sub dbh {
230   my $self = shift;
231
232   if (@_) {
233     $self->{dbh} = $_[0];
234     $self->{provided_dbh} = 1;
235   }
236
237   $self->{dbh} ||= SL::DB->client->dbh;
238 }
239
240 sub provided_dbh {
241   $_[0]{provided_dbh};
242 }
243
244 sub clean_temporary_directories {
245   $::lxdebug->enter_sub;
246
247   foreach my $path (glob($::lx_office_conf{paths}->{userspath} . "/datev-export-*")) {
248     next unless -d $path;
249
250     my $mtime = (stat($path))[9];
251     next if ((time() - $mtime) < 8 * 60 * 60);
252
253     rmtree $path;
254   }
255
256   $::lxdebug->leave_sub;
257 }
258
259 sub _fill {
260   $main::lxdebug->enter_sub();
261
262   my $text      = shift // '';
263   my $field_len = shift;
264   my $fill_char = shift;
265   my $alignment = shift || 'right';
266
267   my $text_len  = length $text;
268
269   if ($field_len < $text_len) {
270     $text = substr $text, 0, $field_len;
271
272   } elsif ($field_len > $text_len) {
273     my $filler = ($fill_char) x ($field_len - $text_len);
274     $text      = $alignment eq 'right' ? $filler . $text : $text . $filler;
275   }
276
277   $main::lxdebug->leave_sub();
278
279   return $text;
280 }
281
282 sub get_datev_stamm {
283   return $_[0]{stamm} ||= selectfirst_hashref_query($::form, $_[0]->dbh, 'SELECT * FROM datev');
284 }
285
286 sub save_datev_stamm {
287   my ($self, $data) = @_;
288
289   SL::DB->client->with_transaction(sub {
290     do_query($::form, $self->dbh, 'DELETE FROM datev');
291
292     my @columns = qw(beraternr beratername dfvkz mandantennr datentraegernr abrechnungsnr);
293
294     my $query = "INSERT INTO datev (" . join(', ', @columns) . ") VALUES (" . join(', ', ('?') x @columns) . ")";
295     do_query($::form, $self->dbh, $query, map { $data->{$_} } @columns);
296   });
297 }
298
299 sub export {
300   my ($self) = @_;
301   my $result;
302
303   die 'no format set!' unless $self->has_format;
304
305   if ($self->format == DATEV_FORMAT_KNE) {
306     $result = $self->kne_export;
307   } elsif ($self->format == DATEV_FORMAT_OBE) {
308     $result = $self->obe_export;
309   } else {
310     die 'unrecognized export format';
311   }
312
313   return $result;
314 }
315
316 sub kne_export {
317   my ($self) = @_;
318   my $result;
319
320   die 'no exporttype set!' unless $self->has_exporttype;
321
322   if ($self->exporttype == DATEV_ET_BUCHUNGEN) {
323     $result = $self->kne_buchungsexport;
324   } elsif ($self->exporttype == DATEV_ET_STAMM) {
325     $result = $self->kne_stammdatenexport;
326   } else {
327     die 'unrecognized exporttype';
328   }
329
330   return $result;
331 }
332
333 sub obe_export {
334   die 'not yet implemented';
335 }
336
337 sub fromto {
338   my ($self) = @_;
339
340   return unless $self->from && $self->to;
341
342   return "transdate >= '" . $self->from->to_lxoffice . "' and transdate <= '" . $self->to->to_lxoffice . "'";
343 }
344
345 sub _sign {
346   $_[0] <=> 0;
347 }
348
349 sub _get_transactions {
350   $main::lxdebug->enter_sub();
351   my $self     = shift;
352   my $fromto   = shift;
353   my $progress_callback = shift || sub {};
354
355   my $form     =  $main::form;
356
357   my $trans_id_filter = '';
358
359   if ( $self->{trans_id} ) {
360     # ignore dates when trans_id is passed so that the entire transaction is
361     # checked, not just either the initial bookings or the subsequent payments
362     # (the transdates will likely differ)
363     $fromto = '';
364     $trans_id_filter = 'ac.trans_id = ' . $self->trans_id;
365   } else {
366     $fromto      =~ s/transdate/ac\.transdate/g;
367   };
368
369   my ($notsplitindex);
370
371   my $filter   = '';            # Useful for debugging purposes
372
373   my %all_taxchart_ids = selectall_as_map($form, $self->dbh, qq|SELECT DISTINCT chart_id, TRUE AS is_set FROM tax|, 'chart_id', 'is_set');
374
375   my $query    =
376     qq|SELECT ac.acc_trans_id, ac.transdate, ac.trans_id,ar.id, ac.amount, ac.taxkey,
377          ar.invnumber, ar.duedate, ar.amount as umsatz, ar.deliverydate,
378          ct.name, ct.ustid,
379          c.accno, c.taxkey_id as charttax, c.datevautomatik, c.id, ac.chart_link AS link,
380          ar.invoice,
381          t.rate AS taxrate,
382          'ar' as table
383        FROM acc_trans ac
384        LEFT JOIN ar          ON (ac.trans_id    = ar.id)
385        LEFT JOIN customer ct ON (ar.customer_id = ct.id)
386        LEFT JOIN chart c     ON (ac.chart_id    = c.id)
387        LEFT JOIN tax t       ON (ac.tax_id      = t.id)
388        WHERE (ar.id IS NOT NULL)
389          AND $fromto
390          $trans_id_filter
391          $filter
392
393        UNION ALL
394
395        SELECT ac.acc_trans_id, ac.transdate, ac.trans_id,ap.id, ac.amount, ac.taxkey,
396          ap.invnumber, ap.duedate, ap.amount as umsatz, ap.deliverydate,
397          ct.name,ct.ustid,
398          c.accno, c.taxkey_id as charttax, c.datevautomatik, c.id, ac.chart_link AS link,
399          ap.invoice,
400          t.rate AS taxrate,
401          'ap' as table
402        FROM acc_trans ac
403        LEFT JOIN ap        ON (ac.trans_id  = ap.id)
404        LEFT JOIN vendor ct ON (ap.vendor_id = ct.id)
405        LEFT JOIN chart c   ON (ac.chart_id  = c.id)
406        LEFT JOIN tax t     ON (ac.tax_id    = t.id)
407        WHERE (ap.id IS NOT NULL)
408          AND $fromto
409          $trans_id_filter
410          $filter
411
412        UNION ALL
413
414        SELECT ac.acc_trans_id, ac.transdate, ac.trans_id,gl.id, ac.amount, ac.taxkey,
415          gl.reference AS invnumber, gl.transdate AS duedate, ac.amount as umsatz, NULL as deliverydate,
416          gl.description AS name, NULL as ustid,
417          c.accno, c.taxkey_id as charttax, c.datevautomatik, c.id, ac.chart_link AS link,
418          FALSE AS invoice,
419          t.rate AS taxrate,
420          'gl' as table
421        FROM acc_trans ac
422        LEFT JOIN gl      ON (ac.trans_id  = gl.id)
423        LEFT JOIN chart c ON (ac.chart_id  = c.id)
424        LEFT JOIN tax t   ON (ac.tax_id    = t.id)
425        WHERE (gl.id IS NOT NULL)
426          AND $fromto
427          $trans_id_filter
428          $filter
429
430        ORDER BY trans_id, acc_trans_id|;
431
432   my $sth = prepare_execute_query($form, $self->dbh, $query);
433   $self->{DATEV} = [];
434
435   my $counter = 0;
436   my $continue = 1; #
437   my $name;
438   while ( $continue && (my $ref = $sth->fetchrow_hashref("NAME_lc")) ) {
439     last unless $ref;  # for single transactions
440     $counter++;
441     if (($counter % 500) == 0) {
442       $progress_callback->($counter);
443     }
444
445     my $trans    = [ $ref ];
446
447     my $count    = $ref->{amount};
448     my $firstrun = 1;
449
450     # if the amount of a booking in a group is smaller than 0.02, any tax
451     # amounts will likely be smaller than 1 cent, so go into subcent mode
452     my $subcent  = abs($count) < 0.02;
453
454     # records from acc_trans are ordered by trans_id and acc_trans_id
455     # first check for unbalanced ledger inside one trans_id
456     # there may be several groups inside a trans_id, e.g. the original booking and the payment
457     # each group individually should be exactly balanced and each group
458     # individually needs its own datev lines
459
460     # keep fetching new acc_trans lines until the end of a balanced group is reached
461     while (abs($count) > 0.01 || $firstrun || ($subcent && abs($count) > 0.005)) {
462       my $ref2 = $sth->fetchrow_hashref("NAME_lc");
463       unless ( $ref2 ) {
464         $continue = 0;
465         last;
466       };
467
468       # check if trans_id of current acc_trans line is still the same as the
469       # trans_id of the first line in group, i.e. we haven't finished a 0-group
470       # before moving on to the next trans_id, error will likely be in the old
471       # trans_id.
472
473       if ($ref2->{trans_id} != $trans->[0]->{trans_id}) {
474         require SL::DB::Manager::AccTransaction;
475         if ( $trans->[0]->{trans_id} ) {
476           my $acc_trans_old_obj  = SL::DB::Manager::AccTransaction->get_first(where => [ trans_id => $trans->[0]->{trans_id} ]);
477           $self->add_error("Unbalanced ledger! Old: " . $acc_trans_old_obj->transaction_name) if ref($acc_trans_old_obj);
478         };
479         if ( $ref2->{trans_id} ) {
480           my $acc_trans_curr_obj = SL::DB::Manager::AccTransaction->get_first(where => [ trans_id => $ref2->{trans_id} ]);
481           $self->add_error("Unbalanced ledger! New:" . $acc_trans_curr_obj->transaction_name) if ref($acc_trans_curr_obj);
482         };
483         $self->add_error("count: $count");
484         return;
485       }
486
487       push @{ $trans }, $ref2;
488
489       $count    += $ref2->{amount};
490       $firstrun  = 0;
491     }
492
493     foreach my $i (0 .. scalar(@{ $trans }) - 1) {
494       my $ref        = $trans->[$i];
495       my $prev_ref   = 0 < $i ? $trans->[$i - 1] : undef;
496       if (   $all_taxchart_ids{$ref->{id}}
497           && ($ref->{link} =~ m/(?:AP_tax|AR_tax)/)
498           && (   ($prev_ref && $prev_ref->{taxkey} && (_sign($ref->{amount}) == _sign($prev_ref->{amount})))
499               || $ref->{invoice})) {
500         $ref->{is_tax} = 1;
501       }
502
503       if (   !$ref->{invoice}   # we have a non-invoice booking (=gl)
504           &&  $ref->{is_tax}    # that has "is_tax" set
505           && !($prev_ref->{is_tax})  # previous line wasn't is_tax
506           &&  (_sign($ref->{amount}) == _sign($prev_ref->{amount}))) {  # and sign same as previous sign
507         $trans->[$i - 1]->{tax_amount} = $ref->{amount};
508       }
509     }
510
511     my $absumsatz     = 0;
512     if (scalar(@{$trans}) <= 2) {
513       push @{ $self->{DATEV} }, $trans;
514       next;
515     }
516
517     # determine at which array position the reference value (called absumsatz) is
518     # and which amount it has
519
520     for my $j (0 .. (scalar(@{$trans}) - 1)) {
521
522       # Three cases:
523       # 1: gl transaction (Dialogbuchung), invoice is false, no double split booking allowed
524
525       # 2: sales or vendor invoice (Verkaufs- und Einkaufsrechnung): invoice is
526       # true, instead of absumsatz use link AR/AP (there should only be one
527       # entry)
528
529       # 3. AR/AP transaction (Kreditoren- und Debitorenbuchung): invoice is false,
530       # instead of absumsatz use link AR/AP (there should only be one, so jump
531       # out of search as soon as you find it )
532
533       # case 1 and 2
534       # for gl-bookings no split is allowed and there is no AR/AP account, so we always use the maximum value as a reference
535       # for ap/ar bookings we can always search for AR/AP in link and use that
536       if ( ( not $trans->[$j]->{'invoice'} and abs($trans->[$j]->{'amount'}) > abs($absumsatz) )
537          or ($trans->[$j]->{'invoice'} and ($trans->[$j]->{'link'} eq 'AR' or $trans->[$j]->{'link'} eq 'AP'))) {
538         $absumsatz     = $trans->[$j]->{'amount'};
539         $notsplitindex = $j;
540       }
541
542       # case 3
543       # Problem: we can't distinguish between AR and AP and normal invoices via boolean "invoice"
544       # for AR and AP transaction exit the loop as soon as an AR or AP account is found
545       # there must be only one AR or AP chart in the booking
546       # since it is possible to do this kind of things with GL too, make sure those don't get aborted in case someone
547       # manually pays an invoice in GL.
548       if ($trans->[$j]->{table} ne 'gl' and ($trans->[$j]->{'link'} eq 'AR' or $trans->[$j]->{'link'} eq 'AP')) {
549         $notsplitindex = $j;   # position in booking with highest amount
550         $absumsatz     = $trans->[$j]->{'amount'};
551         last;
552       };
553     }
554
555     my $ml             = ($trans->[0]->{'umsatz'} > 0) ? 1 : -1;
556     my $rounding_error = 0;
557     my @taxed;
558
559     # go through each line and determine if it is a tax booking or not
560     # skip all tax lines and notsplitindex line
561     # push all other accounts (e.g. income or expense) with corresponding taxkey
562
563     for my $j (0 .. (scalar(@{$trans}) - 1)) {
564       if (   ($j != $notsplitindex)
565           && !$trans->[$j]->{is_tax}
566           && (   $trans->[$j]->{'taxkey'} eq ""
567               || $trans->[$j]->{'taxkey'} eq "0"
568               || $trans->[$j]->{'taxkey'} eq "1"
569               || $trans->[$j]->{'taxkey'} eq "10"
570               || $trans->[$j]->{'taxkey'} eq "11")) {
571         my %new_trans = ();
572         map { $new_trans{$_} = $trans->[$notsplitindex]->{$_}; } keys %{ $trans->[$notsplitindex] };
573
574         $absumsatz               += $trans->[$j]->{'amount'};
575         $new_trans{'amount'}      = $trans->[$j]->{'amount'} * (-1);
576         $new_trans{'umsatz'}      = abs($trans->[$j]->{'amount'}) * $ml;
577         $trans->[$j]->{'umsatz'}  = abs($trans->[$j]->{'amount'}) * $ml;
578
579         push @{ $self->{DATEV} }, [ \%new_trans, $trans->[$j] ];
580
581       } elsif (($j != $notsplitindex) && !$trans->[$j]->{is_tax}) {
582
583         my %new_trans = ();
584         map { $new_trans{$_} = $trans->[$notsplitindex]->{$_}; } keys %{ $trans->[$notsplitindex] };
585
586         my $tax_rate              = $trans->[$j]->{'taxrate'};
587         $new_trans{'net_amount'}  = $trans->[$j]->{'amount'} * -1;
588         $new_trans{'tax_rate'}    = 1 + $tax_rate;
589
590         if (!$trans->[$j]->{'invoice'}) {
591           $new_trans{'amount'}      = $form->round_amount(-1 * ($trans->[$j]->{amount} + $trans->[$j]->{tax_amount}), 2);
592           $new_trans{'umsatz'}      = abs($new_trans{'amount'}) * $ml;
593           $trans->[$j]->{'umsatz'}  = $new_trans{'umsatz'};
594           $absumsatz               += -1 * $new_trans{'amount'};
595
596         } else {
597           my $unrounded             = $trans->[$j]->{'amount'} * (1 + $tax_rate) * -1 + $rounding_error;
598           my $rounded               = $form->round_amount($unrounded, 2);
599
600           $rounding_error           = $unrounded - $rounded;
601           $new_trans{'amount'}      = $rounded;
602           $new_trans{'umsatz'}      = abs($rounded) * $ml;
603           $trans->[$j]->{'umsatz'}  = $new_trans{umsatz};
604           $absumsatz               -= $rounded;
605         }
606
607         push @{ $self->{DATEV} }, [ \%new_trans, $trans->[$j] ];
608         push @taxed, $self->{DATEV}->[-1];
609       }
610     }
611
612     my $idx        = 0;
613     my $correction = 0;
614     while ((abs($absumsatz) >= 0.01) && (abs($absumsatz) < 1.00)) {
615       if ($idx >= scalar @taxed) {
616         last if (!$correction);
617
618         $correction = 0;
619         $idx        = 0;
620       }
621
622       my $transaction = $taxed[$idx]->[0];
623
624       my $old_amount     = $transaction->{amount};
625       my $old_correction = $correction;
626       my @possible_diffs;
627
628       if (!$transaction->{diff}) {
629         @possible_diffs = (0.01, -0.01);
630       } else {
631         @possible_diffs = ($transaction->{diff});
632       }
633
634       foreach my $diff (@possible_diffs) {
635         my $net_amount = $form->round_amount(($transaction->{amount} + $diff) / $transaction->{tax_rate}, 2);
636         next if ($net_amount != $transaction->{net_amount});
637
638         $transaction->{diff}    = $diff;
639         $transaction->{amount} += $diff;
640         $transaction->{umsatz} += $diff;
641         $absumsatz             -= $diff;
642         $correction             = 1;
643
644         last;
645       }
646
647       $idx++;
648     }
649
650     $absumsatz = $form->round_amount($absumsatz, 2);
651     if (abs($absumsatz) >= (0.01 * (1 + scalar @taxed))) {
652       require SL::DB::Manager::AccTransaction;
653       my $acc_trans_obj  = SL::DB::Manager::AccTransaction->get_first(where => [ trans_id => $trans->[0]->{trans_id} ]);
654       $self->add_error("Datev-Export fehlgeschlagen! Bei Transaktion " . $acc_trans_obj->transaction_name . " ($absumsatz)");
655
656     } elsif (abs($absumsatz) >= 0.01) {
657       $self->add_net_gross_differences($absumsatz);
658     }
659   }
660
661   $sth->finish();
662
663   $::lxdebug->leave_sub;
664 }
665
666 sub make_kne_data_header {
667   $main::lxdebug->enter_sub();
668
669   my ($self, $form) = @_;
670   my ($primanota);
671
672   my $stamm = $self->get_datev_stamm;
673
674   my $jahr = $self->from ? $self->from->year : DateTime->today->year;
675
676   #Header
677   my $header  = "\x1D\x181";
678   $header    .= _fill($stamm->{datentraegernr}, 3, ' ', 'left');
679   $header    .= ($self->fromto) ? "11" : "13"; # Anwendungsnummer
680   $header    .= _fill($stamm->{dfvkz}, 2, '0');
681   $header    .= _fill($stamm->{beraternr}, 7, '0');
682   $header    .= _fill($stamm->{mandantennr}, 5, '0');
683   $header    .= _fill(($stamm->{abrechnungsnr} // '') . $jahr, 6, '0');
684
685   $header .= $self->from ? $self->from->strftime('%d%m%y') : '';
686   $header .= $self->to   ? $self->to->strftime('%d%m%y')   : '';
687
688   if ($self->fromto) {
689     $primanota = "001";
690     $header .= $primanota;
691   }
692
693   $header .= _fill($stamm->{passwort}, 4, '0');
694   $header .= " " x 16;       # Anwendungsinfo
695   $header .= " " x 16;       # Inputinfo
696   $header .= "\x79";
697
698   #Versionssatz
699   my $versionssatz  = $self->exporttype == DATEV_ET_BUCHUNGEN ? "\xB5" . "1," : "\xB6" . "1,";
700
701   my $query         = qq|SELECT accno FROM chart LIMIT 1|;
702   my $ref           = selectfirst_hashref_query($form, $self->dbh, $query);
703
704   $versionssatz    .= length $ref->{accno};
705   $versionssatz    .= ",";
706   $versionssatz    .= length $ref->{accno};
707   $versionssatz    .= ",SELF" . "\x1C\x79";
708
709   $header          .= $versionssatz;
710
711   $main::lxdebug->leave_sub();
712
713   return $header;
714 }
715
716 sub datetofour {
717   $main::lxdebug->enter_sub();
718
719   my ($date, $six) = @_;
720
721   my ($day, $month, $year) = split(/\./, $date);
722
723   if ($day =~ /^0/) {
724     $day = substr($day, 1, 1);
725   }
726   if (length($month) < 2) {
727     $month = "0" . $month;
728   }
729   if (length($year) > 2) {
730     $year = substr($year, -2, 2);
731   }
732
733   if ($six) {
734     $date = $day . $month . $year;
735   } else {
736     $date = $day . $month;
737   }
738
739   $main::lxdebug->leave_sub();
740
741   return $date;
742 }
743
744 sub trim_leading_zeroes {
745   my $str = shift;
746
747   $str =~ s/^0+//g;
748
749   return $str;
750 }
751
752 sub make_ed_versionset {
753   $main::lxdebug->enter_sub();
754
755   my ($self, $header, $filename, $blockcount) = @_;
756
757   my $versionset  = "V" . substr($filename, 2, 5);
758   $versionset    .= substr($header, 6, 22);
759
760   if ($self->fromto) {
761     $versionset .= "0000" . substr($header, 28, 19);
762   } else {
763     my $datum = " " x 16;
764     $versionset .= $datum . "001" . substr($header, 28, 4);
765   }
766
767   $versionset .= _fill($blockcount, 5, '0');
768   $versionset .= "001";
769   $versionset .= " 1";
770   $versionset .= substr($header, -12, 10) . "    ";
771   $versionset .= " " x 53;
772
773   $main::lxdebug->leave_sub();
774
775   return $versionset;
776 }
777
778 sub make_ev_header {
779   $main::lxdebug->enter_sub();
780
781   my ($self, $form, $fileno) = @_;
782
783   my $stamm = $self->get_datev_stamm;
784
785   my $ev_header  = _fill($stamm->{datentraegernr}, 3, ' ', 'left');
786   $ev_header    .= "   ";
787   $ev_header    .= _fill($stamm->{beraternr}, 7, ' ', 'left');
788   $ev_header    .= _fill($stamm->{beratername}, 9, ' ', 'left');
789   $ev_header    .= " ";
790   $ev_header    .= (_fill($fileno, 5, '0')) x 2;
791   $ev_header    .= " " x 95;
792
793   $main::lxdebug->leave_sub();
794
795   return $ev_header;
796 }
797
798 sub kne_buchungsexport {
799   $main::lxdebug->enter_sub();
800
801   my ($self) = @_;
802
803   my $form = $::form;
804
805   my @filenames;
806
807   my $filename    = "ED00000";
808   my $evfile      = "EV01";
809   my @ed_versionset;
810   my $fileno = 0;
811
812   my $fromto = $self->fromto;
813
814   $self->_get_transactions($fromto);
815
816   return if $self->errors;
817
818   my $counter = 0;
819
820   while (scalar(@{ $self->{DATEV} || [] })) {
821     my $umsatzsumme = 0;
822     $filename++;
823     my $ed_filename = $self->export_path . $filename;
824     push(@filenames, $filename);
825     my $header = $self->make_kne_data_header($form);
826
827     my $kne_file = SL::DATEV::KNEFile->new();
828     $kne_file->add_block($header);
829
830     while (scalar(@{ $self->{DATEV} }) > 0) {
831       my $transaction = shift @{ $self->{DATEV} };
832       my $trans_lines = scalar(@{$transaction});
833       $counter++;
834
835       my $umsatz         = 0;
836       my $gegenkonto     = "";
837       my $konto          = "";
838       my $belegfeld1     = "";
839       my $datum          = "";
840       my $waehrung       = "";
841       my $buchungstext   = "";
842       my $belegfeld2     = "";
843       my $datevautomatik = 0;
844       my $taxkey         = 0;
845       my $charttax       = 0;
846       my $ustid          ="";
847       my ($haben, $soll);
848       my $iconv          = $::locale->{iconv_utf8};
849       my %umlaute = ($iconv->convert('ä') => 'ae',
850                      $iconv->convert('ö') => 'oe',
851                      $iconv->convert('ü') => 'ue',
852                      $iconv->convert('Ä') => 'Ae',
853                      $iconv->convert('Ö') => 'Oe',
854                      $iconv->convert('Ü') => 'Ue',
855                      $iconv->convert('ß') => 'sz');
856       for (my $i = 0; $i < $trans_lines; $i++) {
857         if ($trans_lines == 2) {
858           if (abs($transaction->[$i]->{'amount'}) > abs($umsatz)) {
859             $umsatz = $transaction->[$i]->{'amount'};
860           }
861         } else {
862           if (abs($transaction->[$i]->{'umsatz'}) > abs($umsatz)) {
863             $umsatz = $transaction->[$i]->{'umsatz'};
864           }
865         }
866         if ($transaction->[$i]->{'datevautomatik'}) {
867           $datevautomatik = 1;
868         }
869         if ($transaction->[$i]->{'taxkey'}) {
870           $taxkey = $transaction->[$i]->{'taxkey'};
871         }
872         if ($transaction->[$i]->{'charttax'}) {
873           $charttax = $transaction->[$i]->{'charttax'};
874         }
875         if ($transaction->[$i]->{'amount'} > 0) {
876           $haben = $i;
877         } else {
878           $soll = $i;
879         }
880       }
881       # Umwandlung von Umlauten und Sonderzeichen in erlaubte Zeichen bei Textfeldern
882       foreach my $umlaut (keys(%umlaute)) {
883         $transaction->[$haben]->{'invnumber'} =~ s/${umlaut}/${umlaute{$umlaut}}/g;
884         $transaction->[$haben]->{'name'}      =~ s/${umlaut}/${umlaute{$umlaut}}/g;
885       }
886
887       $transaction->[$haben]->{'invnumber'} =~ s/[^0-9A-Za-z\$\%\&\*\+\-\/]//g;
888       $transaction->[$haben]->{'name'}      =~ s/[^0-9A-Za-z\$\%\&\*\+\-\ \/]//g;
889
890       $transaction->[$haben]->{'invnumber'} =  substr($transaction->[$haben]->{'invnumber'}, 0, 12);
891       $transaction->[$haben]->{'name'}      =  substr($transaction->[$haben]->{'name'}, 0, 30);
892       $transaction->[$haben]->{'invnumber'} =~ s/\ *$//;
893       $transaction->[$haben]->{'name'}      =~ s/\ *$//;
894
895       if ($trans_lines >= 2) {
896
897         $gegenkonto = "a" . trim_leading_zeroes($transaction->[$haben]->{'accno'});
898         $konto      = "e" . trim_leading_zeroes($transaction->[$soll]->{'accno'});
899         if ($transaction->[$haben]->{'invnumber'} ne "") {
900           $belegfeld1 = "\xBD" . $transaction->[$haben]->{'invnumber'} . "\x1C";
901         }
902         $datum = "d";
903         $datum .= &datetofour($transaction->[$haben]->{'transdate'}, 0);
904         $waehrung = "\xB3" . "EUR" . "\x1C";
905         if ($transaction->[$haben]->{'name'} ne "") {
906           $buchungstext = "\x1E" . $transaction->[$haben]->{'name'} . "\x1C";
907         }
908         if (($transaction->[$haben]->{'ustid'} // '') ne "") {
909           $ustid = "\xBA" . $transaction->[$haben]->{'ustid'} . "\x1C";
910         }
911         if (($transaction->[$haben]->{'duedate'} // '') ne "") {
912           $belegfeld2 = "\xBE" . &datetofour($transaction->[$haben]->{'duedate'}, 1) . "\x1C";
913         }
914       }
915
916       $umsatz       = $kne_file->format_amount(abs($umsatz), 0);
917       $umsatzsumme += $umsatz;
918       $kne_file->add_block("+" . $umsatz);
919
920       # Dies ist die einzige Stelle die datevautomatik auswertet. Was soll gesagt werden?
921       # Im Prinzip hat jeder acc_trans Eintrag einen Steuerschlüssel, außer, bei gewissen Fällen
922       # wie: Kreditorenbuchung mit negativen Vorzeichen, SEPA-Export oder Rechnungen die per
923       # Skript angelegt werden.
924       # Also falls ein Steuerschlüssel da ist und NICHT datevautomatik diesen Block hinzufügen.
925       # Oder aber datevautomatik ist WAHR, aber der Steuerschlüssel in der acc_trans weicht
926       # von dem in der Chart ab: Also wahrscheinlich Programmfehler (NULL übergeben, statt
927       # DATEV-Steuerschlüssel) oder der Steuerschlüssel des Kontos weicht WIRKLICH von dem Eintrag in der
928       # acc_trans ab. Gibt es für diesen Fall eine plausiblen Grund?
929       #
930       if (   ( $datevautomatik || $taxkey)
931           && (!$datevautomatik || ($datevautomatik && ($charttax ne $taxkey)))) {
932 #         $kne_file->add_block("\x6C" . (!$datevautomatik ? $taxkey : "4"));
933         $kne_file->add_block("\x6C${taxkey}");
934       }
935
936       $kne_file->add_block($gegenkonto);
937       $kne_file->add_block($belegfeld1);
938       $kne_file->add_block($belegfeld2);
939       $kne_file->add_block($datum);
940       $kne_file->add_block($konto);
941       $kne_file->add_block($buchungstext);
942       $kne_file->add_block($ustid);
943       $kne_file->add_block($waehrung . "\x79");
944     }
945
946     my $mandantenendsumme = "x" . $kne_file->format_amount($umsatzsumme / 100.0, 14) . "\x79\x7a";
947
948     $kne_file->add_block($mandantenendsumme);
949     $kne_file->flush();
950
951     open(ED, ">", $ed_filename) or die "can't open outputfile: $!\n";
952     print(ED $kne_file->get_data());
953     close(ED);
954
955     $ed_versionset[$fileno] = $self->make_ed_versionset($header, $filename, $kne_file->get_block_count());
956     $fileno++;
957   }
958
959   #Make EV Verwaltungsdatei
960   my $ev_header = $self->make_ev_header($form, $fileno);
961   my $ev_filename = $self->export_path . $evfile;
962   push(@filenames, $evfile);
963   open(EV, ">", $ev_filename) or die "can't open outputfile: EV01\n";
964   print(EV $ev_header);
965
966   foreach my $file (@ed_versionset) {
967     print(EV $file);
968   }
969   close(EV);
970   ###
971
972   $self->add_filenames(@filenames);
973
974   $main::lxdebug->leave_sub();
975
976   return { 'download_token' => $self->download_token, 'filenames' => \@filenames };
977 }
978
979 sub kne_stammdatenexport {
980   $main::lxdebug->enter_sub();
981
982   my ($self) = @_;
983   my $form = $::form;
984
985   $self->get_datev_stamm->{abrechnungsnr} = "99";
986
987   my @filenames;
988
989   my $filename    = "ED00000";
990   my $evfile      = "EV01";
991   my @ed_versionset;
992   my $fileno          = 1;
993   my $i               = 0;
994   my $blockcount      = 1;
995   my $remaining_bytes = 256;
996   my $total_bytes     = 256;
997   my $buchungssatz    = "";
998   $filename++;
999   my $ed_filename = $self->export_path . $filename;
1000   push(@filenames, $filename);
1001   open(ED, ">", $ed_filename) or die "can't open outputfile: $!\n";
1002   my $header = $self->make_kne_data_header($form);
1003   $remaining_bytes -= length($header);
1004
1005   my $fuellzeichen;
1006
1007   my (@where, @values) = ((), ());
1008   if ($self->accnofrom) {
1009     push @where, 'c.accno >= ?';
1010     push @values, $self->accnofrom;
1011   }
1012   if ($self->accnoto) {
1013     push @where, 'c.accno <= ?';
1014     push @values, $self->accnoto;
1015   }
1016
1017   my $where_str = @where ? ' WHERE ' . join(' AND ', map { "($_)" } @where) : '';
1018
1019   my $query     = qq|SELECT c.accno, c.description
1020                      FROM chart c
1021                      $where_str
1022                      ORDER BY c.accno|;
1023
1024   my $sth = $self->dbh->prepare($query);
1025   $sth->execute(@values) || $form->dberror($query);
1026
1027   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1028     if (($remaining_bytes - length("t" . $ref->{'accno'})) <= 6) {
1029       $fuellzeichen = ($blockcount * 256 - length($buchungssatz . $header));
1030       $buchungssatz .= "\x00" x $fuellzeichen;
1031       $blockcount++;
1032       $total_bytes = ($blockcount) * 256;
1033     }
1034     $buchungssatz .= "t" . $ref->{'accno'};
1035     $remaining_bytes = $total_bytes - length($buchungssatz . $header);
1036     $ref->{'description'} =~ s/[^0-9A-Za-z\$\%\&\*\+\-\/]//g;
1037     $ref->{'description'} = substr($ref->{'description'}, 0, 40);
1038     $ref->{'description'} =~ s/\ *$//;
1039
1040     if (
1041         ($remaining_bytes - length("\x1E" . $ref->{'description'} . "\x1C\x79")
1042         ) <= 6
1043       ) {
1044       $fuellzeichen = ($blockcount * 256 - length($buchungssatz . $header));
1045       $buchungssatz .= "\x00" x $fuellzeichen;
1046       $blockcount++;
1047       $total_bytes = ($blockcount) * 256;
1048     }
1049     $buchungssatz .= "\x1E" . $ref->{'description'} . "\x1C\x79";
1050     $remaining_bytes = $total_bytes - length($buchungssatz . $header);
1051   }
1052
1053   $sth->finish;
1054   print(ED $header);
1055   print(ED $buchungssatz);
1056   $fuellzeichen = 256 - (length($header . $buchungssatz . "z") % 256);
1057   my $dateiende = "\x00" x $fuellzeichen;
1058   print(ED "z");
1059   print(ED $dateiende);
1060   close(ED);
1061
1062   #Make EV Verwaltungsdatei
1063   $ed_versionset[0] =
1064     $self->make_ed_versionset($header, $filename, $blockcount);
1065
1066   my $ev_header = $self->make_ev_header($form, $fileno);
1067   my $ev_filename = $self->export_path . $evfile;
1068   push(@filenames, $evfile);
1069   open(EV, ">", $ev_filename) or die "can't open outputfile: EV01\n";
1070   print(EV $ev_header);
1071
1072   foreach my $file (@ed_versionset) {
1073     print(EV $ed_versionset[$file]);
1074   }
1075   close(EV);
1076
1077   $self->add_filenames(@filenames);
1078
1079   $main::lxdebug->leave_sub();
1080
1081   return { 'download_token' => $self->download_token, 'filenames' => \@filenames };
1082 }
1083
1084 sub DESTROY {
1085   clean_temporary_directories();
1086 }
1087
1088 1;
1089
1090 __END__
1091
1092 =encoding utf-8
1093
1094 =head1 NAME
1095
1096 SL::DATEV - kivitendo DATEV Export module
1097
1098 =head1 SYNOPSIS
1099
1100   use SL::DATEV qw(:CONSTANTS);
1101
1102   my $startdate = DateTime->new(year => 2014, month => 9, day => 1);
1103   my $enddate   = DateTime->new(year => 2014, month => 9, day => 31);
1104   my $datev = SL::DATEV->new(
1105     exporttype => DATEV_ET_BUCHUNGEN,
1106     format     => DATEV_FORMAT_KNE,
1107     from       => $startdate,
1108     to         => $enddate,
1109   );
1110
1111   # To only export transactions from a specific trans_id: (from and to are ignored)
1112   my $invoice = SL::DB::Manager::Invoice->find_by( invnumber => '216' );
1113   my $datev = SL::DATEV->new(
1114     exporttype => DATEV_ET_BUCHUNGEN,
1115     format     => DATEV_FORMAT_KNE,
1116     trans_id   => $invoice->trans_id,
1117   );
1118
1119   my $datev = SL::DATEV->new(
1120     exporttype => DATEV_ET_STAMM,
1121     format     => DATEV_FORMAT_KNE,
1122     accnofrom  => $start_account_number,
1123     accnoto    => $end_account_number,
1124   );
1125
1126   # get or set datev stamm
1127   my $hashref = $datev->get_datev_stamm;
1128   $datev->save_datev_stamm($hashref);
1129
1130   # manually clean up temporary directories older than 8 hours
1131   $datev->clean_temporary_directories;
1132
1133   # export
1134   $datev->export;
1135
1136   if ($datev->errors) {
1137     die join "\n", $datev->error;
1138   }
1139
1140   # get relevant data for saving the export:
1141   my $dl_token = $datev->download_token;
1142   my $path     = $datev->export_path;
1143   my @files    = $datev->filenames;
1144
1145   # retrieving an export at a later time
1146   my $datev = SL::DATEV->new(
1147     download_token => $dl_token_from_user,
1148   );
1149
1150   my $path     = $datev->export_path;
1151   my @files    = glob("$path/*");
1152
1153 =head1 DESCRIPTION
1154
1155 This module implements the DATEV export standard. For usage see above.
1156
1157 =head1 FUNCTIONS
1158
1159 =over 4
1160
1161 =item new PARAMS
1162
1163 Generic constructor. See section attributes for information about what to pass.
1164
1165 =item get_datev_stamm
1166
1167 Loads DATEV Stammdaten and returns as hashref.
1168
1169 =item save_datev_stamm HASHREF
1170
1171 Saves DATEV Stammdaten from provided hashref.
1172
1173 =item exporttype
1174
1175 See L<CONSTANTS> for possible values
1176
1177 =item has_exporttype
1178
1179 Returns true if an exporttype has been set. Without exporttype most report functions won't work.
1180
1181 =item format
1182
1183 Specifies the designated format of the export. Currently only KNE export is implemented.
1184
1185 See L<CONSTANTS> for possible values
1186
1187 =item has_format
1188
1189 Returns true if a format has been set. Without format most report functions won't work.
1190
1191 =item download_token
1192
1193 Returns a download token for this DATEV object.
1194
1195 Note: If either a download_token or export_path were set at the creation these are infered, otherwise randomly generated.
1196
1197 =item export_path
1198
1199 Returns an export_path for this DATEV object.
1200
1201 Note: If either a download_token or export_path were set at the creation these are infered, otherwise randomly generated.
1202
1203 =item filenames
1204
1205 Returns a list of filenames generated by this DATEV object. This only works if the files were generated during its lifetime, not if the object was created from a download_token.
1206
1207 =item net_gross_differences
1208
1209 If there were any net gross differences during calculation they will be collected here.
1210
1211 =item sum_net_gross_differences
1212
1213 Sum of all differences.
1214
1215 =item clean_temporary_directories
1216
1217 Forces a garbage collection on previous exports which will delete all exports that are older than 8 hours. It will be automatically called on destruction of the object, but is advised to be called manually before delivering results of an export to the user.
1218
1219 =item errors
1220
1221 Returns a list of errors that occured. If no errors occured, the export was a success.
1222
1223 =item export
1224
1225 Exports data. You have to have set L<exporttype> and L<format> or an error will
1226 occur. OBE exports are currently not implemented.
1227
1228 =back
1229
1230 =head1 ATTRIBUTES
1231
1232 This is a list of attributes set in either the C<new> or a method of the same name.
1233
1234 =over 4
1235
1236 =item dbh
1237
1238 Set a database handle to use in the process. This allows for an export to be
1239 done on a transaction in progress without committing first.
1240
1241 Note: If you don't want this code to commit, simply providing a dbh is not
1242 enough enymore. You'll have to wrap the call into a transaction yourself, so
1243 that the internal transaction does not commit.
1244
1245 =item exporttype
1246
1247 See L<CONSTANTS> for possible values. This MUST be set before export is called.
1248
1249 =item format
1250
1251 See L<CONSTANTS> for possible values. This MUST be set before export is called.
1252
1253 =item download_token
1254
1255 Can be set on creation to retrieve a prior export for download.
1256
1257 =item from
1258
1259 =item to
1260
1261 Set boundary dates for the export. Unless a trans_id is passed these MUST be
1262 set for the export to work.
1263
1264 =item trans_id
1265
1266 To check only one gl/ar/ap transaction, pass the trans_id. The attributes
1267 L<from> and L<to> are currently still needed for the query to be assembled
1268 correctly.
1269
1270 =item accnofrom
1271
1272 =item accnoto
1273
1274 Set boundary account numbers for the export. Only useful for a stammdaten export.
1275
1276 =back
1277
1278 =head1 CONSTANTS
1279
1280 =head2 Supplied to L<exporttype>
1281
1282 =over 4
1283
1284 =item DATEV_ET_BUCHUNGEN
1285
1286 =item DATEV_ET_STAMM
1287
1288 =back
1289
1290 =head2 Supplied to L<format>.
1291
1292 =over 4
1293
1294 =item DATEV_FORMAT_KNE
1295
1296 =item DATEV_FORMAT_OBE
1297
1298 =back
1299
1300 =head1 ERROR HANDLING
1301
1302 This module will die in the following cases:
1303
1304 =over 4
1305
1306 =item *
1307
1308 No or unrecognized exporttype or format was provided for an export
1309
1310 =item *
1311
1312 OBE export was called, which is not yet implemented.
1313
1314 =item *
1315
1316 general I/O errors
1317
1318 =back
1319
1320 Errors that occur during th actual export will be collected in L<errors>. The following types can occur at the moment:
1321
1322 =over 4
1323
1324 =item *
1325
1326 C<Unbalanced Ledger!>. Exactly that, your ledger is unbalanced. Should never occur.
1327
1328 =item *
1329
1330 C<Datev-Export fehlgeschlagen! Bei Transaktion %d (%f).>  This error occurs if a
1331 transaction could not be reliably sorted out, or had rounding errors above the acceptable threshold.
1332
1333 =back
1334
1335 =head1 BUGS AND CAVEATS
1336
1337 =over 4
1338
1339 =item *
1340
1341 Handling of Vollvorlauf is currently not fully implemented. You must provide both from and to in order to get a working export.
1342
1343 =item *
1344
1345 OBE export is currently not implemented.
1346
1347 =back
1348
1349 =head1 TODO
1350
1351 - handling of export_path and download token is a bit dodgy, clean that up.
1352
1353 =head1 SEE ALSO
1354
1355 L<SL::DATEV::KNEFile>
1356
1357 =head1 AUTHORS
1358
1359 Philip Reetz E<lt>p.reetz@linet-services.deE<gt>,
1360
1361 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>,
1362
1363 Jan Büren E<lt>jan@lx-office-hosting.deE<gt>,
1364
1365 Geoffrey Richardson E<lt>information@lx-office-hosting.deE<gt>,
1366
1367 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>,
1368
1369 Stephan Köhler
1370
1371 =cut