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