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