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