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