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