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