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