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