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