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