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