]> git.donarmstrong.com Git - bin.git/blob - make_invoice
* add tex-only optino
[bin.git] / make_invoice
1 #! /usr/bin/perl
2 # make_invoice makes latex invoices, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2008 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 495 2006-08-10 08:02:01Z don $
7
8
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 =head1 NAME
16
17 make_invoice - makes invoices using latex
18
19 =head1 SYNOPSIS
20
21  make_invoice [options]
22
23  Options:
24   --log,-l the log file to use to make the invoice
25   --template,-t the template to use to make the invoice
26   --min-time-interval, -m minimum time to bill, default 0
27   --time-granularity, -g time granularity, default 0
28   --hourly-fee, -f hourly fee, default 50.00
29   --svn,-s whether to use subversion or not
30   --debug, -d debugging level (Default 0)
31   --help, -h display this help
32   --man, -m display manual
33
34 =head1 OPTIONS
35
36 =over
37
38 =item B<--log, -l>
39
40 The log file to use to generate the invoice
41
42 =item B<--template, -t>
43
44 The tex template to use to generate the invoice
45
46 =item B<--svn, -s>
47
48 Whether to use subversion or not; defaults to yes if .svn exists in
49 the current directory.
50
51 =item B<--invoice,-i>
52
53 Invoice directory to place invoice in (automatically calculated if not
54 passed.)
55
56 =item B<--min-time-interval, -m>
57
58 Minimum time interval to bill, defaults to 0.
59
60 =item B<--time-granularity, -g>
61
62 Time granularity, defaults to 0.
63
64 =item B<--hourly-fee,-f>
65
66 Hourly fee, defaults to 50.00
67
68 =item B<--debug, -d>
69
70 Debug verbosity. (Default 0)
71
72 =item B<--help, -h>
73
74 Display brief useage information.
75
76 =item B<--man, -m>
77
78 Display this manual.
79
80 =back
81
82 =head1 EXAMPLES
83
84
85 =cut
86
87
88 use vars qw($DEBUG);
89
90 use Date::Manip;
91 use POSIX qw(ceil strftime);
92 use Cwd qw(cwd);
93 use Text::Template;
94
95 use Params::Validate qw(validate_with :types);
96
97 my %options = (log             => undef,
98                template        => undef,
99                svn             => undef,
100                invoice         => undef,
101                time_interval   => 0.00,
102                time_granularity => 0.00,
103                hourly_fee      => '50.00',
104                debug           => 0,
105                help            => 0,
106                man             => 0,
107                log_only        => 0,
108                tex_only        => 0,
109                );
110
111 GetOptions(\%options,
112            'log|l=s','template|t=s','invoice|i=s','svn|s!',
113            'time_granularity|time-granularity|g=s',
114            'time_interval|min-time-interval|T=s',
115            'hourly_fee|hourly-fee|f=s',
116            'log_only|log-only',
117            'tex_only|tex-only',
118            'debug|d+','help|h|?','man|m');
119
120 pod2usage() if $options{help};
121 pod2usage({verbose=>2}) if $options{man};
122
123 $DEBUG = $options{debug};
124
125 my @USAGE_ERRORS;
126 if (not defined $options{log}) {
127      push @USAGE_ERRORS,"You must pass a log file with --log";
128 }
129 if (not defined $options{template}) {
130      push @USAGE_ERRORS,"You must pass a template file with --template";
131 }
132
133 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
134
135 if (not defined $options{svn}) {
136      $options{svn} = -e '.svn';
137 }
138
139
140 my $log_fh = IO::File->new($options{log},'r') or
141      die "Unable to open $options{log} for reading: $!";
142 my $template_fh = IO::File->new($options{template},'r') or
143      die "Unable to open $options{template} for reading: $!";
144
145
146 my $calc_log = '';
147 my $tex_log = <<'EOF';
148 \setlength\LTleft{0pt plus 1fill minus 1fill}%
149 \let\LTright\LTleft
150 \begin{longtable}{|p{9cm}|r|r|r|r|}%
151 %  \caption*{}
152 \hline
153   \mbox{Description} & Item Cost & Quantity & Cost & Total \\
154 \endhead
155 EOF
156 my $totaldelta = undef;
157
158 my $total = 0;
159
160 my $first_date = undef;
161 my $last_date = undef;
162 my $time = undef;
163 my $date = undef;
164 my $date2 = undef;
165 my @events;
166
167 while (<$log_fh>) {
168      chomp;
169      next if /^Total: \d+\.\d{2}$/;
170      if (/^\s*\* /) {
171           if (defined $time) {
172                $tex_log .= format_events(date => $date,
173                                          date2 => $date2,
174                                          time => $time,
175                                          total => \$total,
176                                          events => \@events);
177                @events = ();
178                $date = undef;
179                $time = undef;
180           }
181           s/\s*\[[\.\d]+\]\s*\[[\.\d]+\]\s*$//;
182           my $string = $_;
183           my ($d1,$d2) = map {s/^\s*\*\s*//;
184                              UnixDate(ParseDate($_),'%s')
185                         } split /\s*-\s*/;
186           if (not defined $first_date) {
187                $first_date = $d1;
188           }
189           $last_date = $d2;
190           my $delta = $d2-$d1;
191           $date = $d1;
192           $date2 = $d2;
193           my $hours = $delta / (60*60);
194           if ($hours < $options{time_interval}) {
195                $hours = $options{time_interval}
196           }
197           if ($options{time_granularity} > 0) {
198                $hours = ceil($hours / $options{time_granularity})*$options{time_granularity};
199           }
200           $time = $hours;
201           $totaldelta += $delta;
202           $calc_log .= qq($string [).sprintf('%.2f',$hours).qq(] [).sprintf('%.2f',$totaldelta/(60*60)).qq(]\n);
203      }
204      elsif (/^\s+-\s*(.+)/) {
205           my $event = $1;
206           chomp $event;
207           push @events,$event;
208           $calc_log .= $_.qq(\n);
209      }
210      else {
211           $calc_log .= $_.qq(\n);
212      }
213 }
214 $calc_log .= "\nTotal: ".sprintf('%.2f',$totaldelta/(60*60)).qq(\n);
215 if (defined $time) {
216     $tex_log .= format_events(date => $date,
217                                date2 => $date2,
218                               time => $time,
219                               total => \$total,
220                               events => \@events);
221      @events = ();
222      $date = undef;
223      $date2 = undef;
224      $time = undef;
225 }
226
227 $tex_log .= <<'EOF';
228 \hline\hline
229 \multicolumn{4}{|r|}{\textbf{Total}} & \$%
230 EOF
231
232 $tex_log .= sprintf('%.2f',$total)."%\n";
233
234 $tex_log .= <<'EOF';
235 \\
236 \hline
237 \end{longtable}
238 EOF
239
240 my $template;
241 {
242      local $/;
243      $template = <$template_fh>;
244 }
245
246 my $invoice_start = strftime('%c',localtime($first_date));
247 my $invoice_stop = strftime('%c',localtime($last_date));
248
249 my $tt = Text::Template->new(TYPE=>'string',
250                              SOURCE => $template,
251                              DELIMITERS => ['{--','--}'],
252                             );
253 my $tex_invoice = $tt->fill_in(HASH=>{start => $invoice_start,
254                                       stop  => $invoice_stop,
255                                       log   => $tex_log,
256                                       total => sprintf('%0.2f',$total),
257                                      }
258                               );
259 if (not defined $tex_invoice) {
260      die $Text::Template::ERROR;
261 }
262
263 if ($options{log_only}) {
264     print $calc_log;
265     exit 0;
266 }
267
268 if ($options{tex_only}) {
269     print $tex_invoice;
270     exit 0;
271 }
272
273
274 my $invoice_date = strftime('%Y_%m_%d',localtime($last_date));
275 my $invoice_dir = "invoice_$invoice_date";
276
277 if (not -d $invoice_dir) {
278      if ($options{svn}) {
279           system('svn','mkdir',$invoice_dir) == 0 or
280                die "Unable to create invoice directory $invoice_dir";
281      }
282      else {
283           system('mkdir','-p',$invoice_dir) == 0 or
284                die "Unable to create invoice directory $invoice_dir";
285      }
286 }
287
288 my $cwd = cwd;
289 if (-e 'common_makefile' and not -e '$invoice_dir/Makefile') {
290      chdir($invoice_dir);
291      system('ln','-sf','../common_makefile','Makefile') == 0 or
292           die "Unable to link common_makefile to Makefile";
293      if ($options{svn}) {
294           system('svn','add','Makefile') == 0 or
295                die "Unable to add Makefile";
296      }
297      chdir($cwd);
298 }
299
300 # now we write stuff out
301 chdir($invoice_dir);
302 my $calc_log_fh = IO::File->new("log_${invoice_date}",'w') or
303      die "Unable to open log_${invoice_date} for writing: $!";
304 print {$calc_log_fh} $calc_log;
305 close($calc_log_fh);
306
307 my $tex_invoice_fh = IO::File->new("invoice_${invoice_date}.tex",'w') or
308      die "Unable to open log_${invoice_date} for writing: $!";
309 print {$tex_invoice_fh} $tex_invoice;
310 close($tex_invoice_fh);
311
312 if ($options{svn}) {
313      system('svn','add',
314             "log_${invoice_date}",
315             "invoice_${invoice_date}.tex",
316            ) == 0 or die "Unable to add log and invoice to svn";
317      system('svn','propset','svn:ignore',
318             "*.aux\n*.log\n*.dvi\n*.ps\n*.pdf\nauto\n",
319             '.'
320            ) == 0 or die "Unable to set svn:ignore";
321 }
322
323
324 sub format_events{
325      my %param = validate_with(params => \@_,
326                                spec   => {time => {type => SCALAR,
327                                                   },
328                                           date => {type => SCALAR,
329                                                   },
330                                           date2 => {type => SCALAR,
331                                                    },
332                                           total => {type => SCALARREF,
333                                                    },
334                                           events => {type => ARRAYREF,
335                                                     },
336                                          },
337                               );
338      ${$param{total}} += $param{time} * $options{hourly_fee};
339
340 #     $param{date} =~ s/\s+\d+\:\d+\:\d+\s+[A-Z]{0,3}\s*//;
341      my $output = '\hline'."\n".'        \mbox{'.strftime('%A, %B %e, %H:%M',localtime($param{date})).
342           ' to '.strftime('%H:%M %Z',localtime($param{date2}))."}\n\n".
343          '         \begin{itemize*}'."\n";
344      $output .= join('',map { s/_/\\_/g; "           \\item $_\n";} @{$param{events}});
345      $output .= '         \end{itemize*} & \$'.sprintf('%.2f',$options{hourly_fee}).' & '.sprintf('%.2f',$param{time}).
346          ' & \$'.sprintf('%.2f',$param{time}*$options{hourly_fee}).' & \$'.
347              sprintf('%.2f',${$param{total}}) .
348                  " \\\\\n";
349      return $output;
350 }
351
352 ## sub format_events{
353 ##      my ($date,$date2,$time,@events) = @_;
354 ##      my $output = '        \Fee{'.strftime('%A, %B %e, %H:%M',localtime(UnixDate($date,'%s'))).
355 ##        ' to '.strftime('%H:%M %Z',localtime(UnixDate($date2,'%s')))."\n".
356 ##        '         \begin{itemize*}'."\n";
357 ##      $output .= join('',map {"           \\item $_\n"} @events);
358 ##      $output .= '         \end{itemize*}}{50.00}{'.$time.'}'."\n";
359 ##      return $output;
360 ## }
361
362
363 __END__