]> git.donarmstrong.com Git - bin.git/blob - make_invoice
update make invoice
[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                );
109
110 GetOptions(\%options,
111            'log|l=s','template|t=s','invoice|i=s','svn|s!',
112            'time_granularity|time-granularity|g=s',
113            'time_interval|min-time-interval|T=s',
114            'hourly_fee|hourly-fee|f=s',
115            'log_only|log-only',
116            'debug|d+','help|h|?','man|m');
117
118 pod2usage() if $options{help};
119 pod2usage({verbose=>2}) if $options{man};
120
121 $DEBUG = $options{debug};
122
123 my @USAGE_ERRORS;
124 if (not defined $options{log}) {
125      push @USAGE_ERRORS,"You must pass a log file with --log";
126 }
127 if (not defined $options{template}) {
128      push @USAGE_ERRORS,"You must pass a template file with --template";
129 }
130
131 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
132
133 if (not defined $options{svn}) {
134      $options{svn} = -e '.svn';
135 }
136
137
138 my $log_fh = IO::File->new($options{log},'r') or
139      die "Unable to open $options{log} for reading: $!";
140 my $template_fh = IO::File->new($options{template},'r') or
141      die "Unable to open $options{template} for reading: $!";
142
143
144 my $calc_log = '';
145 my $tex_log = <<'EOF';
146 \setlength\LTleft{0pt plus 1fill minus 1fill}%
147 \let\LTright\LTleft
148 \begin{longtable}{|p{9cm}|r|r|r|r|}%
149 %  \caption*{}
150 \hline
151   \mbox{Description} & Item Cost & Quantity & Cost & Total \\
152 \endhead
153 EOF
154 my $totaldelta = undef;
155
156 my $total = 0;
157
158 my $first_date = undef;
159 my $last_date = undef;
160 my $time = undef;
161 my $date = undef;
162 my $date2 = undef;
163 my @events;
164
165 while (<$log_fh>) {
166      chomp;
167      next if /^Total: \d+\.\d{2}$/;
168      if (/^\s*\* /) {
169           if (defined $time) {
170                $tex_log .= format_events(date => $date,
171                                          date2 => $date2,
172                                          time => $time,
173                                          total => \$total,
174                                          events => \@events);
175                @events = ();
176                $date = undef;
177                $time = undef;
178           }
179           s/\s*\[[\.\d]+\]\s*\[[\.\d]+\]\s*$//;
180           my $string = $_;
181           my ($d1,$d2) = map {s/^\s*\*\s*//;
182                              UnixDate(ParseDate($_),'%s')
183                         } split /\s*-\s*/;
184           if (not defined $first_date) {
185                $first_date = $d1;
186           }
187           $last_date = $d2;
188           my $delta = $d2-$d1;
189           $date = $d1;
190           $date2 = $d2;
191           my $hours = $delta / (60*60);
192           if ($hours < $options{time_interval}) {
193                $hours = $options{time_interval}
194           }
195           if ($options{time_granularity} > 0) {
196                $hours = ceil($hours / $options{time_granularity})*$options{time_granularity};
197           }
198           $time = $hours;
199           $totaldelta += $delta;
200           $calc_log .= qq($string [).sprintf('%.2f',$hours).qq(] [).sprintf('%.2f',$totaldelta/(60*60)).qq(]\n);
201      }
202      elsif (/^\s+-\s*(.+)/) {
203           my $event = $1;
204           chomp $event;
205           push @events,$event;
206           $calc_log .= $_.qq(\n);
207      }
208      else {
209           $calc_log .= $_.qq(\n);
210      }
211 }
212 $calc_log .= "\nTotal: ".sprintf('%.2f',$totaldelta/(60*60)).qq(\n);
213 if (defined $time) {
214     $tex_log .= format_events(date => $date,
215                                date2 => $date2,
216                               time => $time,
217                               total => \$total,
218                               events => \@events);
219      @events = ();
220      $date = undef;
221      $date2 = undef;
222      $time = undef;
223 }
224
225 $tex_log .= <<'EOF';
226 \hline\hline
227 \multicolumn{4}{|r|}{\textbf{Total}} & \$%
228 EOF
229
230 $tex_log .= sprintf('%.2f',$total)."%\n";
231
232 $tex_log .= <<'EOF';
233 \\
234 \hline
235 \end{longtable}
236 EOF
237
238 my $template;
239 {
240      local $/;
241      $template = <$template_fh>;
242 }
243
244 my $invoice_start = strftime('%c',localtime($first_date));
245 my $invoice_stop = strftime('%c',localtime($last_date));
246
247 my $tt = Text::Template->new(TYPE=>'string',
248                              SOURCE => $template,
249                              DELIMITERS => ['{--','--}'],
250                             );
251 my $tex_invoice = $tt->fill_in(HASH=>{start => $invoice_start,
252                                       stop  => $invoice_stop,
253                                       log   => $tex_log,
254                                       total => sprintf('%0.2f',$total),
255                                      }
256                               );
257 if (not defined $tex_invoice) {
258      die $Text::Template::ERROR;
259 }
260
261 if ($options{log_only}) {
262     print $calc_log;
263     exit 0;
264 }
265
266 my $invoice_date = strftime('%Y_%m_%d',localtime($last_date));
267 my $invoice_dir = "invoice_$invoice_date";
268
269 if (not -d $invoice_dir) {
270      if ($options{svn}) {
271           system('svn','mkdir',$invoice_dir) == 0 or
272                die "Unable to create invoice directory $invoice_dir";
273      }
274      else {
275           system('mkdir','-p',$invoice_dir) == 0 or
276                die "Unable to create invoice directory $invoice_dir";
277      }
278 }
279
280 my $cwd = cwd;
281 if (-e 'common_makefile' and not -e '$invoice_dir/Makefile') {
282      chdir($invoice_dir);
283      system('ln','-sf','../common_makefile','Makefile') == 0 or
284           die "Unable to link common_makefile to Makefile";
285      if ($options{svn}) {
286           system('svn','add','Makefile') == 0 or
287                die "Unable to add Makefile";
288      }
289      chdir($cwd);
290 }
291
292 # now we write stuff out
293 chdir($invoice_dir);
294 my $calc_log_fh = IO::File->new("log_${invoice_date}",'w') or
295      die "Unable to open log_${invoice_date} for writing: $!";
296 print {$calc_log_fh} $calc_log;
297 close($calc_log_fh);
298
299 my $tex_invoice_fh = IO::File->new("invoice_${invoice_date}.tex",'w') or
300      die "Unable to open log_${invoice_date} for writing: $!";
301 print {$tex_invoice_fh} $tex_invoice;
302 close($tex_invoice_fh);
303
304 if ($options{svn}) {
305      system('svn','add',
306             "log_${invoice_date}",
307             "invoice_${invoice_date}.tex",
308            ) == 0 or die "Unable to add log and invoice to svn";
309      system('svn','propset','svn:ignore',
310             "*.aux\n*.log\n*.dvi\n*.ps\n*.pdf\nauto\n",
311             '.'
312            ) == 0 or die "Unable to set svn:ignore";
313 }
314
315
316 sub format_events{
317      my %param = validate_with(params => \@_,
318                                spec   => {time => {type => SCALAR,
319                                                   },
320                                           date => {type => SCALAR,
321                                                   },
322                                           date2 => {type => SCALAR,
323                                                    },
324                                           total => {type => SCALARREF,
325                                                    },
326                                           events => {type => ARRAYREF,
327                                                     },
328                                          },
329                               );
330      ${$param{total}} += $param{time} * $options{hourly_fee};
331
332 #     $param{date} =~ s/\s+\d+\:\d+\:\d+\s+[A-Z]{0,3}\s*//;
333      my $output = '\hline'."\n".'        \mbox{'.strftime('%A, %B %e, %H:%M',localtime($param{date})).
334           ' to '.strftime('%H:%M %Z',localtime($param{date2}))."}\n\n".
335          '         \begin{itemize*}'."\n";
336      $output .= join('',map { s/_/\\_/g; "           \\item $_\n";} @{$param{events}});
337      $output .= '         \end{itemize*} & \$'.sprintf('%.2f',$options{hourly_fee}).' & '.sprintf('%.2f',$param{time}).
338          ' & \$'.sprintf('%.2f',$param{time}*$options{hourly_fee}).' & \$'.
339              sprintf('%.2f',${$param{total}}) .
340                  " \\\\\n";
341      return $output;
342 }
343
344 ## sub format_events{
345 ##      my ($date,$date2,$time,@events) = @_;
346 ##      my $output = '        \Fee{'.strftime('%A, %B %e, %H:%M',localtime(UnixDate($date,'%s'))).
347 ##        ' to '.strftime('%H:%M %Z',localtime(UnixDate($date2,'%s')))."\n".
348 ##        '         \begin{itemize*}'."\n";
349 ##      $output .= join('',map {"           \\item $_\n"} @events);
350 ##      $output .= '         \end{itemize*}}{50.00}{'.$time.'}'."\n";
351 ##      return $output;
352 ## }
353
354
355 __END__