und die restlichen .pm Module.
[kivitendo-erp.git] / SL / DATEV.pm
1 #=====================================================================
2 # Lx-Office 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 DATEV;
28
29 use List::Util qw(max);
30
31 use SL::DBUtils;
32 use SL::DATEV::KNEFile;
33 use SL::Taxkeys;
34
35 use Data::Dumper;
36 use File::Path;
37 use Time::HiRes qw(gettimeofday);
38
39 use strict;
40
41 sub _get_export_path {
42   $main::lxdebug->enter_sub();
43
44   my ($a, $b) = gettimeofday();
45   my $path    = get_path_for_download_token("${a}-${b}-${$}");
46
47   mkpath($path) unless (-d $path);
48
49   $main::lxdebug->leave_sub();
50
51   return $path;
52 }
53
54 sub get_path_for_download_token {
55   $main::lxdebug->enter_sub();
56
57   my $token = shift;
58   my $path;
59
60   if ($token =~ m|^(\d+)-(\d+)-(\d+)$|) {
61     $path = "${main::userspath}/datev-export-${1}-${2}-${3}";
62   }
63
64   $main::lxdebug->leave_sub();
65
66   return $path;
67 }
68
69 sub get_download_token_for_path {
70   $main::lxdebug->enter_sub();
71
72   my $path = shift;
73   my $token;
74
75   if ($path =~ m|.*datev-export-(\d+)-(\d+)-(\d+)/?$|) {
76     $token = "${1}-${2}-${3}";
77   }
78
79   $main::lxdebug->leave_sub();
80
81   return $token;
82 }
83
84 sub clean_temporary_directories {
85   $main::lxdebug->enter_sub();
86
87   foreach my $path (glob "${main::userspath}/datev-export-*") {
88     next unless (-d $path);
89
90     my $mtime = (stat($path))[9];
91     next if ((time() - $mtime) < 8 * 60 * 60);
92
93     rmtree $path;
94   }
95
96   $main::lxdebug->leave_sub();
97 }
98
99 sub _fill {
100   $main::lxdebug->enter_sub();
101
102   my $text      = shift;
103   my $field_len = shift;
104   my $fill_char = shift;
105   my $alignment = shift || 'right';
106
107   my $text_len  = length $text;
108
109   if ($field_len < $text_len) {
110     $text = substr $text, 0, $field_len;
111
112   } elsif ($field_len > $text_len) {
113     my $filler = ($fill_char) x ($field_len - $text_len);
114     $text      = $alignment eq 'right' ? $filler . $text : $text . $filler;
115   }
116
117   $main::lxdebug->leave_sub();
118
119   return $text;
120 }
121
122 sub get_datev_stamm {
123   $main::lxdebug->enter_sub();
124
125   my ($self, $myconfig, $form) = @_;
126
127   # connect to database
128   my $dbh = $form->dbconnect($myconfig);
129
130   my $query = qq|SELECT * FROM datev|;
131   my $sth   = $dbh->prepare($query);
132   $sth->execute || $form->dberror($query);
133
134   my $ref = $sth->fetchrow_hashref("NAME_lc");
135
136   map { $form->{$_} = $ref->{$_} } keys %$ref;
137
138   $sth->finish;
139   $dbh->disconnect;
140   $main::lxdebug->leave_sub();
141 }
142
143 sub save_datev_stamm {
144   $main::lxdebug->enter_sub();
145
146   my ($self, $myconfig, $form) = @_;
147
148   # connect to database
149   my $dbh = $form->dbconnect_noauto($myconfig);
150
151   my $query = qq|DELETE FROM datev|;
152   $dbh->do($query) || $form->dberror($query);
153
154   $query = qq|INSERT INTO datev
155               (beraternr, beratername, dfvkz, mandantennr, datentraegernr, abrechnungsnr) VALUES
156               (|
157     . $dbh->quote($form->{beraternr}) . qq|,|
158     . $dbh->quote($form->{beratername}) . qq|,|
159     . $dbh->quote($form->{dfvkz}) . qq|,
160               |
161     . $dbh->quote($form->{mandantennr}) . qq|,|
162     . $dbh->quote($form->{datentraegernr}) . qq|,|
163     . $dbh->quote($form->{abrechnungsnr}) . qq|)|;
164   my $sth = $dbh->prepare($query);
165   $sth->execute || $form->dberror($query);
166   $sth->finish;
167
168   $dbh->commit;
169   $dbh->disconnect;
170   $main::lxdebug->leave_sub();
171 }
172
173 sub kne_export {
174   $main::lxdebug->enter_sub();
175
176   my ($self, $myconfig, $form) = @_;
177   my $result;
178
179   if ($form->{exporttype} == 0) {
180     $result = kne_buchungsexport($myconfig, $form);
181   } else {
182     $result = kne_stammdatenexport($myconfig, $form);
183   }
184
185   $main::lxdebug->leave_sub();
186
187   return $result;
188 }
189
190 sub obe_export {
191   $main::lxdebug->enter_sub();
192
193   my ($self, $myconfig, $form) = @_;
194
195   # connect to database
196   my $dbh = $form->dbconnect_noauto($myconfig);
197   $dbh->commit;
198   $dbh->disconnect;
199   $main::lxdebug->leave_sub();
200 }
201
202 sub get_dates {
203   $main::lxdebug->enter_sub();
204
205   my ($zeitraum, $monat, $quartal, $transdatefrom, $transdateto) = @_;
206   my ($fromto, $jahr, $leap);
207
208   my $form = $main::form;
209
210   $fromto = "transdate >= ";
211
212   my @a = localtime;
213   $a[5] += 1900;
214   $jahr = $a[5];
215   if ($zeitraum eq "monat") {
216   SWITCH: {
217       $monat eq "1" && do {
218         $form->{fromdate} = "1.1.$jahr";
219         $form->{todate}   = "31.1.$jahr";
220         last SWITCH;
221       };
222       $monat eq "2" && do {
223         $form->{fromdate} = "1.2.$jahr";
224
225         #this works from 1901 to 2099, 1900 and 2100 fail.
226         $leap = ($jahr % 4 == 0) ? "29" : "28";
227         $form->{todate} = "$leap.2.$jahr";
228         last SWITCH;
229       };
230       $monat eq "3" && do {
231         $form->{fromdate} = "1.3.$jahr";
232         $form->{todate}   = "31.3.$jahr";
233         last SWITCH;
234       };
235       $monat eq "4" && do {
236         $form->{fromdate} = "1.4.$jahr";
237         $form->{todate}   = "30.4.$jahr";
238         last SWITCH;
239       };
240       $monat eq "5" && do {
241         $form->{fromdate} = "1.5.$jahr";
242         $form->{todate}   = "31.5.$jahr";
243         last SWITCH;
244       };
245       $monat eq "6" && do {
246         $form->{fromdate} = "1.6.$jahr";
247         $form->{todate}   = "30.6.$jahr";
248         last SWITCH;
249       };
250       $monat eq "7" && do {
251         $form->{fromdate} = "1.7.$jahr";
252         $form->{todate}   = "31.7.$jahr";
253         last SWITCH;
254       };
255       $monat eq "8" && do {
256         $form->{fromdate} = "1.8.$jahr";
257         $form->{todate}   = "31.8.$jahr";
258         last SWITCH;
259       };
260       $monat eq "9" && do {
261         $form->{fromdate} = "1.9.$jahr";
262         $form->{todate}   = "30.9.$jahr";
263         last SWITCH;
264       };
265       $monat eq "10" && do {
266         $form->{fromdate} = "1.10.$jahr";
267         $form->{todate}   = "31.10.$jahr";
268         last SWITCH;
269       };
270       $monat eq "11" && do {
271         $form->{fromdate} = "1.11.$jahr";
272         $form->{todate}   = "30.11.$jahr";
273         last SWITCH;
274       };
275       $monat eq "12" && do {
276         $form->{fromdate} = "1.12.$jahr";
277         $form->{todate}   = "31.12.$jahr";
278         last SWITCH;
279       };
280     }
281     $fromto .=
282       "'" . $form->{fromdate} . "' and transdate <= '" . $form->{todate} . "'";
283   }
284
285   elsif ($zeitraum eq "quartal") {
286     if ($quartal == 1) {
287       $fromto .=
288         "'01.01." . $jahr . "' and transdate <= '31.03." . $jahr . "'";
289     } elsif ($quartal == 2) {
290       $fromto .=
291         "'01.04." . $jahr . "' and transdate <= '30.06." . $jahr . "'";
292     } elsif ($quartal == 3) {
293       $fromto .=
294         "'01.07." . $jahr . "' and transdate <= '30.09." . $jahr . "'";
295     } elsif ($quartal == 4) {
296       $fromto .=
297         "'01.10." . $jahr . "' and transdate <= '31.12." . $jahr . "'";
298     }
299   }
300
301   elsif ($zeitraum eq "zeit") {
302     $fromto            .= "'" . $transdatefrom . "' and transdate <= '" . $transdateto . "'";
303     my ($yy, $mm, $dd)  = $main::locale->parse_date(\%main::myconfig, $transdatefrom);
304     $jahr               = $yy;
305   }
306
307   $main::lxdebug->leave_sub();
308
309   return ($fromto, $jahr);
310 }
311
312 sub _sign {
313   my $value = shift;
314
315   return $value < 0 ? -1
316     :    $value > 0 ?  1
317     :                  0;
318 }
319
320 sub _get_transactions {
321   $main::lxdebug->enter_sub();
322
323   my $fromto   =  shift;
324
325   my $myconfig =  \%main::myconfig;
326   my $form     =  $main::form;
327
328   my $dbh      =  $form->get_standard_dbh($myconfig);
329
330   my ($notsplitindex);
331   my @errors   = ();
332
333   $fromto      =~ s/transdate/ac\.transdate/g;
334
335   my $taxkeys  = Taxkeys->new();
336   my $filter   = '';            # Useful for debugging purposes
337
338   my %all_taxchart_ids = selectall_as_map($form, $dbh, qq|SELECT DISTINCT chart_id, TRUE AS is_set FROM tax|, 'chart_id', 'is_set');
339
340   my $query    =
341     qq|SELECT ac.acc_trans_id, ac.transdate, ac.trans_id,ar.id, ac.amount, ac.taxkey,
342          ar.invnumber, ar.duedate, ar.amount as umsatz,
343          ct.name,
344          c.accno, c.taxkey_id as charttax, c.datevautomatik, c.id, c.link,
345          ar.invoice
346        FROM acc_trans ac
347        LEFT JOIN ar          ON (ac.trans_id    = ar.id)
348        LEFT JOIN customer ct ON (ar.customer_id = ct.id)
349        LEFT JOIN chart c     ON (ac.chart_id    = c.id)
350        WHERE (ar.id IS NOT NULL)
351          AND $fromto
352          $filter
353
354        UNION ALL
355
356        SELECT ac.acc_trans_id, ac.transdate, ac.trans_id,ap.id, ac.amount, ac.taxkey,
357          ap.invnumber, ap.duedate, ap.amount as umsatz,
358          ct.name,
359          c.accno, c.taxkey_id as charttax, c.datevautomatik, c.id, c.link,
360          ap.invoice
361        FROM acc_trans ac
362        LEFT JOIN ap        ON (ac.trans_id  = ap.id)
363        LEFT JOIN vendor ct ON (ap.vendor_id = ct.id)
364        LEFT JOIN chart c   ON (ac.chart_id  = c.id)
365        WHERE (ap.id IS NOT NULL)
366          AND $fromto
367          $filter
368
369        UNION ALL
370
371        SELECT ac.acc_trans_id, ac.transdate, ac.trans_id,gl.id, ac.amount, ac.taxkey,
372          gl.reference AS invnumber, gl.transdate AS duedate, ac.amount as umsatz,
373          gl.description AS name,
374          c.accno, c.taxkey_id as charttax, c.datevautomatik, c.id, c.link,
375          FALSE AS invoice
376        FROM acc_trans ac
377        LEFT JOIN gl      ON (ac.trans_id  = gl.id)
378        LEFT JOIN chart c ON (ac.chart_id  = c.id)
379        WHERE (gl.id IS NOT NULL)
380          AND $fromto
381          $filter
382
383        ORDER BY trans_id, acc_trans_id|;
384
385   my $sth = prepare_execute_query($form, $dbh, $query);
386
387   my $counter = 0;
388   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
389     $counter++;
390     if (($counter % 500) == 0) {
391       print("$counter ");
392     }
393
394     my $trans    = [ $ref ];
395
396     my $count    = $ref->{amount};
397     my $firstrun = 1;
398
399     while (abs($count) > 0.01 || $firstrun) {
400       my $ref2 = $sth->fetchrow_hashref("NAME_lc");
401       last unless ($ref2);
402
403       if ($ref2->{trans_id} != $trans->[0]->{trans_id}) {
404         $form->error("Unbalanced ledger! old trans_id " . $trans->[0]->{trans_id} . " new trans_id " . $ref2->{trans_id} . " count $count");
405         exit 1;
406       }
407
408       push @{ $trans }, $ref2;
409
410       $count    += $ref2->{amount};
411       $firstrun  = 0;
412     }
413
414     foreach my $i (0 .. scalar(@{ $trans }) - 1) {
415       my $ref        = $trans->[$i];
416       my $prev_ref   = 0 < $i ? $trans->[$i - 1] : undef;
417       if (   $all_taxchart_ids{$ref->{id}}
418           && ($ref->{link} =~ m/(?:AP_tax|AR_tax)/)
419           && (   ($prev_ref && $prev_ref->{taxkey} && (_sign($ref->{amount}) == _sign($prev_ref->{amount})))
420               || $ref->{invoice})) {
421         $ref->{is_tax} = 1;
422       }
423
424       if (   !$ref->{invoice}
425           &&  $ref->{is_tax}
426           && !($prev_ref->{is_tax})
427           &&  (_sign($ref->{amount}) == _sign($prev_ref->{amount}))) {
428         $trans->[$i - 1]->{tax_amount} = $ref->{amount};
429       }
430     }
431
432     my %taxid_taxkeys = ();
433     my $absumsatz     = 0;
434     if (scalar(@{$trans}) <= 2) {
435       push @{ $form->{DATEV} }, $trans;
436       next;
437     }
438
439     for my $j (0 .. (scalar(@{$trans}) - 1)) {
440       if (abs($trans->[$j]->{'amount'}) > abs($absumsatz)) {
441         $absumsatz     = $trans->[$j]->{'amount'};
442         $notsplitindex = $j;
443       }
444     }
445
446     my $ml             = ($trans->[0]->{'umsatz'} > 0) ? 1 : -1;
447     my $rounding_error = 0;
448
449     for my $j (0 .. (scalar(@{$trans}) - 1)) {
450       if (   ($j != $notsplitindex)
451           && !$trans->[$j]->{is_tax}
452           && (   $trans->[$j]->{'taxkey'} eq ""
453               || $trans->[$j]->{'taxkey'} eq "0"
454               || $trans->[$j]->{'taxkey'} eq "1"
455               || $trans->[$j]->{'taxkey'} eq "10"
456               || $trans->[$j]->{'taxkey'} eq "11")) {
457         my %new_trans = ();
458         map { $new_trans{$_} = $trans->[$notsplitindex]->{$_}; } keys %{ $trans->[$notsplitindex] };
459
460         $absumsatz               += $trans->[$j]->{'amount'};
461         $new_trans{'amount'}      = $trans->[$j]->{'amount'} * (-1);
462         $new_trans{'umsatz'}      = abs($trans->[$j]->{'amount'}) * $ml;
463         $trans->[$j]->{'umsatz'}  = abs($trans->[$j]->{'amount'}) * $ml;
464
465         push @{ $form->{DATEV} }, [ \%new_trans, $trans->[$j] ];
466
467       } elsif (($j != $notsplitindex) && !$trans->[$j]->{is_tax}) {
468         my %tax_info = $taxkeys->get_full_tax_info('transdate' => $trans->[$j]->{transdate});
469
470         my %new_trans = ();
471         map { $new_trans{$_} = $trans->[$notsplitindex]->{$_}; } keys %{ $trans->[$notsplitindex] };
472
473         my $tax_rate              = $tax_info{taxkeys}->{ $trans->[$j]->{'taxkey'} }->{taxrate};
474         $new_trans{'net_amount'}  = $trans->[$j]->{'amount'} * -1;
475         $new_trans{'tax_rate'}    = 1 + $tax_rate;
476
477         if (!$trans->[$j]->{'invoice'}) {
478           $new_trans{'amount'}      = $form->round_amount(-1 * ($trans->[$j]->{amount} + $trans->[$j]->{tax_amount}), 2);
479           $new_trans{'umsatz'}      = abs($new_trans{'amount'}) * $ml;
480           $trans->[$j]->{'umsatz'}  = $new_trans{'umsatz'};
481           $absumsatz               += -1 * $new_trans{'amount'};
482
483         } else {
484           my $unrounded             = $trans->[$j]->{'amount'} * (1 + $tax_rate) * -1; # + $rounding_error;
485           my $rounded               = $form->round_amount($unrounded, 2);
486           $rounding_error          += $unrounded - $rounded;
487           $new_trans{'amount'}      = $rounded;
488           $new_trans{'umsatz'}      = abs($form->round_amount(($trans->[$j]->{'amount'} * (1 + $tax_rate)), 2)) * $ml;
489           $trans->[$j]->{'umsatz'}  = abs($form->round_amount(($trans->[$j]->{'amount'} * (1 + $tax_rate)), 2)) * $ml;
490           $absumsatz               += $form->round_amount($trans->[$j]->{'amount'} + $trans->[$j]->{'amount'} * $tax_rate, 2);
491         }
492
493         push @{ $form->{DATEV} }, [ \%new_trans, $trans->[$j] ];
494       }
495     }
496
497     my $idx        = 0;
498     my $correction = 0;
499     our @taxed;          # most likely defunct
500     while (abs($absumsatz) >= 0.01) {
501       if ($idx >= scalar @taxed) {
502         last if (!$correction);
503
504         $correction = 0;
505         $idx        = 0;
506       }
507
508       my $transaction = $taxed[$idx]->[0];
509
510       my $old_amount     = $transaction->{amount};
511       my $old_correction = $correction;
512       my @possible_diffs;
513
514       if (!$transaction->{diff}) {
515         @possible_diffs = (0.01, -0.01);
516       } else {
517         @possible_diffs = ($transaction->{diff});
518       }
519
520       foreach my $diff (@possible_diffs) {
521         my $net_amount = $form->round_amount(($transaction->{amount} + $diff) / $transaction->{tax_rate}, 2);
522         next if ($net_amount != $transaction->{net_amount});
523
524         $transaction->{diff}    = $diff;
525         $transaction->{amount} += $diff;
526         $transaction->{umsatz} += $diff;
527         $absumsatz             -= $diff;
528         $correction             = 1;
529
530         last;
531       }
532
533       $idx++;
534     }
535
536     if (abs($absumsatz) >= 0.01) {
537       push @errors, "Datev-Export fehlgeschlagen! Bei Transaktion $trans->[0]->{trans_id} ($absumsatz, Rundungsfehler $rounding_error)\n";
538     }
539   }
540
541   $sth->finish();
542
543   $form->error(join("<br>\n", @errors)) if (@errors);
544
545   $main::lxdebug->leave_sub();
546 }
547
548 sub make_kne_data_header {
549   $main::lxdebug->enter_sub();
550
551   my ($myconfig, $form, $fromto, $start_jahr) = @_;
552   my ($primanota);
553
554   my $jahr = $start_jahr;
555   if (!$jahr) {
556     my @a = localtime;
557     $jahr = $a[5];
558   }
559
560   #Header
561   my $header  = "\x1D\x181";
562   $header    .= _fill($form->{datentraegernr}, 3, ' ', 'left');
563   $header    .= ($fromto) ? "11" : "13"; # Anwendungsnummer
564   $header    .= _fill($form->{dfvkz}, 2, '0');
565   $header    .= _fill($form->{beraternr}, 7, '0');
566   $header    .= _fill($form->{mandantennr}, 5, '0');
567   $header    .= _fill($form->{abrechnungsnr} . $jahr, 6, '0');
568
569   $fromto         =~ s/transdate|>=|and|\'|<=//g;
570   my ($from, $to) =  split /   /, $fromto;
571   $from           =~ s/ //g;
572   $to             =~ s/ //g;
573
574   if ($from ne "") {
575     my ($fday, $fmonth, $fyear) = split(/\./, $from);
576     if (length($fmonth) < 2) {
577       $fmonth = "0" . $fmonth;
578     }
579     if (length($fday) < 2) {
580       $fday = "0" . $fday;
581     }
582     $from = $fday . $fmonth . substr($fyear, -2, 2);
583   } else {
584     $from = "";
585   }
586
587   $header .= $from;
588
589   if ($to ne "") {
590     my ($tday, $tmonth, $tyear) = split(/\./, $to);
591     if (length($tmonth) < 2) {
592       $tmonth = "0" . $tmonth;
593     }
594     if (length($tday) < 2) {
595       $tday = "0" . $tday;
596     }
597     $to = $tday . $tmonth . substr($tyear, -2, 2);
598   } else {
599     $to = "";
600   }
601   $header .= $to;
602
603   if ($fromto ne "") {
604     $primanota = "001";
605     $header .= $primanota;
606   }
607
608   $header .= _fill($form->{passwort}, 4, '0');
609   $header .= " " x 16;       # Anwendungsinfo
610   $header .= " " x 16;       # Inputinfo
611   $header .= "\x79";
612
613   #Versionssatz
614   my $versionssatz  = $form->{exporttype} == 0 ? "\xB5" . "1," : "\xB6" . "1,";
615
616   my $dbh           = $form->get_standard_dbh($myconfig);
617   my $query         = qq|SELECT accno FROM chart LIMIT 1|;
618   my $ref           = selectfirst_hashref_query($form, $dbh, $query);
619
620   $versionssatz    .= length $ref->{accno};
621   $versionssatz    .= ",";
622   $versionssatz    .= length $ref->{accno};
623   $versionssatz    .= ",SELF" . "\x1C\x79";
624
625   $header          .= $versionssatz;
626
627   $main::lxdebug->leave_sub();
628
629   return $header;
630 }
631
632 sub datetofour {
633   $main::lxdebug->enter_sub();
634
635   my ($date, $six) = @_;
636
637   my ($day, $month, $year) = split(/\./, $date);
638
639   if ($day =~ /^0/) {
640     $day = substr($day, 1, 1);
641   }
642   if (length($month) < 2) {
643     $month = "0" . $month;
644   }
645   if (length($year) > 2) {
646     $year = substr($year, -2, 2);
647   }
648
649   if ($six) {
650     $date = $day . $month . $year;
651   } else {
652     $date = $day . $month;
653   }
654
655   $main::lxdebug->leave_sub();
656
657   return $date;
658 }
659
660 sub trim_leading_zeroes {
661   my $str = shift;
662
663   $str =~ s/^0+//g;
664
665   return $str;
666 }
667
668 sub make_ed_versionset {
669   $main::lxdebug->enter_sub();
670
671   my ($header, $filename, $blockcount, $fromto) = @_;
672
673   my $versionset  = "V" . substr($filename, 2, 5);
674   $versionset    .= substr($header, 6, 22);
675
676   if ($fromto ne "") {
677     $versionset .= "0000" . substr($header, 28, 19);
678   } else {
679     my $datum = " " x 16;
680     $versionset .= $datum . "001" . substr($header, 28, 4);
681   }
682
683   $versionset .= _fill($blockcount, 5, '0');
684   $versionset .= "001";
685   $versionset .= " 1";
686   $versionset .= substr($header, -12, 10) . "    ";
687   $versionset .= " " x 53;
688
689   $main::lxdebug->leave_sub();
690
691   return $versionset;
692 }
693
694 sub make_ev_header {
695   $main::lxdebug->enter_sub();
696
697   my ($form, $fileno) = @_;
698
699   my $ev_header  = _fill($form->{datentraegernr}, 3, ' ', 'left');
700   $ev_header    .= "   ";
701   $ev_header    .= _fill($form->{beraternr}, 7, ' ', 'left');
702   $ev_header    .= _fill($form->{beratername}, 9, ' ', 'left');
703   $ev_header    .= " ";
704   $ev_header    .= (_fill($fileno, 5, '0')) x 2;
705   $ev_header    .= " " x 95;
706
707   $main::lxdebug->leave_sub();
708
709   return $ev_header;
710 }
711
712 sub kne_buchungsexport {
713   $main::lxdebug->enter_sub();
714
715   my ($myconfig, $form) = @_;
716
717   my @filenames;
718
719   my $export_path = _get_export_path() . "/";
720   my $filename    = "ED00000";
721   my $evfile      = "EV01";
722   my @ed_versionset;
723   my $fileno = 0;
724
725   $form->header;
726   print qq|
727   <html>
728   <body>Export in Bearbeitung<br>
729   Buchungss&auml;tze verarbeitet:
730 |;
731
732   my ($fromto, $start_jahr) =
733     &get_dates($form->{zeitraum}, $form->{monat},
734                $form->{quartal},  $form->{transdatefrom},
735                $form->{transdateto});
736   _get_transactions($fromto);
737   my $counter = 0;
738   print qq|<br>2. Durchlauf:|;
739   while (scalar(@{ $form->{DATEV} })) {
740     my $umsatzsumme = 0;
741     $filename++;
742     my $ed_filename = $export_path . $filename;
743     push(@filenames, $filename);
744     my $header = &make_kne_data_header($myconfig, $form, $fromto, $start_jahr);
745
746     my $kne_file = SL::DATEV::KNEFile->new();
747     $kne_file->add_block($header);
748
749     while (scalar(@{ $form->{DATEV} }) > 0) {
750       my $transaction = shift @{ $form->{DATEV} };
751       my $trans_lines = scalar(@{$transaction});
752       $counter++;
753       if (($counter % 500) == 0) {
754         print("$counter ");
755       }
756
757       my $umsatz         = 0;
758       my $gegenkonto     = "";
759       my $konto          = "";
760       my $belegfeld1     = "";
761       my $datum          = "";
762       my $waehrung       = "";
763       my $buchungstext   = "";
764       my $belegfeld2     = "";
765       my $datevautomatik = 0;
766       my $taxkey         = 0;
767       my $charttax       = 0;
768       my ($haben, $soll);
769       my $iconv          = $main::locale->{iconv_iso8859};
770       my %umlaute = ($iconv->convert('ä') => 'ae',
771                      $iconv->convert('ö') => 'oe',
772                      $iconv->convert('ü') => 'ue',
773                      $iconv->convert('Ä') => 'Ae',
774                      $iconv->convert('Ö') => 'Oe',
775                      $iconv->convert('Ü') => 'Ue',
776                      $iconv->convert('ß') => 'sz');
777       for (my $i = 0; $i < $trans_lines; $i++) {
778         if ($trans_lines == 2) {
779           if (abs($transaction->[$i]->{'amount'}) > abs($umsatz)) {
780             $umsatz = $transaction->[$i]->{'amount'};
781           }
782         } else {
783           if (abs($transaction->[$i]->{'umsatz'}) > abs($umsatz)) {
784             $umsatz = $transaction->[$i]->{'umsatz'};
785           }
786         }
787         if ($transaction->[$i]->{'datevautomatik'}) {
788           $datevautomatik = 1;
789         }
790         if ($transaction->[$i]->{'taxkey'}) {
791           $taxkey = $transaction->[$i]->{'taxkey'};
792         }
793         if ($transaction->[$i]->{'charttax'}) {
794           $charttax = $transaction->[$i]->{'charttax'};
795         }
796         if ($transaction->[$i]->{'amount'} > 0) {
797           $haben = $i;
798         } else {
799           $soll = $i;
800         }
801       }
802
803       # Umwandlung von Umlauten und Sonderzeichen in erlaubte Zeichen bei Textfeldern
804       foreach my $umlaut (keys(%umlaute)) {
805         $transaction->[$haben]->{'invnumber'} =~ s/${umlaut}/${umlaute{$umlaut}}/g;
806         $transaction->[$haben]->{'name'}      =~ s/${umlaut}/${umlaute{$umlaut}}/g;
807       }
808
809       $transaction->[$haben]->{'invnumber'} =~ s/[^0-9A-Za-z\$\%\&\*\+\-\/]//g;
810       $transaction->[$haben]->{'name'}      =~ s/[^0-9A-Za-z\$\%\&\*\+\-\ \/]//g;
811
812       $transaction->[$haben]->{'invnumber'} =  substr($transaction->[$haben]->{'invnumber'}, 0, 12);
813       $transaction->[$haben]->{'name'}      =  substr($transaction->[$haben]->{'name'}, 0, 30);
814       $transaction->[$haben]->{'invnumber'} =~ s/\ *$//;
815       $transaction->[$haben]->{'name'}      =~ s/\ *$//;
816
817       if ($trans_lines >= 2) {
818
819         $gegenkonto = "a" . trim_leading_zeroes($transaction->[$haben]->{'accno'});
820         $konto      = "e" . trim_leading_zeroes($transaction->[$soll]->{'accno'});
821         if ($transaction->[$haben]->{'invnumber'} ne "") {
822           $belegfeld1 = "\xBD" . $transaction->[$haben]->{'invnumber'} . "\x1C";
823         }
824         $datum = "d";
825         $datum .= &datetofour($transaction->[$haben]->{'transdate'}, 0);
826         $waehrung = "\xB3" . "EUR" . "\x1C";
827         if ($transaction->[$haben]->{'name'} ne "") {
828           $buchungstext = "\x1E" . $transaction->[$haben]->{'name'} . "\x1C";
829         }
830         if ($transaction->[$haben]->{'duedate'} ne "") {
831           $belegfeld2 = "\xBE" . &datetofour($transaction->[$haben]->{'duedate'}, 1) . "\x1C";
832         }
833       }
834
835       $umsatz       = $kne_file->format_amount(abs($umsatz), 0);
836       $umsatzsumme += $umsatz;
837       $kne_file->add_block("+" . $umsatz);
838
839       if (   ( $datevautomatik || $taxkey)
840           && (!$datevautomatik || ($datevautomatik && ($charttax ne $taxkey)))) {
841 #         $kne_file->add_block("\x6C" . (!$datevautomatik ? $taxkey : "4"));
842         $kne_file->add_block("\x6C${taxkey}");
843       }
844
845       $kne_file->add_block($gegenkonto);
846       $kne_file->add_block($belegfeld1);
847       $kne_file->add_block($belegfeld2);
848       $kne_file->add_block($datum);
849       $kne_file->add_block($konto);
850       $kne_file->add_block($buchungstext);
851       $kne_file->add_block($waehrung . "\x79");
852     }
853
854     my $mandantenendsumme = "x" . $kne_file->format_amount($umsatzsumme / 100.0, 14) . "\x79\x7a";
855
856     $kne_file->add_block($mandantenendsumme);
857     $kne_file->flush();
858
859     open(ED, "> $ed_filename") or die "can't open outputfile: $!\n";
860     print(ED $kne_file->get_data());
861     close(ED);
862
863     $ed_versionset[$fileno] = &make_ed_versionset($header, $filename, $kne_file->get_block_count(), $fromto);
864     $fileno++;
865   }
866
867   #Make EV Verwaltungsdatei
868   my $ev_header = &make_ev_header($form, $fileno);
869   my $ev_filename = $export_path . $evfile;
870   push(@filenames, $evfile);
871   open(EV, "> $ev_filename") or die "can't open outputfile: EV01\n";
872   print(EV $ev_header);
873
874   foreach my $file (@ed_versionset) {
875     print(EV $ed_versionset[$file]);
876   }
877   close(EV);
878   print qq|<br>Done. <br>
879 |;
880   ###
881   $main::lxdebug->leave_sub();
882
883   return { 'download_token' => get_download_token_for_path($export_path), 'filenames' => \@filenames };
884 }
885
886 sub kne_stammdatenexport {
887   $main::lxdebug->enter_sub();
888
889   my ($myconfig, $form) = @_;
890   $form->{abrechnungsnr} = "99";
891
892   $form->header;
893   print qq|
894   <html>
895   <body>Export in Bearbeitung<br>
896 |;
897
898   my @filenames;
899
900   my $export_path = _get_export_path() . "/";
901   my $filename    = "ED00000";
902   my $evfile      = "EV01";
903   my @ed_versionset;
904   my $fileno          = 1;
905   my $i               = 0;
906   my $blockcount      = 1;
907   my $remaining_bytes = 256;
908   my $total_bytes     = 256;
909   my $buchungssatz    = "";
910   $filename++;
911   my $ed_filename = $export_path . $filename;
912   push(@filenames, $filename);
913   open(ED, "> $ed_filename") or die "can't open outputfile: $!\n";
914   my $header = &make_kne_data_header($myconfig, $form, "");
915   $remaining_bytes -= length($header);
916
917   my $fuellzeichen;
918   our $fromto;
919
920   # connect to database
921   my $dbh = $form->dbconnect($myconfig);
922
923   my (@where, @values) = ((), ());
924   if ($form->{accnofrom}) {
925     push @where, 'c.accno >= ?';
926     push @values, $form->{accnofrom};
927   }
928   if ($form->{accnoto}) {
929     push @where, 'c.accno <= ?';
930     push @values, $form->{accnoto};
931   }
932
933   my $where_str = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (scalar @where);
934
935   my $query     = qq|SELECT c.accno, c.description
936                      FROM chart c
937                      $where_str
938                      ORDER BY c.accno|;
939
940   my $sth = $dbh->prepare($query);
941   $sth->execute(@values) || $form->dberror($query);
942
943   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
944     if (($remaining_bytes - length("t" . $ref->{'accno'})) <= 6) {
945       $fuellzeichen = ($blockcount * 256 - length($buchungssatz . $header));
946       $buchungssatz .= "\x00" x $fuellzeichen;
947       $blockcount++;
948       $total_bytes = ($blockcount) * 256;
949     }
950     $buchungssatz .= "t" . $ref->{'accno'};
951     $remaining_bytes = $total_bytes - length($buchungssatz . $header);
952     $ref->{'description'} =~ s/[^0-9A-Za-z\$\%\&\*\+\-\/]//g;
953     $ref->{'description'} = substr($ref->{'description'}, 0, 40);
954     $ref->{'description'} =~ s/\ *$//;
955
956     if (
957         ($remaining_bytes - length("\x1E" . $ref->{'description'} . "\x1C\x79")
958         ) <= 6
959       ) {
960       $fuellzeichen = ($blockcount * 256 - length($buchungssatz . $header));
961       $buchungssatz .= "\x00" x $fuellzeichen;
962       $blockcount++;
963       $total_bytes = ($blockcount) * 256;
964     }
965     $buchungssatz .= "\x1E" . $ref->{'description'} . "\x1C\x79";
966     $remaining_bytes = $total_bytes - length($buchungssatz . $header);
967   }
968
969   $sth->finish;
970   print(ED $header);
971   print(ED $buchungssatz);
972   $fuellzeichen = 256 - (length($header . $buchungssatz . "z") % 256);
973   my $dateiende = "\x00" x $fuellzeichen;
974   print(ED "z");
975   print(ED $dateiende);
976   close(ED);
977
978   #Make EV Verwaltungsdatei
979   $ed_versionset[0] =
980     &make_ed_versionset($header, $filename, $blockcount, $fromto);
981
982   my $ev_header = &make_ev_header($form, $fileno);
983   my $ev_filename = $export_path . $evfile;
984   push(@filenames, $evfile);
985   open(EV, "> $ev_filename") or die "can't open outputfile: EV01\n";
986   print(EV $ev_header);
987
988   foreach my $file (@ed_versionset) {
989     print(EV $ed_versionset[$file]);
990   }
991   close(EV);
992
993   $dbh->disconnect;
994   ###
995
996   print qq|<br>Done. <br>
997 |;
998
999   $main::lxdebug->leave_sub();
1000
1001   return { 'download_token' => get_download_token_for_path($export_path), 'filenames' => \@filenames };
1002 }
1003
1004 1;