8e1ba7623d469f8ec153894be381a501ea6dadf1
[kivitendo-erp.git] / SL / USTVA.pm
1 #=====================================================================
2 # kivitendo ERP
3 # Copyright (c) 2004 by Udo Spallek, Aachen
4 #
5 #  Author: Udo Spallek
6 #   Email: udono@gmx.net
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 # Utilities for ustva
24 #=====================================================================
25
26 package USTVA;
27
28 use List::Util qw(first);
29
30 use SL::DB;
31 use SL::DBUtils;
32 use SL::DB::Default;
33 use SL::DB::Finanzamt;
34
35 use utf8;
36 use strict;
37
38 my @tax_office_information = (
39   { 'id' =>  8, 'name' => 'Baden-Württemberg',      'taxbird_nr' => '1',  'elster_format' => 'FFBBB/UUUUP',  },
40   { 'id' =>  9, 'name' => 'Bayern',                 'taxbird_nr' => '2',  'elster_format' => 'FFF/BBB/UUUUP', },
41   { 'id' => 11, 'name' => 'Berlin',                 'taxbird_nr' => '3',  'elster_format' => 'FF/BBB/UUUUP',  },
42   { 'id' => 12, 'name' => 'Brandenburg',            'taxbird_nr' => '4',  'elster_format' => 'FFF/BBB/UUUUP', },
43   { 'id' =>  4, 'name' => 'Bremen',                 'taxbird_nr' => '5',  'elster_format' => 'FF BBB UUUUP',  },
44   { 'id' =>  2, 'name' => 'Hamburg',                'taxbird_nr' => '6',  'elster_format' => 'FF/BBB/UUUUP',  },
45   { 'id' =>  6, 'name' => 'Hessen',                 'taxbird_nr' => '7',  'elster_format' => '0FF BBB UUUUP', },
46   { 'id' => 13, 'name' => 'Mecklenburg-Vorpommern', 'taxbird_nr' => '8',  'elster_format' => 'FFF/BBB/UUUUP', },
47   { 'id' =>  3, 'name' => 'Niedersachsen',          'taxbird_nr' => '9',  'elster_format' => 'FF/BBB/UUUUP',  },
48   { 'id' =>  5, 'name' => 'Nordrhein-Westfalen',    'taxbird_nr' => '10', 'elster_format' => 'FFF/BBBB/UUUP', },
49   { 'id' =>  7, 'name' => 'Rheinland-Pfalz',        'taxbird_nr' => '11', 'elster_format' => 'FF/BBB/UUUUP', },
50   { 'id' => 10, 'name' => 'Saarland',               'taxbird_nr' => '12', 'elster_format' => 'FFF/BBB/UUUUP', },
51   { 'id' => 14, 'name' => 'Sachsen',                'taxbird_nr' => '13', 'elster_format' => 'FFF/BBB/UUUUP', },
52   { 'id' => 15, 'name' => 'Sachsen-Anhalt',         'taxbird_nr' => '14', 'elster_format' => 'FFF/BBB/UUUUP', },
53   { 'id' =>  1, 'name' => 'Schleswig-Holstein',     'taxbird_nr' => '15', 'elster_format' => 'FF BBB UUUUP',  },
54   { 'id' => 16, 'name' => 'Thüringen',              'taxbird_nr' => '16', 'elster_format' => 'FFF/BBB/UUUUP', },
55   );
56
57   my @fiamt_config = qw(taxnumber fa_bufa_nr fa_dauerfrist fa_steuerberater_city fa_steuerberater_name
58   fa_steuerberater_street fa_steuerberater_tel fa_voranmeld);
59
60   my @fiamt_finanzamt = qw(
61     fa_land_nr          fa_bufa_nr            fa_name             fa_strasse
62     fa_plz              fa_ort                fa_telefon          fa_fax
63     fa_plz_grosskunden  fa_plz_postfach       fa_postfach
64     fa_blz_1 fa_kontonummer_1 fa_bankbezeichnung_1
65     fa_blz_2 fa_kontonummer_2 fa_bankbezeichnung_2 fa_oeffnungszeiten
66     fa_email fa_internet);
67
68
69 sub new {
70   my $type = shift;
71
72   my $self = {};
73
74   bless $self, $type;
75
76   $self->_init(@_);
77
78   return $self;
79 }
80
81 sub _init {
82   my $self = shift;
83
84   $self->{tax_office_information} = [];
85
86   foreach (@tax_office_information) {
87     my $entry      = \%{ $_ };
88     $entry->{name} = $::locale->{iconv_utf8}->convert($entry->{name});
89     push @{ $self->{tax_office_information} }, $entry;
90   }
91 }
92
93 sub get_coa {
94
95   my ( $self, $form ) = @_;
96
97   my $coa = $::instance_conf->get_coa;
98   $form->{coa} = $coa;
99   $form->{"COA_$coa"} = '1';
100   $form->{COA_Germany} = '1' if ($coa =~ m/^germany/i);
101
102   return;
103 }
104
105
106 sub report_variables {
107   # Get all positions for taxreport out of the database
108   # Needs Databaseupdate Pg-upgrade2/USTVA_abstraction.pl
109
110   my ( $self,
111        $arg_ref) = @_;
112
113   my $myconfig   = $arg_ref->{myconfig};
114   my $form       = $arg_ref->{form};
115   my $type       = $arg_ref->{type}; # 'paied' || 'received' || ''
116   my $attribute  = $arg_ref->{attribute}; #
117   my $dec_places = (defined $arg_ref->{dec_places}) ? $arg_ref->{dec_places}:undef;
118
119   my $where_type = $type ? "AND tax.report_headings.type = '$type'" : '';
120   my $where_dcp  = defined $dec_places ? "AND tax.report_variables.dec_places = '$dec_places'" : '';
121
122   my $query = qq|
123     SELECT $attribute
124     FROM tax.report_variables
125     LEFT JOIN tax.report_headings
126       ON (tax.report_variables.heading_id = tax.report_headings.id)
127     WHERE 1=1
128     $where_type
129     $where_dcp
130   |;
131
132   my @positions;
133
134   SL::DB->client->with_transaction(sub {
135     my $dbh = SL::DB->client->dbh;
136     my $sth = $dbh->prepare($query);
137
138     $sth->execute() || $form->dberror($query);
139
140     while ( my $row_ref = $sth->fetchrow_arrayref() ) {
141       push @positions, @$row_ref;  # Copy the array contents
142     }
143
144     $sth->finish;
145     1;
146   }) or do { die SL::DB->client->error };
147
148   return @positions;
149 }
150
151
152 sub steuernummer_input {
153   $main::lxdebug->enter_sub();
154
155   my ($self, $elsterland, $elsterFFFF, $steuernummer) = @_;
156   our ($elster_FFFF, $elster_land);
157
158   my $steuernummer_input = '';
159
160   $elster_land  = $elsterland;
161   $elster_FFFF  = $elsterFFFF;
162   $steuernummer = '0000000000' if ($steuernummer eq '');
163
164   # $steuernummer formatieren (nur Zahlen) -> $stnr
165   my $stnr = $steuernummer;
166   $stnr =~ s/\D+//g;
167
168   #Pattern description Elstersteuernummer
169
170   #split the pattern
171   my $tax_office     = first { $_->{id} eq $elster_land } @{ $self->{tax_office_information} };
172   my $elster_pattern = $tax_office->{elster_format};
173  # $::lxdebug->message(LXDebug->DEBUG2, "stnr=".$stnr." elster_FFFF=".$elster_FFFF.
174  #                     " pattern=".$elster_pattern." land=".$elster_land);
175   my @elster_pattern = split(' ', $elster_pattern);
176   my $delimiter1      = ' ';
177   my $delimiter2      = ' ';
178   my $patterncount   = @elster_pattern;
179   if ($patterncount < 2) {
180     @elster_pattern = ();
181     @elster_pattern = split('/', $elster_pattern);
182     $delimiter1      = '/';
183     $delimiter2      = '/';
184     $patterncount   = @elster_pattern;
185     if ($patterncount < 2) {
186         @elster_pattern = ();
187         @elster_pattern = split(' ', $elster_pattern);
188         $delimiter1      = ' ';
189         $delimiter2      = ' ';
190         $patterncount   = @elster_pattern;
191     }
192   }
193
194   # no we have an array of patternparts and a delimiter
195   # create the first automated and fixed part and delimiter
196
197   $steuernummer_input .= qq|<b><font size="+1">|;
198   my $part = '';
199 #  $::lxdebug->message(LXDebug->DEBUG2, "pattern0=".$elster_pattern[0]);
200 SWITCH: {
201     $elster_pattern[0] eq 'FFF' && do {
202       $part = substr($elster_FFFF, 1, 4);
203       $steuernummer_input .= qq|$part|;
204       last SWITCH;
205     };
206     $elster_pattern[0] eq '0FF' && do {
207       $part = '0' . substr($elster_FFFF, 2, 4);
208       $steuernummer_input .= qq|$part|;
209       last SWITCH;
210     };
211     $elster_pattern[0] eq 'FFBBB' && do {
212       $part = substr($elster_FFFF, 2, 4);
213       $steuernummer_input .= qq|$part|;
214       $delimiter1 = '';
215       $patterncount++ ;
216       # Sonderfall BW
217       @elster_pattern = ('FF','BBB','UUUUP');
218       last SWITCH;
219     };
220     $elster_pattern[0] eq 'FF' && do {
221       $part = substr($elster_FFFF, 2, 4);
222       $steuernummer_input .= qq|$part|;
223       last SWITCH;
224     };
225     1 == 1 && do {
226       $steuernummer_input .= qq|Fehler!|;
227       last SWITCH;
228     };
229   }
230
231   #now the rest of the Steuernummer ...
232   $steuernummer_input .= qq|</font></b>|;
233   $steuernummer_input .= qq|\n
234            <input type=hidden name="elster_pattern" value="$elster_pattern">
235            <input type=hidden name="patterncount" value="$patterncount">
236            <input type=hidden name="patternlength" value="$patterncount">
237            <input type=hidden name="delimiter1" value="$delimiter1">
238            <input type=hidden name="delimiter2" value="$delimiter2">
239            <input type=hidden name="part" value="$part">
240   |;
241
242   my $k = 0;
243
244   for (my $h = 1; $h < $patterncount; $h++) {
245     my $delimiter = ( $h==1?$delimiter1:$delimiter2);
246     $steuernummer_input .= qq|&nbsp;$delimiter&nbsp;\n|;
247 #  $::lxdebug->message(LXDebug->DEBUG2, "pattern[$h]=".$elster_pattern[$h]);
248     for (my $i = 1; $i <= length($elster_pattern[$h]); $i++) {
249       $steuernummer_input .= qq|<select name="part_$h\_$i">\n|;
250
251       for (my $j = 0; $j <= 9; $j++) {
252         $steuernummer_input .= qq|      <option value="$j"|;
253         if ($steuernummer ne '') {
254           if ($j eq substr($stnr, length($part) + $k, 1)) {
255             $steuernummer_input .= qq| selected|;
256           }
257         }
258         $steuernummer_input .= qq|>$j</option>\n|;
259       }
260       $k++;
261       $steuernummer_input .= qq|</select>\n|;
262     }
263   }
264
265   $main::lxdebug->leave_sub();
266
267   return $steuernummer_input;
268 }
269
270 sub fa_auswahl {
271   $main::lxdebug->enter_sub();
272
273   # Referenz wird übergeben, hash of hash wird nicht
274   # in neues  Hash kopiert, sondern direkt über die Referenz verändert
275   # Prototyp für diese Konstruktion
276
277   my ($self, $land, $elsterFFFF, $elster_init) = @_;
278
279 #  $::lxdebug->message(LXDebug->DEBUG2,"land=".$land." amt=".$elsterFFFF);
280   my $terminal = '';
281   my $FFFF     = $elsterFFFF;
282   my $ffff     = '';
283   my $checked  = '';
284   $checked = 'checked' if ($elsterFFFF eq '' and $land eq '');
285   my %elster_land_fa;
286   my %elster_land_name = ();
287
288   my $fa_auswahl = qq|
289         <script language="Javascript">
290         function update_auswahl()
291         {
292                 var elsterBLAuswahl = document.verzeichnis.fa_land_nr_new;
293                 var elsterFAAuswahl = document.verzeichnis.fa_bufa_nr_new;
294
295                 elsterFAAuswahl.options.length = 0; // dropdown aufräumen
296                 |;
297
298   foreach my $elster_land (sort keys %$elster_init) {
299     $fa_auswahl .= qq|
300                if (elsterBLAuswahl.options[elsterBLAuswahl.selectedIndex].value == "$elster_land")
301                {
302                |;
303     my $j              = 0;
304     %elster_land_fa = ();
305     $FFFF = '';
306     for $FFFF (keys %{ $elster_init->{$elster_land} }) {
307         if ( $FFFF eq 'name' ) {
308             $elster_land_name{$elster_land} = $elster_init->{$elster_land}{$FFFF};
309             delete $elster_init->{$elster_land}{$FFFF};
310         } else {
311             $elster_land_fa{$FFFF} = $elster_init->{$elster_land}{$FFFF}->fa_name;
312        }
313     }
314     foreach $ffff (sort { $elster_land_fa{$a} cmp $elster_land_fa{$b} }
315                    keys(%elster_land_fa)
316       ) {
317       $fa_auswahl .= qq|
318                    elsterFAAuswahl.options[$j] = new Option("$elster_land_fa{$ffff} ($ffff)","$ffff");|;
319       $j++;
320     }
321     $fa_auswahl .= qq|
322                }|;
323   }
324   $fa_auswahl .= qq|
325         }
326         </script>
327
328         <table width="100%">
329           <tr>
330             <td>
331                Bundesland
332             </td>
333             <td>
334               <select size="1" name="fa_land_nr_new" onchange="update_auswahl()">|;
335   if ($land eq '') {
336     $fa_auswahl .= qq|<option value="Auswahl" $checked>| . $main::locale->text('Select federal state...') . qq|</option>\n|;
337   }
338   foreach my $elster_land (sort keys %$elster_init) {
339     $fa_auswahl .= qq|
340                   <option value="$elster_land"|;
341 #  $::lxdebug->message(LXDebug->DEBUG2,"land=".$land." elster_land=".$elster_land." lname=".$elster_land_name{$elster_land});
342     if ($elster_land eq $land and $checked eq '') {
343       $fa_auswahl .= qq| selected|;
344     }
345     $fa_auswahl .= qq|>$elster_land_name{$elster_land}</option>
346              |;
347   }
348   $fa_auswahl .= qq|
349               </select>
350             </td>
351           </tr>
352           |;
353
354   my $elster_land = '';
355   $elster_land = ($land ne '') ? $land : '';
356   %elster_land_fa = ();
357   for $FFFF (keys %{ $elster_init->{$elster_land} }) {
358     $elster_land_fa{$FFFF} = $elster_init->{$elster_land}{$FFFF}->fa_name;
359   }
360
361   $fa_auswahl .= qq|
362            <tr>
363               <td>Finanzamt
364               </td>
365               <td>
366                  <select size="1" name="fa_bufa_nr_new">|;
367   if ($elsterFFFF eq '') {
368     $fa_auswahl .= qq|<option value="Auswahl" $checked>| . $main::locale->text('Select tax office...') . qq|</option>|;
369   } else {
370     foreach $ffff (sort { $elster_land_fa{$a} cmp $elster_land_fa{$b} }
371                    keys(%elster_land_fa)
372       ) {
373
374       $fa_auswahl .= qq|
375                         <option value="$ffff"|;
376       if ($ffff eq $elsterFFFF and $checked eq '') {
377         $fa_auswahl .= qq| selected|;
378       }
379       $fa_auswahl .= qq|>$elster_land_fa{$ffff} ($ffff)</option>|;
380     }
381   }
382   $fa_auswahl .= qq|
383                  </select>
384               </td>
385           </tr>
386         </table>|;
387
388   $main::lxdebug->leave_sub();
389
390   return $fa_auswahl;
391 }
392
393 sub info {
394   $main::lxdebug->enter_sub();
395
396   my $msg = $_[0];
397
398   if ($ENV{HTTP_USER_AGENT}) {
399     $msg =~ s/\n/<br>/g;
400
401     print qq|<body><h2 class=info>Hinweis</h2>
402
403     <p><b>$msg</b>
404     <br>
405     <br>
406     <hr>
407     <input type=button value="| . $main::locale->text('Back') . qq|" onClick="history.go(-1)">
408     </body>
409     |;
410
411     $::dispatcher->end_request;
412
413   } else {
414
415     die "Hinweis: $msg\n";
416   }
417
418   $main::lxdebug->leave_sub();
419 }
420
421 # 20.10.2009 sschoeling: this sub seems to be orphaned.
422 sub stichtag {
423   $main::lxdebug->enter_sub();
424
425   # noch nicht fertig
426   # soll mal eine Erinnerungsfunktion für USTVA Abgaben werden, die automatisch
427   # den Termin der nächsten USTVA anzeigt.
428   #
429   #
430   my ($today, $FA_dauerfrist, $FA_voranmeld) = @_;
431
432   #$today zerlegen:
433
434   #$today =today * 1;
435   $today =~ /(\d\d\d\d)(\d\d)(\d\d)/;
436   my $year     = $1;
437   my $month    = $2;
438   my $day      = $3;
439   my $yy       = $year;
440   my $mm       = $month;
441   my $yymmdd   = "$year$month$day" * 1;
442   my $mmdd     = "$month$day" * 1;
443   my $stichtag = '';
444
445   #$tage_bis = '1234';
446   #$ical = '...vcal format';
447
448   #if ($FA_voranmeld eq 'month'){
449
450   my %liste = (
451     "0110" => 'December',
452     "0210" => 'January',
453     "0310" => 'February',
454     "0410" => 'March',
455     "0510" => 'April',
456     "0610" => 'May',
457     "0710" => 'June',
458     "0810" => 'July',
459     "0910" => 'August',
460     "1010" => 'September',
461     "1110" => 'October',
462     "1210" => 'November',
463   );
464
465   #$mm += $dauerfrist
466   #$month *= 1;
467   $month += 1 if ($day > 10);
468   $month    = sprintf("%02d", $month);
469   $stichtag = $year . $month . "10";
470   my $ust_va   = $month . "10";
471
472   foreach my $date (%liste) {
473     $ust_va = $liste{$date} if ($date eq $stichtag);
474   }
475
476   #} elsif ($FA_voranmeld eq 'quarter'){
477   #1;
478
479   #}
480
481   #@stichtag = ('10.04.2004', '10.05.2004');
482
483   #@liste = ['0110', '0210', '0310', '0410', '0510', '0610', '0710', '0810', '0910',
484   #          '1010', '1110', '1210', ];
485   #
486   #foreach $key (@liste){
487   #  #if ($ddmm < ('0110' * 1));
488   #  if ($ddmm ){}
489   #  $stichtag = $liste[$key - 1] if ($ddmm > $key);
490   #
491   #}
492   #
493   #$stichtag =~ /([\d]\d)(\d\d)$/
494   #$stichtag = "$1.$2.$yy"
495   #$stichtag=$1;
496   our $description; # most probably not existent.
497   our $tage_bis;    # most probably not existent.
498   our $ical;        # most probably not existent.
499
500   $main::lxdebug->leave_sub();
501   return ($stichtag, $description, $tage_bis, $ical);
502 }
503
504 sub query_finanzamt {
505   $main::lxdebug->enter_sub();
506
507   my ($self, $myconfig, $form) = @_;
508
509   my $dbh = SL::DB->client->dbh;
510
511   #Test, if table finanzamt exist
512   my $table    = 'finanzamt';
513   my $filename = "sql/$table.sql";
514
515   my $tst = $dbh->prepare("SELECT * FROM $table");
516   $tst->execute || do {
517     #There is no table, read the table from sql/finanzamt.sql
518     print qq|<p>Bitte warten, Tabelle $table wird einmalig in Datenbank:
519     $myconfig->{dbname} als Benutzer: $myconfig->{dbuser} hinzugefügt...</p>|;
520     SL::DB->client->with_transaction(sub {
521       process_query($form, $dbh, $filename) || $self->error(DBI->errstr);
522       1;
523     }) or do { die SL::DB->client->error };
524   };
525   $tst->finish();
526
527
528   my $fiamt =  SL::DB::Finanzamt->_get_manager_class->get_all(sort => 'fa_land_nr');
529   my $land      = 0;
530   my %finanzamt;
531   foreach my $row (@$fiamt) {
532     my $tax_office   = first { $_->{id} == $row->fa_land_nr } @{ $self->{tax_office_information} };
533     $land            = $tax_office->{id};
534     $finanzamt{$land}{$row->fa_bufa_nr}  = $row;
535     $finanzamt{$land}{'name'} ||= $tax_office->{name};
536   }
537   $main::lxdebug->leave_sub();
538
539   return \%finanzamt;
540 }
541
542 sub process_query {
543   $main::lxdebug->enter_sub();
544
545   # Copyright D. Simander -> SL::Form under Gnu GPL.
546   my ($form, $dbh, $filename) = @_;
547
548   #  return unless (-f $filename);
549
550   open my $FH, "<", "$filename" or $form->error("$filename : $!\n");
551   my $query = "";
552   my $sth;
553   my @quote_chars;
554
555   while (<$FH>) {
556
557     # Remove DOS and Unix style line endings.
558     s/[\r\n]//g;
559
560     # don't add comments or empty lines
561     next if /^(--.*|\s+)$/;
562
563     for (my $i = 0; $i < length($_); $i++) {
564       my $char = substr($_, $i, 1);
565
566       # Are we inside a string?
567       if (@quote_chars) {
568         if ($char eq $quote_chars[-1]) {
569           pop(@quote_chars);
570         }
571         $query .= $char;
572
573       } else {
574         if (($char eq "'") || ($char eq "\"")) {
575           push(@quote_chars, $char);
576
577         } elsif ($char eq ";") {
578
579           # Query is complete. Send it.
580
581           $sth = $dbh->prepare($query);
582           $sth->execute || $form->dberror($query);
583           $sth->finish;
584
585           $char  = "";
586           $query = "";
587         }
588
589         $query .= $char;
590       }
591     }
592   }
593
594   close $FH;
595
596   $main::lxdebug->leave_sub();
597 }
598
599 sub ustva {
600   $main::lxdebug->enter_sub();
601
602   my ($self, $myconfig, $form) = @_;
603
604   my $dbh = SL::DB->client->dbh;
605
606   my $last_period     = 0;
607   my $category        = "pos_ustva";
608
609   $form->{coa} = $::instance_conf->get_coa;
610
611   my @category_cent = USTVA->report_variables({
612       myconfig    => $myconfig,
613       form        => $form,
614       type        => '',
615       attribute   => 'position',
616       dec_places  => '2',
617   });
618
619   if ( $form->{coa} eq 'Germany-DATEV-SKR03EU' or $form->{coa} eq 'Germany-DATEV-SKR04EU') {
620       push @category_cent, qw(Z43  Z45  Z53  Z54  Z62  Z65  Z67);
621   }
622   my @category_euro = USTVA->report_variables({
623       myconfig    => $myconfig,
624       form        => $form,
625       type        => '',
626       attribute   => 'position',
627       dec_places  => '0',
628   });
629
630   @{$form->{category_cent}} = @category_cent;
631   @{$form->{category_euro}} = @category_euro;
632   $form->{decimalplaces} *= 1;
633
634   foreach my $item (@category_cent) {
635     $form->{"$item"} = 0;
636   }
637   foreach my $item (@category_euro) {
638     $form->{"$item"} = 0;
639   }
640
641   # Controlvariable for templates
642   my $coa_name = $form->{coa};
643   $form->{"$coa_name"} = '1';
644
645   &get_accounts_ustva($dbh, $last_period, $form->{fromdate}, $form->{todate},
646                       $form, $category);
647
648   ###########################################
649   #
650   # Nationspecific Modfications
651   #
652   ###########################################
653
654   # Germany
655
656   if ( $form->{coa} eq 'Germany-DATEV-SKR03EU' or $form->{coa} eq 'Germany-DATEV-SKR04EU'){
657
658     # 16%/19% Umstellung
659     # Umordnen der Kennziffern
660     if ( $form->{year} < 2007) {
661       $form->{35} += $form->{81};
662       $form->{36} += $form->{811};
663       $form->{95} += $form->{89};
664       $form->{98} += $form->{891};
665       map { delete $form->{$_} } qw(81 811 89 891);
666     } else {
667       $form->{35} += $form->{51};
668       $form->{36} += $form->{511};
669       $form->{95} += $form->{97};
670       $form->{98} += $form->{971};
671       map { delete $form->{$_} } qw(51 511 97 971);
672     }
673
674   }
675
676
677   # Fixme: Wird auch noch für Oesterreich gebraucht,
678   # weil kein eigenes Ausgabeformular
679   # sotte aber aus der allgeméinen Steuerberechnung verschwinden
680   #
681   # Berechnung der USTVA Formularfelder laut Bogen 207
682   #
683
684   $form->{"51r"} = $form->{"511"};
685   $form->{"86r"} = $form->{"861"};
686   $form->{"97r"} = $form->{"971"};
687   $form->{"93r"} = $form->{"931"};
688
689   $form->{"Z43"} = $form->{"511"}     + $form->{"811"} + $form->{"861"}
690                      + $form->{"36"}  + $form->{"80"}  + $form->{"971"}
691                      + $form->{"891"} + $form->{"931"} + $form->{"96"}
692                      + $form->{"98"};
693
694   $form->{"Z45"} = $form->{"Z43"};
695
696   $form->{"Z53"} = $form->{"Z45"}     + $form->{"47"}  + $form->{"53"}  + $form->{"74"}
697                      + $form->{"85"}  + $form->{"65"};
698
699   $form->{"Z62"} = $form->{"Z53"}     - $form->{"66"}  - $form->{"61"}
700                      - $form->{"62"}  - $form->{"67"}  - $form->{"63"}
701                      - $form->{"64"}  - $form->{"59"};
702
703   $form->{"Z65"} = $form->{"Z62"}     - $form->{"69"};
704   $form->{"83"}  = $form->{"Z65"}     - $form->{"39"};
705
706   $main::lxdebug->leave_sub();
707 }
708
709 sub get_accounts_ustva {
710   $main::lxdebug->enter_sub();
711
712   my ($dbh, $last_period, $fromdate, $todate, $form, $category) = @_;
713   our ($dpt_join);
714
715   my $query;
716   my $where    = "";
717   my $glwhere  = "";
718   my $subwhere = "";
719   my $ARwhere  = "";
720   my $APwhere  = '';
721   my $arwhere  = "";
722   my $item;
723
724   my $gltaxkey_where = "((tk.pos_ustva = 46) OR (tk.pos_ustva>=59 AND tk.pos_ustva<=67) or (tk.pos_ustva>=89 AND tk.pos_ustva<=93))";
725
726   if ($fromdate) {
727     if ($form->{accounting_method} eq 'cash') {
728       $subwhere .= " AND transdate >= '$fromdate'";
729       $glwhere = " AND ac.transdate >= '$fromdate'";
730       $ARwhere .= " AND acc.transdate >= '$fromdate'";
731     }
732     $APwhere .= " AND AP.transdate >= '$fromdate'";
733     $where .= " AND ac.transdate >= '$fromdate'";
734   }
735
736   if ($todate) {
737     $where    .= " AND ac.transdate <= '$todate'";
738     $ARwhere  .= " AND acc.transdate <= '$todate'";
739   }
740
741   my $acc_trans_where = '1=1';
742   if ($fromdate || $todate) {
743     $acc_trans_where = "ac.trans_id IN (SELECT DISTINCT trans_id FROM acc_trans WHERE ";
744
745     if ($fromdate) {
746       $acc_trans_where .= "transdate >= '$fromdate'";
747     }
748     if ($todate) {
749       $acc_trans_where .= " AND " if ($fromdate);
750       $acc_trans_where .= "transdate <= '$todate'";
751     }
752
753     $acc_trans_where .= ")";
754   }
755
756   ############################################
757   # Method eq 'cash' = IST Versteuerung
758   ############################################
759   # Betrifft nur die eingenommene Umsatzsteuer
760   #
761   ############################################
762
763   if ($form->{accounting_method} eq 'cash') {
764
765     $query = qq|
766        SELECT
767          -- USTVA IST-Versteuerung
768          --
769          -- Alle tatsaechlichen _Zahlungseingaenge_
770          -- im Voranmeldezeitraum erfassen
771          -- (Teilzahlungen werden prozentual auf verschiedene Steuern aufgeteilt)
772          SUM( ac.amount *
773             -- Bezahlt / Rechnungssumme
774            (
775              SELECT SUM(acc.amount)
776              FROM acc_trans acc
777              INNER JOIN chart c ON (acc.chart_id   =   c.id
778                                     AND c.link   like  '%AR_paid%')
779              WHERE
780               1=1
781               $ARwhere
782               AND acc.trans_id = ac.trans_id
783               )
784            /
785            (
786             SELECT amount FROM ar WHERE id = ac.trans_id
787            )
788          ) AS amount,
789          tk.pos_ustva
790        FROM acc_trans ac
791        LEFT JOIN chart c ON (c.id  = ac.chart_id)
792        LEFT JOIN ar      ON (ar.id = ac.trans_id)
793        LEFT JOIN taxkeys tk ON (
794          tk.id = (
795            SELECT id FROM taxkeys
796            WHERE chart_id   = ac.chart_id
797              -- AND taxkey_id  = ac.taxkey
798              AND startdate <= COALESCE(ar.deliverydate,ar.transdate)
799            ORDER BY startdate DESC LIMIT 1
800          )
801        )
802        WHERE
803        $acc_trans_where
804        GROUP BY tk.pos_ustva
805     |;
806
807   } elsif ($form->{accounting_method} eq 'accrual') {
808     #########################################
809     # Method eq 'accrual' = Soll Versteuerung
810     #########################################
811
812     $query = qq|
813        -- Alle Einnahmen AR und pos_ustva erfassen
814        SELECT
815          - sum(ac.amount) AS amount,
816          tk.pos_ustva
817        FROM acc_trans ac
818        JOIN chart c ON (c.id = ac.chart_id)
819        JOIN ar ON (ar.id = ac.trans_id)
820        JOIN taxkeys tk ON (
821          tk.id = (
822            SELECT id FROM taxkeys
823            WHERE chart_id   = ac.chart_id
824              AND startdate <= COALESCE(ar.deliverydate,ar.transdate)
825            ORDER BY startdate DESC LIMIT 1
826          )
827        )
828        $dpt_join
829        WHERE 1 = 1
830        $where
831        GROUP BY tk.pos_ustva
832   |;
833
834   } else {
835
836     $form->error("Unknown tax method: $form->{accounting_method}")
837
838   }
839
840   #########################################
841   # Ausgaben und Gl Buchungen sind gleich
842   # für Ist- und Soll-Versteuerung
843   #########################################
844   $query .= qq|
845      UNION -- alle Ausgaben AP erfassen
846
847        SELECT
848          sum(ac.amount) AS amount,
849          tk.pos_ustva
850        FROM acc_trans ac
851        JOIN ap ON (ap.id = ac.trans_id )
852        JOIN chart c ON (c.id = ac.chart_id)
853        LEFT JOIN taxkeys tk ON (
854            tk.id = (
855              SELECT id FROM taxkeys
856              WHERE 1=1
857                AND chart_id=ac.chart_id
858                --AND taxkey_id = ac.taxkey
859                AND startdate <= COALESCE(AP.transdate)
860              ORDER BY startdate DESC LIMIT 1
861            )
862        )
863        WHERE
864        1=1
865        $where
866        GROUP BY tk.pos_ustva
867
868      UNION -- Einnahmen direkter gl Buchungen erfassen
869
870        SELECT sum
871          ( - ac.amount) AS amount,
872          tk.pos_ustva
873        FROM acc_trans ac
874        JOIN chart c ON (c.id = ac.chart_id)
875        JOIN gl a ON (a.id = ac.trans_id)
876        LEFT JOIN taxkeys tk ON (
877          tk.id = (
878            SELECT id FROM taxkeys
879            WHERE chart_id=ac.chart_id
880              AND NOT $gltaxkey_where
881              AND startdate <= COALESCE(ac.transdate)
882            ORDER BY startdate DESC LIMIT 1
883          )
884        )
885
886        $dpt_join
887        WHERE 1 = 1
888        $where
889        GROUP BY tk.pos_ustva
890
891
892      UNION -- Ausgaben direkter gl Buchungen erfassen
893
894        SELECT sum
895          (ac.amount) AS amount,
896          tk.pos_ustva
897        FROM acc_trans ac
898        JOIN chart c ON (c.id = ac.chart_id)
899        JOIN gl a ON (a.id = ac.trans_id)
900        LEFT JOIN taxkeys tk ON (
901          tk.id = (
902            SELECT id FROM taxkeys
903            WHERE chart_id=ac.chart_id
904              AND $gltaxkey_where
905              AND startdate <= COALESCE(ac.transdate)
906            ORDER BY startdate DESC LIMIT 1
907          )
908        )
909
910        $dpt_join
911        WHERE 1 = 1
912        $where
913        GROUP BY tk.pos_ustva
914
915   |;
916
917   my @accno;
918   my $accno;
919   my $ref;
920
921   # Show all $query in Debuglevel LXDebug::QUERY
922   my $callingdetails = (caller (0))[3];
923   $main::lxdebug->message(LXDebug->QUERY(), "$callingdetails \$query=\n $query");
924
925   my $sth = $dbh->prepare($query);
926
927   $sth->execute || $form->dberror($query);
928
929   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
930     # Bug 365 solved?!
931     $ref->{amount} *= -1;
932     $form->{ $ref->{$category} } += $ref->{amount};
933   }
934
935   $sth->finish;
936
937   $main::lxdebug->leave_sub();
938
939 }
940
941 sub set_FromTo {
942   $main::lxdebug->enter_sub();
943
944   my ($self, $form) = @_;
945
946   # init some form vars
947   my @anmeldungszeitraum =
948     qw('0401' '0402' '0403'
949        '0404' '0405' '0406'
950        '0407' '0408' '0409'
951        '0410' '0411' '0412'
952        '0441' '0442' '0443' '0444');
953
954   foreach my $item (@anmeldungszeitraum) {
955     $form->{$item} = "";
956   }
957
958   #forgotten the year --> thisyear
959   if ($form->{year} !~ m/^\d\d\d\d$/) {
960       $form->{year} = substr(
961           $form->datetonum(
962               $form->current_date(\%::myconfig), \%::myconfig
963           ),
964           0, 4);
965       $::lxdebug->message(LXDebug->DEBUG1,
966                           qq|Actual year from Database: $form->{year}\n|);
967   }
968
969   #
970   # using dates in ISO-8601 format: yyyymmmdd  for Postgres...
971   #
972
973   #yearly report
974   if ($form->{period} eq "13") {
975       $form->{fromdate} = "$form->{year}0101";
976       $form->{todate}   = "$form->{year}1231";
977   }
978
979   #quarter reports
980   if ($form->{period} eq "41") {
981       $form->{fromdate} = "$form->{year}0101";
982       $form->{todate}   = "$form->{year}0331";
983       $form->{'0441'}   = "X";
984   }
985   if ($form->{period} eq "42") {
986       $form->{fromdate} = "$form->{year}0401";
987       $form->{todate}   = "$form->{year}0630";
988       $form->{'0442'}   = "X";
989   }
990   if ($form->{period} eq "43") {
991       $form->{fromdate} = "$form->{year}0701";
992       $form->{todate}   = "$form->{year}0930";
993       $form->{'0443'}   = "X";
994   }
995   if ($form->{period} eq "44") {
996       $form->{fromdate} = "$form->{year}1001";
997       $form->{todate}   = "$form->{year}1231";
998       $form->{'0444'}   = "X";
999   }
1000
1001    #Monthly reports
1002   SWITCH: {
1003       $form->{period} eq "01" && do {
1004         $form->{fromdate} = "$form->{year}0101";
1005         $form->{todate}   = "$form->{year}0131";
1006         $form->{'0401'}   = "X";
1007         last SWITCH;
1008       };
1009       $form->{period} eq "02" && do {
1010         $form->{fromdate} = "$form->{year}0201";
1011
1012         #this works from 1901 to 2099, 1900 and 2100 fail.
1013         my $leap = ($form->{year} % 4 == 0) ? "29" : "28";
1014         $form->{todate} = "$form->{year}02$leap";
1015         $form->{"0402"} = "X";
1016         last SWITCH;
1017       };
1018       $form->{period} eq "03" && do {
1019         $form->{fromdate} = "$form->{year}0301";
1020         $form->{todate}   = "$form->{year}0331";
1021         $form->{"0403"}   = "X";
1022         last SWITCH;
1023       };
1024       $form->{period} eq "04" && do {
1025         $form->{fromdate} = "$form->{year}0401";
1026         $form->{todate}   = "$form->{year}0430";
1027         $form->{"0404"}   = "X";
1028         last SWITCH;
1029       };
1030       $form->{period} eq "05" && do {
1031         $form->{fromdate} = "$form->{year}0501";
1032         $form->{todate}   = "$form->{year}0531";
1033         $form->{"0405"}   = "X";
1034         last SWITCH;
1035       };
1036       $form->{period} eq "06" && do {
1037         $form->{fromdate} = "$form->{year}0601";
1038         $form->{todate}   = "$form->{year}0630";
1039         $form->{"0406"}   = "X";
1040         last SWITCH;
1041       };
1042       $form->{period} eq "07" && do {
1043         $form->{fromdate} = "$form->{year}0701";
1044         $form->{todate}   = "$form->{year}0731";
1045         $form->{"0407"}   = "X";
1046         last SWITCH;
1047       };
1048       $form->{period} eq "08" && do {
1049         $form->{fromdate} = "$form->{year}0801";
1050         $form->{todate}   = "$form->{year}0831";
1051         $form->{"0408"}   = "X";
1052         last SWITCH;
1053       };
1054       $form->{period} eq "09" && do {
1055         $form->{fromdate} = "$form->{year}0901";
1056         $form->{todate}   = "$form->{year}0930";
1057         $form->{"0409"}   = "X";
1058         last SWITCH;
1059       };
1060       $form->{period} eq "10" && do {
1061         $form->{fromdate} = "$form->{year}1001";
1062         $form->{todate}   = "$form->{year}1031";
1063         $form->{"0410"}   = "X";
1064         last SWITCH;
1065       };
1066       $form->{period} eq "11" && do {
1067         $form->{fromdate} = "$form->{year}1101";
1068         $form->{todate}   = "$form->{year}1130";
1069         $form->{"0411"}   = "X";
1070         last SWITCH;
1071       };
1072       $form->{period} eq "12" && do {
1073         $form->{fromdate} = "$form->{year}1201";
1074         $form->{todate}   = "$form->{year}1231";
1075         $form->{"0412"}   = "X";
1076         last SWITCH;
1077       };
1078     }
1079
1080   # Kontrollvariablen für die Templates
1081   $form->{"year$_"} = ($form->{year} >= $_ ) ? "1":"0" for 2007..2107;
1082
1083   $main::lxdebug->leave_sub();
1084 }
1085
1086 sub get_fiamt_vars {
1087     return @fiamt_finanzamt;
1088 }
1089
1090 sub get_oldconfig {
1091   $main::lxdebug->enter_sub();
1092
1093   my $ret = 0;
1094   my %oldkeys = (
1095       'steuernummer' => 'taxnumber',
1096       'elsterFFFF' => 'fa_bufa_nr',
1097       'FA_dauerfrist' => 'fa_dauerfrist',
1098       'FA_steuerberater_city' => 'fa_steuerberater_city',
1099       'FA_steuerberater_name' => 'fa_steuerberater_name',
1100       'FA_steuerberater_street' => 'fa_steuerberater_street',
1101       'FA_steuerberater_tel' => 'fa_steuerberater_tel',
1102       'FA_voranmeld' => 'fa_voranmeld',
1103       );
1104
1105   my $filename = $::lx_office_conf{paths}{userspath}."/finanzamt.ini";
1106   my $FACONF;
1107   return unless (open( $FACONF, "<", $filename));
1108
1109   while (<$FACONF>) {
1110     last if (/^\[/);
1111     next if (/^(\#|\s)/);
1112
1113     # remove comments
1114     s/\s#.*//g;
1115
1116     # remove any trailing whitespace
1117     s/^\s*(.*?)\s*$/$1/;
1118     my ($key, $value) = split(/=/, $_, 2);
1119
1120     $main::lxdebug->message(LXDebug->DEBUG2(), "oldkey: ".$key." val=".$value." newkey=".
1121                           $oldkeys{$key}." oval=".$::form->{$oldkeys{$key}});
1122     if ( $oldkeys{$key} && $::form->{$oldkeys{$key}} eq '' ) {
1123         $::form->{$oldkeys{$key}} = $::locale->{iconv_utf8}->convert($value);
1124         $main::lxdebug->message(LXDebug->DEBUG2(), "set ".$oldkeys{$key}."=".$::form->{$oldkeys{$key}});
1125         $ret = 1;
1126     }
1127   }
1128   $main::lxdebug->leave_sub();
1129   return $ret;
1130 }
1131
1132 sub get_config {
1133     $main::lxdebug->enter_sub();
1134     my $defaults   = SL::DB::Default->get;
1135     my @rd_config =  @fiamt_config;
1136     push @rd_config ,qw(accounting_method coa company address co_ustid duns);
1137     $::form->{$_} = $defaults->$_ for @rd_config;
1138
1139     if ( $::form->{taxnumber} eq '' || $::form->{fa_bufa_nr} eq '') {
1140         #alte finanzamt.ini lesen, ggf abspeichern
1141         if ( get_oldconfig() ) {
1142             get_finanzamt();
1143             save_config();
1144         }
1145     }
1146
1147     my $coa = $::form->{coa};
1148     $::form->{"COA_$coa"} = '1';
1149     $::form->{COA_Germany} = '1' if ($coa =~ m/^germany/i);
1150     $main::lxdebug->leave_sub();
1151 }
1152
1153 sub get_finanzamt {
1154     $main::lxdebug->enter_sub();
1155     if ( $::form->{fa_bufa_nr} && $::form->{fa_bufa_nr} ne '' ) {
1156         my $fiamt =  SL::DB::Finanzamt->_get_manager_class->get_first(
1157                  query => [ fa_bufa_nr => $::form->{fa_bufa_nr} ]);
1158         $::form->{$_} = $fiamt->$_ for @fiamt_finanzamt;
1159     }
1160     $main::lxdebug->leave_sub();
1161 }
1162
1163 sub save_config {
1164     $main::lxdebug->enter_sub();
1165     my $defaults  = SL::DB::Default->get;
1166     $defaults->$_($::form->{$_}) for @fiamt_config;
1167     $defaults->save;
1168     if ( $defaults->fa_bufa_nr ) {
1169         my $fiamt =  SL::DB::Finanzamt->_get_manager_class->get_first(
1170                  query => [ fa_bufa_nr => $defaults->fa_bufa_nr ]);
1171         $fiamt->$_($::form->{$_}) for @fiamt_finanzamt;
1172         $fiamt->save;
1173     }
1174     $main::lxdebug->leave_sub();
1175 }
1176
1177 1;