Only display outgoing items for reimbursements
[infodrom.org/service.infodrom.org] / src / InfoCon / buch / infocon
1 #! /usr/bin/perl
2
3 #  infocon - Administration tool for InfoCon
4 #  Copyright (c) 1998-2003,2005-8,10,11,12,14,15,16  Martin Schulze <joey@infodrom.org>
5 #
6 #  This program is free software; you can redistribute it and/or modify
7 #  it under the terms of the GNU General Public License as published by
8 #  the Free Software Foundation; either version 2 of the License, or
9 #  (at your option) any later version.
10 #
11 #  This program is distributed in the hope that it will be useful,
12 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #  GNU General Public License for more details.
15 #
16 #  You should have received a copy of the GNU General Public License
17 #  along with this program; if not, write to the Free Software
18 #  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
19
20 use strict;
21 use warnings;
22
23 use DBI;
24 use Scalar::Util qw/reftype/;
25 use Term::ReadLine;
26 use Getopt::Long;
27
28 my $table = "sales";
29 my $engine  = "dbi:Pg:dbname=infocon";
30 my $dbh = DBI->connect($engine);
31 if (!$dbh) {
32     print "Access to database denied!\n";
33     return 1;
34 }
35
36 my %data;
37 my @categories = ();
38 my $term = undef;
39 my $opt_all = 0;
40 my $opt_csv = 0;
41 my $opt_verbose = 0;
42 my $opt_year = 0;
43 my $opt_date = undef;
44 my $opt_direction = undef;
45
46 sub sdate
47 {
48     $_[0] =~ /\d{2}(\d{2})(\d{2})(\d{2})/;
49     return sprintf ("%d.%02d.%02d", $3,$2,$1);
50 }
51
52 sub isodate
53 {
54     $_[0] =~ /(\d{4})(\d{2})(\d{2})/;
55     return sprintf ("%04d-%02d-%02d", $1,$2,$3);
56 }
57
58 # Wandelt einen lesbaren Datumsstring in die Form um, in der er in der
59 # Datenbank gespeichert werden kann.
60 #
61 sub date_to_string
62 {
63     my ($day,$mon,$year);
64
65     return "" if (!$_[0]);
66
67     my ($date_sec,$date_min,$date_hour,$date_mday,$date_mon,$date_year,$date_wday,$date_isdst)
68         = localtime;
69
70     if ($_[0] eq "heute" || $_[0] eq "sofort" || $_[0] eq "pronto" || $_[0] eq "today" || $_[0] eq "now") {
71         $day = $date_mday;
72         $mon = $date_mon+1;
73         $year = $date_year;
74     } elsif ($_[0] eq "gestern" || $_[0] eq "yesterday") {
75         $day = $date_mday-1 if ($date_mday);
76         $mon = $date_mon+1;
77         $year = $date_year;
78     } elsif ($_[0] eq "morgen" || $_[0] eq "tomorrow") {
79         $day = $date_mday+1;
80         $mon = $date_mon+1;
81         $year = $date_year;
82     } else {
83         ($day,$mon,$year) = split(/\./, $_[0]);
84         if (!$year) {    
85             $year = $date_year;
86         }
87     }
88
89     if ($year < 70) {
90         $year += 2000;
91     } elsif ($year < 100) {
92         $year += 1900;
93     }
94     return sprintf("%4d%02d%02d", $year,$mon,$day);
95 }
96
97 sub valid_isodate
98 {
99     my $date = shift;
100     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
101
102     return sprintf('%04d-%02d-%02d', $year+1900, $mon+1, $mday) unless defined $date;
103
104     if ($date =~ /^(\d+)\.(\d+)\.?$/) {
105         if ($mon == 0 && $2 > 9) {
106             $date = sprintf('%04d-%02d-%02d', $year+1900-1, $2, $1);
107         } else {
108             $date = sprintf('%04d-%02d-%02d', $year+1900, $2, $1);
109         }
110     } elsif ($date =~ /^(\d+)\.(\d+)\.(\d+)?$/) {
111         if (length $3 == 2) {
112             $date = sprintf('20%02d-%02d-%02d', $3, $2, $1);
113         } else {
114             $date = sprintf('%04d-%02d-%02d', $3, $2, $1);
115         }
116     } elsif ($date !~ /^(\d+)-(\d+)-(\d+)$/) {
117         return undef;
118     }
119     return $date;
120 }
121
122 sub pay_invoice
123 {
124     my $nr = shift;
125     my $pay = shift;
126     my $query;
127     my $sth;
128
129     if ($pay) {
130         my $date = valid_isodate $opt_date;
131
132         die "Invalid date\n" unless defined $date;
133
134         $query  = sprintf("UPDATE sales SET paid=1,billing_date=%s WHERE nr = %d",
135                           defined $date ? $dbh->quote($date) : 'now()', $nr);
136     } else {
137         $query  = sprintf("UPDATE sales SET paid=0,billing_date=NULL WHERE nr = %d", $nr);
138     }
139     $sth = $dbh->do($query);
140 }
141
142 sub hide_invoice
143 {
144     my $nr = shift;
145     my $hide = shift;
146     my $value = $hide==1?0:1;
147     my $query;
148     my $sth;
149
150     $query  = "UPDATE sales SET visible=$value WHERE nr = $nr";
151     $sth = $dbh->do($query);
152 }
153
154 sub sales_list
155 {
156     my $where = shift;
157     my $descr;
158     my $sum_pos=0;
159     my $sum_neg=0;
160     my $query;
161     my $row;
162     my $sth;
163     my $d;
164
165     if ($where && $where !~ /visible/ && (!$opt_all || $opt_all == 0)) {
166         if ($where) {
167             $where .= " AND visible = 1";
168         } else {
169             $where .= "visible = 1";
170         }
171     }
172
173     if ($opt_year) {
174         $where .= " AND " if $where;
175         $where .= sprintf("year = %d", $opt_year);
176     }
177
178     if (defined $data{category} && length $data{category}) {
179         $where .= " AND " if $where;
180         $where .= sprintf("category = %s", $dbh->quote($data{category}));
181     }
182
183     if ($opt_direction) {
184         if ($opt_direction eq "in") {
185             $d = "price >= 0"
186         } elsif ($opt_direction eq "out") {
187             $d = "price <= 0"
188         }
189
190         if ($where) {
191             $where .= " AND $d";
192         } else {
193             $where .= "$d";
194         }
195     }
196
197     if ($where !~ /visible/) {
198         $where .= " AND " if $where;
199         $where .= "visible = 1";
200     }
201
202     $query  = "SELECT nr,date,description,price,tax_percent,tax_assigned FROM $table";
203     $query .= " WHERE $where" if ($where);
204     $query .= " ORDER by date,nr";
205
206     $sth = $dbh->prepare($query);
207     if ($sth && (my $rc = $sth->execute) > 0) {
208         if ($opt_csv) {
209             print '"nr","date","description","taxrate","tax","value"'."\n";
210         } else {
211             print " Nr.   Datum  Bezeichnung                                           Betrag\n";
212             print "----------------------------------------------------------------------------\n";
213         }
214         while ($row = $sth->fetchrow_hashref) {
215             $descr = substr($row->{description},0,50);
216             if ($opt_csv) {
217                 printf '"%d","%s","%s","%.2f","%.2f","%.2f"'."\n", $row->{nr}, isodate($row->{date}), $descr,
218                     $row->{tax_percent}, $row->{tax_assigned}, $row->{price};
219             } else {
220                 printf "%4d %8s %-50s  %9.2f\n", $row->{nr}, sdate($row->{date}), $descr, $row->{price};
221             }
222             if ($row->{price} < 0.0) {
223                 $sum_neg -= $row->{price};
224             } else {
225                 $sum_pos += $row->{price};
226             }
227         }
228         if (!$opt_csv) {
229             print "---------------------------------------------------------------------------\n"
230                 if ($sum_neg > 0 || $sum_pos > 0) ;
231             printf " Zahlungseingänge                                                 %9.2f\n", $sum_pos
232                 if ($sum_pos > 0);
233             printf " Zahlungsausgänge                                                 %9.2f\n", -$sum_neg
234                 if ($sum_neg > 0);
235             print "============================================================================\n";
236             printf " Summe                                                            %9.2f\n\n", $sum_pos - $sum_neg;
237         }
238     }
239     $data{'done'} = 1;
240 }
241
242 sub get_categories
243 {
244     my $query;
245     my @row;
246     my $sth;
247     my @arr = ();
248
249     $query  = "SELECT DISTINCT category FROM $table ORDER by category";
250     $sth = $dbh->prepare($query);
251     if ($sth && (my $rc = $sth->execute) > 0) {
252         while (@row = $sth->fetchrow_array) {
253             push(@arr, $row[0]) if ($row[0]);
254         }
255     }
256     return @arr;
257 }
258
259 sub list_categories
260 {
261     my $field = shift;
262     my $answers = shift;
263
264     @categories = get_categories unless @categories;
265
266     printf "%s\n", join (", ",@categories);
267
268     exit unless $field;
269 }
270
271 sub validate_date
272 {
273     my $ans = shift;
274     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
275
276     return sprintf("%d.%d.%d", $mday, $mon+1, $year+1900) unless length $ans;
277
278     my @arr = split(/\./, $ans);
279
280     return sprintf("%d.%d.%d", $ans, $mon+1, $year+1900) if scalar @arr == 1;
281     return sprintf("%d.%d.%d", $arr[0], $arr[1], $year+1900) if scalar @arr == 2;
282     return sprintf("%d.%d.%d", $arr[0], $arr[1],
283                    length $arr[2] > 2 ? $arr[2] : $arr[2] + 2000);
284 }
285
286 my $answers;
287 sub calculate_price
288 {
289     my $ans = shift;
290
291     if (!defined $answers->{tax_assigned} || !length $answers->{tax_assigned}) {
292         $answers->{tax_assigned} = $ans - ($ans / ((100+$answers->{tax_percent})/100));
293     }
294
295     if ($answers->{einaus} =~ /[ei]/i) {
296         $answers->{tax_assigned} *= -1 if $answers->{tax_assigned} < 0;
297         $ans *= -1 if $ans < 0;
298     } else {
299         $answers->{tax_assigned} *= -1 if $answers->{tax_assigned} > 0;
300         $ans *= -1 if $ans > 0;
301     }
302
303     return $ans;
304 }
305
306 sub complete_category
307 {
308     my ($text, $line, $start) = @_;
309
310     return () unless exists $answers->{category} && length $answers->{category};
311
312     my $sql = sprintf("SELECT DISTINCT description FROM %s WHERE category = '%s' AND description LIKE '%s%%' ORDER BY description",
313                       $table,
314                       $answers->{category},
315                       $line);
316     my $sth = $dbh->prepare($sql);
317     $sth->execute;
318     my @complete;
319     while (my $row = $sth->fetchrow_hashref) {
320         $row->{description} = substr $row->{description}, $start if $start;
321         push @complete, $row->{description};
322     }
323
324     return @complete;
325 }
326
327 sub complete_categoryname
328 {
329     my ($text, $line, $start) = @_;
330
331     return () unless length $line;
332
333     my $sql = sprintf("SELECT DISTINCT category FROM %s WHERE category LIKE '%s%%' ORDER BY category",
334                       $table,
335                       $line);
336     my $sth = $dbh->prepare($sql);
337     $sth->execute;
338     my @complete;
339     while (my $row = $sth->fetchrow_hashref) {
340         $row->{category} = substr $row->{category}, $start if $start;
341         push @complete, $row->{category};
342     }
343
344     return @complete;
345 }
346
347 sub default_year
348 {
349     my $answers = shift;
350
351     my @arr = split(/\./, $answers->{date});
352     return $arr[2];
353 }
354
355 sub read_input
356 {
357     my $name = shift;
358     my $info = shift;
359     my $default;
360     my $ans;
361
362     if (exists $info->{default}) {
363         if ($info->{default} eq 'last') {
364             $default = $answers->{$name} if $answers->{$name};
365         } elsif (reftype $info->{default} && reftype $info->{default} eq 'CODE') {
366             $default = $info->{default}($answers);
367         } elsif ($info->{type} && $info->{type} eq 'boolean') {
368             if ($info->{default}) {
369                 $default = 'J';
370             } else {
371                 $default = 'N';
372             }
373         } else {
374             $default = $info->{default};
375         }
376     }
377
378     if ($info->{complete}) {
379         $term->{completion_function} = $info->{complete};
380     } else {
381         $term->{completion_function} = undef;
382     }
383
384     if ($default) {
385         $ans = $term->readline ($info->{title} . " [" . $default . "]: ");
386     } else {
387         $ans = $term->readline ($info->{title} . ": ");
388     }
389
390     exit unless defined $ans;
391
392     if (!length $ans && defined $default) {
393         $ans = $default;
394     } elsif ($ans eq ".") {
395         $ans = '';
396     }
397
398     return read_input($name, $info) unless length $ans || exists $info->{empty};
399
400     if ($ans eq '?' && exists $info->{lookup}) {
401         $info->{lookup}($name, $answers);
402         return read_input($name, $info);
403     }
404
405     if (exists $info->{type} && $info->{type} eq 'boolean') {
406         if ($ans =~ /[JY1]/i) {
407             $ans = 1;
408         } else {
409             $ans = 0;
410         }
411     } elsif (exists $info->{validate} && reftype $info->{validate} eq 'CODE') {
412         $ans = $info->{validate}($ans);
413     } else {
414         $ans =~ s/ *$// if $ans;
415     }
416
417     if (!exists $info->{type} || $info->{type} ne 'boolean') {
418         $term->addhistory($ans);
419     }
420
421     return $ans;
422 }
423
424 # Gibt die naechste freie Nr. in der Datenbank zurueck.  Wenn der
425 # INSERT nicht schnell darauf folgt, kann es passieren, dass die
426 # Nr. anschliessend bereits wieder vergeben ist.
427 #
428 sub get_next_nr
429 {
430     my $query;
431     my $sth;
432     my $rc;
433     my @row;
434
435     $query = "SELECT nr FROM $table ORDER BY nr DESC";
436     $sth = $dbh->prepare($query);
437     if ($sth) {
438         $rc = $sth->execute;
439         if ($rc > 0 && (@row = $sth->fetchrow_array)) {
440             return $row[0] + 1;
441         }
442     }
443     return 1;
444 }
445
446 sub buchung_input
447 {
448     my $weiter = 'y';
449     my $ans;
450     my ($date_sec,$date_min,$date_hour,$date_mday,$date_mon,$date_year,$date_wday,$date_isdst)
451         = localtime;
452
453     my $fields = {
454         'date' => {
455             'title' => 'Datum',
456             'validate' => \&validate_date,
457             'default' => 'last'},
458         'pdf' => {
459             'title' => 'PDF',
460             'type' => 'boolean',
461             'default' => 0},
462         'year' => {
463             'title' => 'Jahr',
464             'default' => \&default_year},
465         'category' => {
466             'title' => 'Kategorie',
467             'lookup' => \&list_categories,
468             'default' => 'last',
469             'complete' => \&complete_categoryname},
470         'description' => {
471             'title' => 'Beschreibung',
472             'default' => 'last',
473             'complete' => \&complete_category},
474         'einaus' => {
475             'title' => 'Ein/Aus',
476             'default' => 'a',
477             'save' => 0},
478         'tax_percent' => {
479             'title' => 'Steuersatz',
480             'default' => '19'},
481         'tax_assigned' => {
482             'title' => 'Umsatzsteuer',
483             'empty' => 1},
484         'price' => {
485             'title' => 'Betrag',
486             'validate' => \&calculate_price},
487         'paid' => {
488             'title' => 'bezahlt',
489             'type' => 'boolean',
490             'default' => 0},
491         'billing_date' => {
492             'title' => 'wann',
493             'type' => 'date',
494             'validate' => \&validate_date},
495         'weiter' => {
496             'title' => 'Weiter',
497             'type' => 'boolean',
498             'default' => 1,
499             'save' => 0},
500     };
501     my @fields = ('date','year','pdf','category','description','einaus','tax_percent','tax_assigned','price','paid','weiter');
502
503     @categories = get_categories unless @categories;
504
505     $term = new Term::ReadLine '' unless $term;
506
507     my $sth = $dbh->prepare ("INSERT INTO $table (nr,date,pdf,year,category,description,tax_percent,tax_assigned,price,billing_date,paid) " .
508                              "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
509
510     print "Buchungseingabe\n\n";
511     while ($weiter =~ /[JjYy1]/) {
512         foreach my $f (@fields) {
513             if ($f eq 'tax_assigned' && $answers->{'tax_percent'} == 0) {
514                 $answers->{$f} = 0;
515                 next;
516             }
517             $ans = read_input($f, $fields->{$f});
518             $answers->{$f} = $ans;
519
520             if ($f eq 'paid') {
521                 if ($answers->{paid}) {
522                     $fields->{'billing_date'}{'default'} = $answers->{'date'};
523                     $ans = read_input('billing_date', $fields->{'billing_date'});
524                     $answers->{billing_date} = $ans;
525                 } else {
526                     $answers->{billing_date} = undef;
527                 }
528             }
529         }
530
531         $sth->execute(get_next_nr(),
532                       date_to_string($answers->{date}),
533                       $answers->{pdf},
534                       $answers->{year},
535                       $answers->{category},
536                       $answers->{description},
537                       $answers->{tax_percent},
538                       $answers->{tax_assigned},
539                       $answers->{price},
540                       defined $answers->{billing_date} ? date_to_string($answers->{billing_date}) : undef,
541                       $answers->{paid});
542
543         $weiter = $answers->{weiter};
544         $answers->{tax_assigned} = 0.0;
545     }
546
547     exit;
548 }
549
550 sub buchung_hidden
551 {
552     $table = "sales_dm";
553     sales_list("visible = 0");
554     $table = "sales";
555     sales_list("visible = 0");
556     exit;
557 }
558
559 sub buchung_unpaid
560 {
561     $table = "sales";
562     sales_list("paid = 0");
563     exit;
564 }
565
566 sub usage
567 {
568     print "infocon [options] [-h|--help] commands\n";
569     print "  --buchung-category|-bc [category]\n";
570     print "  --buchung-input|-bi\n";
571     print "  --buchung-unpaid\n";
572     print "  --buchung-hidden\n";
573     print "  --date [yyyy-mm-dd|dd.mm.] (for --pay)\n";
574     print "  --pay <nr> | --unpay <nr>\n";
575     print "  --hide <nr> | --unhide <nr>\n";
576     print "  --list-categories|-lc\n";
577     print "  Options:\n";
578     print "    --all|-a\n";
579     print "    --csv\n";
580     print "    --verbose|-v\n";
581     print "    --year|-y year\n";
582     print "    --direction|--dir|-d in|out\n";
583     print "    --dm\n";
584     exit 0;
585 }
586
587 %data = (
588     'category' => undef,
589     'done' => undef,
590     'pay' => undef,
591     'unpay' => undef,
592     'hide' => undef,
593     'unhide' => undef,
594     'mailto' => undef,
595     'buchung-input' => undef,
596     'buchung-unpaid' => undef,
597     'buchung-hidden' => undef,
598     'list-categories' => undef,
599     );
600 my %options = (
601     'buchung-category|bc:s' => \$data{category},
602     'pay=s' => \$data{pay},
603     'unpay=s' => \$data{unpay},
604     'hide=s' => \$data{hide},
605     'unhide=s' => \$data{unhide},
606     'year=i' => \$opt_year,
607     'date=s' => \$opt_date,
608     'direction|d=s' => \$opt_direction,
609     'mailto:s' => \$data{mailto},
610     'all' => \$opt_all,
611     'csv' => \$opt_csv,
612     'verbose' => \$opt_verbose,
613     'help' => \&usage,
614     'dm' => sub {$table = "sales_dm"},
615     'buchung-input|bi' => \&buchung_input,
616     'buchung-unpaid|bu' => \&buchung_unpaid,
617     'buchung-hidden|bh' => \&buchung_hidden,
618     'list-categories|lc' => \$data{'list-categories'},
619     );
620
621 my $cmdln = 'infocon ' . join (' ', @ARGV);
622 GetOptions(%options);
623
624 if ($opt_year != 0 && $opt_year < 2002) {
625     $table = "sales_dm";
626 }
627
628 if (defined $opt_direction) {
629     usage unless $opt_direction =~ /^(in|out)$/i;
630 }
631
632 if (defined $data{mailto}) {
633     if (open(STDOUT, "| /usr/sbin/sendmail -t")) {
634         print  "From: Joey Schulze <joey\@infodrom.org>\n";
635         printf "To: %s\n", length($data{mailto})?$data{mailto}:'Joey Schulze <joey@infodrom.org>';
636         printf "Subject: %s\n", $cmdln;
637         print  "MIME-Version: 1.0\n";
638         print  "Content-type: text/plain; charset=iso-8859-1\n";
639         print  "Content-Disposition: inline\n";
640         print  "Content-Transfer-Encoding: 8bit\n";
641         print  "\n";
642     }
643 }
644
645 if (defined $data{category}) {
646     sales_list;
647     exit;
648 } elsif (defined $data{'list-categories'}) {
649     list_categories;
650 } elsif (defined $data{pay}) {
651     pay_invoice($data{pay}, 1);
652 } elsif (defined $data{unpay}) {
653     pay_invoice($data{unpay}, 0);
654 } elsif (defined $data{hide}) {
655     hide_invoice($data{hide}, 1);
656 } elsif (defined $data{unhide}) {
657     hide_invoice($data{unhide}, 0);
658 } else {
659     usage;
660 }