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