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