Open new tab for editing items
[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 pay_invoice
91 {
92     my $nr = shift;
93     my $pay = shift;
94     my $query;
95     my $sth;
96
97     if ($pay) {
98         $query  = sprintf("UPDATE sales SET paid=1,billing_date=%s WHERE nr = %d",
99                           defined $opt_date ? $dbh->quote($opt_date) : 'now()', $nr);
100     } else {
101         $query  = sprintf("UPDATE sales SET paid=0,billing_date=NULL WHERE nr = %d", $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,billing_date,paid) " .
452                              "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
453
454     print "Buchungseingabe\n\n";
455     while ($weiter =~ /[JjYy1]/) {
456         foreach my $f (@fields) {
457             if ($f eq 'tax_assigned' && $answers->{'tax_percent'} == 0) {
458                 $answers->{$f} = 0;
459                 next;
460             } elsif ($f eq 'paid') {
461                 if ($answers->{paid}) {
462                     my @now = localtime(time);
463                     $answers->{billing_date} = sprintf('%04d-%02d-%02d', $now[5]+1900, $now[4]+1, $now[3]);
464                 } else {
465                     $answers->{billing_date} = undef;
466                 }
467             }
468             $ans = read_input($f, $fields->{$f});
469             $answers->{$f} = $ans;
470         }
471
472         $sth->execute(get_next_nr(),
473                       date_to_string($answers->{date}),
474                       $answers->{pdf},
475                       $answers->{year},
476                       $answers->{category},
477                       $answers->{description},
478                       $answers->{tax_percent},
479                       $answers->{tax_assigned},
480                       $answers->{price},
481                       $answers->{billing_date},
482                       $answers->{paid});
483
484         $weiter = $answers->{weiter};
485         $answers->{tax_assigned} = 0.0;
486     }
487
488     exit;
489 }
490
491 sub buchung_hidden
492 {
493     $table = "sales_dm";
494     sales_list("visible = 0");
495     $table = "sales";
496     sales_list("visible = 0");
497     exit;
498 }
499
500 sub buchung_unpaid
501 {
502     $table = "sales";
503     sales_list("paid = 0");
504     exit;
505 }
506
507 sub usage
508 {
509     print "infocon [options] [-h|--help] commands\n";
510     print "  --buchung-category|-bc [category]\n";
511     print "  --buchung-input|-bi\n";
512     print "  --buchung-unpaid\n";
513     print "  --buchung-hidden\n";
514     print "  --date yyyy-mm-dd (for --pay)\n";
515     print "  --pay <nr> | --unpay <nr>\n";
516     print "  --hide <nr> | --unhide <nr>\n";
517     print "  --list-categories|-lc\n";
518     print "  Options:\n";
519     print "    --all|-a\n";
520     print "    --verbose|-v\n";
521     print "    --year|-y year\n";
522     print "    --direction|--dir|-d in|out\n";
523     print "    --dm\n";
524     exit 0;
525 }
526
527 %data = (
528     'category' => undef,
529     'done' => undef,
530     'pay' => undef,
531     'unpay' => undef,
532     'hide' => undef,
533     'unhide' => undef,
534     'mailto' => undef,
535     'buchung-input' => undef,
536     'buchung-unpaid' => undef,
537     'buchung-hidden' => undef,
538     'list-categories' => undef,
539     );
540 my %options = (
541     'buchung-category|bc:s' => \$data{category},
542     'pay=s' => \$data{pay},
543     'unpay=s' => \$data{unpay},
544     'hide=s' => \$data{hide},
545     'unhide=s' => \$data{unhide},
546     'year=i' => \$opt_year,
547     'date=s' => \$opt_date,
548     'direction|d=s' => \$opt_direction,
549     'mailto:s' => \$data{mailto},
550     'all' => \$opt_all,
551     'verbose' => \$opt_verbose,
552     'help' => \&usage,
553     'dm' => sub {$table = "sales_dm"},
554     'buchung-input|bi' => \$data{'buchung-input'},
555     'buchung-unpaid|bu' => \$data{'buchung-unpaid'},
556     'buchung-hidden|bh' => \$data{'buchung-hidden'},
557     'list-categories|lc' => \$data{'list-categories'},
558     );
559
560 my $cmdln = 'infocon ' . join (' ', @ARGV);
561 GetOptions(%options);
562
563 if ($opt_year != 0 && $opt_year < 2002) {
564     $table = "sales_dm";
565 }
566
567 if (defined $opt_direction) {
568     usage unless $opt_direction =~ /^(in|out)$/i;
569 }
570
571 if (defined $data{mailto}) {
572     if (open(STDOUT, "| /usr/sbin/sendmail -t")) {
573         print  "From: Joey Schulze <joey\@infodrom.org>\n";
574         printf "To: %s\n", length($data{mailto})?$data{mailto}:'Joey Schulze <joey@infodrom.org>';
575         printf "Subject: %s\n", $cmdln;
576         print  "MIME-Version: 1.0\n";
577         print  "Content-type: text/plain; charset=iso-8859-1\n";
578         print  "Content-Disposition: inline\n";
579         print  "Content-Transfer-Encoding: 8bit\n";
580         print  "\n";
581     }
582 }
583
584 if (defined $data{category}) {
585     if (length($data{category})) {
586         sales_list("category = '".$data{category}."'");
587     } else {
588         sales_list;
589     }
590     exit;
591 } elsif (defined $data{'buchung-input'}) {
592     buchung_input;
593 } elsif (defined $data{'buchung-unpaid'}) {
594     buchung_unpaid;
595 } elsif (defined $data{'buchung-hidden'}) {
596     buchung_hidden;
597 } elsif (defined $data{'list-categories'}) {
598     list_categories;
599 } elsif (defined $data{pay}) {
600     pay_invoice($data{pay}, 1);
601 } elsif (defined $data{unpay}) {
602     pay_invoice($data{unpay}, 0);
603 } elsif (defined $data{hide}) {
604     hide_invoice($data{hide}, 1);
605 } elsif (defined $data{unhide}) {
606     hide_invoice($data{unhide}, 0);
607 } else {
608     usage;
609 }