Annotation of RT/Invoicing/rt_invoices.pl, Revision 1.11
1.1 andrew 1: #!/usr/bin/perl
1.11 ! andrew 2: # $AFresh1$
! 3: ########################################################################
! 4: # Copyright (c) 2011 Andrew Fresh <andrew@afresh1.com>
! 5: #
! 6: # Permission to use, copy, modify, and distribute this software for any
! 7: # purpose with or without fee is hereby granted, provided that the above
! 8: # copyright notice and this permission notice appear in all copies.
! 9: #
! 10: # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
! 11: # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
! 12: # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
! 13: # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
! 14: # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
! 15: # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
! 16: # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
! 17: ########################################################################
1.1 andrew 18: use strict;
19: use warnings;
20:
21: use 5.010;
22:
23: use YAML::Any;
24: use Template;
25: use RT::Client::REST;
26: use RT::Client::REST::Ticket;
27: use RT::Client::REST::User;
28:
29: use DateTime;
30:
31: my $config = RTI::Config->new();
1.6 andrew 32: my $state = RTI::State->new( $config->get('state') );
1.1 andrew 33:
1.6 andrew 34: my $rt_conf = $config->get('rt');
35: my $rt = RT::Client::REST->new(
36: server => $rt_conf->{server},
37: timeout => $rt_conf->{timeout},
38: );
39: my $tickets = RT::Client::REST::Ticket->new( rt => $rt );
40: my $users = RT::Client::REST::User->new( rt => $rt );
1.1 andrew 41:
1.6 andrew 42: $rt->login( username => $rt_conf->{user}, password => $rt_conf->{pass} );
43:
44: #print Dump $config, $state; exit;
1.1 andrew 45:
46: my $startdate;
1.3 andrew 47:
1.6 andrew 48: my $customers = $config->get('customers');
49: CUSTOMER: while ( my ( $custid, $cust ) = each %{$customers} ) {
50:
51: my %invoice = ( end => DateTime->now, );
1.1 andrew 52:
53: if ( $cust->{base_rate} ) {
1.3 andrew 54: my $day = $cust->{day} || 1;
1.1 andrew 55: my $freq = $cust->{frequency} || 1;
56:
1.7 andrew 57: my $per;
1.3 andrew 58: my $day_method;
1.1 andrew 59: given ( $cust->{per} ) {
1.3 andrew 60: when ('week') { $per = 'weeks'; $day_method = 'dow' }
61: when ('month') { $per = 'months'; $day_method = 'day' }
1.1 andrew 62: default { die "Unknown per [$cust->{per}]\n" }
63: }
64:
1.6 andrew 65: my $billends
1.3 andrew 66: = DateTime->now->set( hour => 0, minute => 0, second => 0 );
1.7 andrew 67: $billends->subtract( days => 1 ) while $billends->$day_method != $day;
1.3 andrew 68:
1.6 andrew 69: my $date = $billends->clone->subtract( $per => $freq );
70:
71: my $lastinvoice = $state->last_invoice($custid);
72: if ( $lastinvoice->{date} ) {
73: my $last_invoice_date = ymd_to_DateTime( $lastinvoice->{date} );
74: $date = $last_invoice_date->clone->add( days => 1 );
75: }
1.1 andrew 76:
1.7 andrew 77: next CUSTOMER if $billends <= $date;
78:
1.1 andrew 79: my $title
80: = $freq == 1
81: ? ucfirst( $cust->{per} . 'ly' )
82: : $freq . ' ' . ucfirst( $cust->{per} );
83: $title .= ' Retainer';
84:
85: my %project = ( title => $title, fees => [], );
86:
1.6 andrew 87: while ( $date < $billends ) {
1.3 andrew 88: my $start = $date->clone;
89:
90: $date->add( $per => $freq );
1.6 andrew 91: $date = $billends->clone if $date > $billends;
1.7 andrew 92:
93: # XXX This is helpful, but monthly and billday > 28 == !!!
94: $date->subtract( days => 1 ) while $date->$day_method != $day;
1.3 andrew 95:
1.6 andrew 96: my $end = $date->clone->subtract( seconds => 1 );
1.3 andrew 97:
1.7 andrew 98: next if $end < $start;
99:
1.4 andrew 100: $startdate = $start->clone if !$startdate || $startdate > $start;
1.3 andrew 101: $invoice{start} ||= $start->clone;
102: $invoice{end} = $end->clone;
1.1 andrew 103: my %hours = (
1.3 andrew 104: start => $start->clone,
105: end => $end->clone,
1.1 andrew 106: hours => { %{ $cust->{hours} } },
107: );
108:
1.3 andrew 109: push @{ $invoice{hours} }, \%hours;
110: push @{ $project{fees} },
1.1 andrew 111: {
112: count => 1,
113: rate => $cust->{base_rate},
1.3 andrew 114: contents => $start->ymd . ' to ' . $end->ymd,
1.1 andrew 115: };
116:
117: }
118:
1.3 andrew 119: if ( @{ $project{fees} } ) {
1.2 andrew 120: push @{ $invoice{projects} }, \%project;
121: }
1.1 andrew 122: }
123:
1.9 andrew 124: $cust->{from} ||= get_user($custid);
1.6 andrew 125: $cust->{invoice} = \%invoice;
1.1 andrew 126: }
127:
128: my @limits = map +{
129: attribute => 'status',
130: operator => '=',
131: value => $_,
132: aggregator => 'or',
133: },
134:
135: # XXX This should be a config option
136: qw/ open stalled resolved /;
137:
138: if ($startdate) {
139: push @limits,
140: {
141: attribute => 'last_updated',
142: operator => '>=',
143: value => $startdate->ymd,
144: };
145: }
146:
147: my $results = $tickets->search(
148: limits => \@limits,
149: orderby => 'id',
150: );
151:
152: my $count = $results->count;
153: print "There are $count results that matched your query\n";
154:
155: my $iterator = $results->get_iterator;
156: while ( my $ticket = &$iterator ) {
1.6 andrew 157: my $cust = find_customer_for_ticket( $customers, $ticket );
158: if ( !$cust ) {
1.10 andrew 159: warn "No customer found for ticket " . $ticket->id;
1.7 andrew 160: next;
161: }
162: if ( !$cust->{invoice} ) {
1.10 andrew 163: #say "Customer has no open invoices for ticket " . $ticket->id;
1.4 andrew 164: next;
165: }
1.6 andrew 166: my $invoice = $cust->{invoice};
1.1 andrew 167:
1.7 andrew 168: my $project = make_project( $ticket, $cust );
1.6 andrew 169: next unless @{ $project->{fees} } || @{ $project->{expenses} };
1.1 andrew 170:
1.6 andrew 171: foreach my $fee ( @{ $project->{fees} } ) {
172: my $hours = hours_for_date( $invoice, $fee->{date} );
1.1 andrew 173:
1.3 andrew 174: my $h_type
1.4 andrew 175: = exists $hours->{ $fee->{type} }
176: ? $fee->{type}
1.1 andrew 177: : 'default';
178:
1.4 andrew 179: next unless exists $hours->{$h_type} && $hours->{$h_type} > 0;
1.1 andrew 180:
181: my $discount_time = 0;
1.4 andrew 182: if ( $hours->{$h_type} > $fee->{count} ) {
183: $hours->{$h_type} -= $fee->{count};
184: $discount_time = $fee->{count};
1.1 andrew 185: }
186: else {
1.3 andrew 187: $discount_time = $hours->{$h_type};
188: $hours->{$h_type} = 0;
1.1 andrew 189: }
190:
191: if ($discount_time) {
1.4 andrew 192: $invoice->{discount}{amount} += $discount_time * $fee->{rate};
193: $invoice->{discount}{hours}{$h_type} += $discount_time;
194:
195: $h_type = '' if $h_type eq 'default';
196: $fee->{detail} = "$discount_time $h_type Hours Discounted";
1.1 andrew 197: }
198: }
199:
1.6 andrew 200: push @{ $invoice->{projects} }, $project;
1.1 andrew 201: }
202:
1.6 andrew 203: while ( my ( $custid, $cust ) = each %{$customers} ) {
204: my $invoice = $cust->{invoice};
1.1 andrew 205: next unless $invoice->{projects} && @{ $invoice->{projects} };
206:
1.7 andrew 207: my %li = ( custid => $custid, );
208:
1.1 andrew 209: foreach my $project ( @{ $invoice->{projects} } ) {
1.6 andrew 210: if ( $project->{transactions} ) {
1.7 andrew 211: push @{ $li{transactions} }, @{ $project->{transactions} };
1.6 andrew 212: }
1.1 andrew 213: my $subtotal = 0;
214: foreach my $fee ( @{ $project->{fees} } ) {
215: my $amount = round( $fee->{count} * $fee->{rate} );
216: $subtotal += $amount;
217: }
218: foreach my $expense ( @{ $project->{expenses} } ) {
219: $subtotal += round( $expense->{amount} );
220: }
221: $project->{total} = $subtotal;
222: $invoice->{total} += $subtotal;
223: }
224:
225: if ( $invoice->{discount} ) {
226: my $c = "Included Hours\n";
227: if ( $invoice->{discount}{hours} ) {
228: foreach my $t ( keys %{ $invoice->{discount}{hours} } ) {
229: $c .= "\n$invoice->{discount}{hours}{$t} $t hour";
230: $c .= 's' if $invoice->{discount}{hours}{$t} != 1;
231: $c .= "\n";
232: }
233: }
234: $invoice->{discount}{contents} = $c;
235: $invoice->{total} -= round( $invoice->{discount}{amount} );
236: }
237:
238: if ( $invoice->{past_due} ) {
239: $invoice->{total_due} = $invoice->{total} + $invoice->{past_due};
1.3 andrew 240: }
241:
1.9 andrew 242: next unless $invoice->{total} > 0 || $invoice->{total_due};
243:
1.6 andrew 244: # XXX Here we need to "make_address"
245: $invoice->{info} = $config->get('info');
246: $invoice->{from} = $config->get('from');
247: $invoice->{to} = $cust->{address};
248:
249: $state->{lastinvoice}++;
250: $invoice->{id} = $state->{lastinvoice};
251: $invoice->{file} = 'invoice_' . $state->{lastinvoice} . '.pdf';
252:
1.10 andrew 253: foreach my $k (qw/ file transactions start end total past_due total_due /)
254: {
255: my $v;
256: if ( $invoice->{$k} ) { $v = $invoice->{$k} }
257: elsif ( $cust->{$k} ) { $v = $cust->{$k} }
258:
259: if (defined $v && length $v) {
260: if ( ref $v eq 'DateTime' ) {
261: $li{$k} = $v->ymd;
262: }
263: else {
264: $li{$k} = $v;
265: }
266: }
267: }
268: $state->{invoice}->{ $li{end} }{ $invoice->{id} } = \%li;
269:
1.3 andrew 270: foreach my $key (qw/ start end /) {
271: if ( exists $invoice->{$key} ) {
272: $invoice->{$key} = $invoice->{$key}->strftime('%B %d, %Y');
273: }
1.1 andrew 274: }
275: my $tt = Template->new;
276: $tt->process( 'invoice.tex.tt', $invoice, $invoice->{file} )
277: or die $tt->error . "\n";
278:
1.9 andrew 279: printf "Generated %s for %s: \$%.02f\n", $invoice->{file}, $custid,
280: $invoice->{total};
1.1 andrew 281: }
282:
1.6 andrew 283: $state->save;
1.1 andrew 284:
285: sub round {
286: my ($amount) = @_;
287:
288: #$amount =~ s/\.\d\d\K.*$//;
289: #return $amount;
290: return sprintf "%.02f", $amount;
1.4 andrew 291: }
292:
1.6 andrew 293: sub find_customer_for_ticket {
294: my ( $customers, $ticket ) = @_;
1.4 andrew 295:
1.6 andrew 296: INVOICE: foreach my $cust ( values %{$customers} ) {
297: next INVOICE unless $cust->{match};
298: foreach my $m ( @{ $cust->{match} } ) {
1.4 andrew 299: my $type = $m->{type};
300: my $thing = join ' ', $ticket->$type;
301:
302: if ( $m->{$type} ) {
303: my $match = lc $m->{$type};
304: next INVOICE unless lc($thing) ~~ $match;
305: }
306: elsif ( $m->{regex} ) {
307: next INVOICE unless $thing ~~ /\Q$m->{regex}\E/;
308: }
309: else {
310: warn "Invalid match!";
311: next INVOICE;
312: }
313: }
1.6 andrew 314: return $cust;
315: }
316:
1.8 andrew 317: return fake_customer( $customers, $ticket );
1.6 andrew 318: }
319:
320: sub fake_customer {
1.8 andrew 321: my ( $customers, $ticket ) = @_;
322:
323: # make the custid the first requestor
324: my ($custid) = $ticket->requestors;
325: return unless $custid;
326:
327: my $cust = $config->get('default') || {};
1.9 andrew 328: $cust->{to} = get_user($custid);
1.8 andrew 329:
330: my %invoice = ( end => DateTime->now );
331:
332: my $lastinvoice = $state->last_invoice($custid);
333: if ( $lastinvoice->{date} ) {
334: my $last_invoice_date = ymd_to_DateTime( $lastinvoice->{date} );
335: $invoice{start} = $last_invoice_date->clone->add( days => 1 );
336: }
337:
338: if ( !( $invoice{start} && $invoice{start} < $invoice{end} ) ) {
339: $cust->{invoice} = \%invoice;
340: }
341:
342: $customers->{$custid} = $cust;
343: return $cust;
344: }
345:
1.9 andrew 346: sub get_user {
1.8 andrew 347: my ($id) = @_;
348:
1.9 andrew 349: state %users;
350: return $users{$id} if $users{$id};
1.8 andrew 351:
352: my %map = (
353: address_one => 'addr1',
354: address_two => 'addr2',
355: email_address => 'email',
1.9 andrew 356: real_name => 'name',
357: name => 'username',
1.8 andrew 358: );
359:
360: $users->id($id);
361: $users->retrieve;
362:
1.9 andrew 363: my %user;
1.8 andrew 364: foreach my $m ( keys %{ $users->_attributes } ) {
365: next unless $users->can($m);
366:
367: my $v = $users->$m;
368: next unless $v;
369:
370: $m = $map{$m} if exists $map{$m};
371:
1.9 andrew 372: $user{$m} = $v;
1.8 andrew 373: }
1.6 andrew 374:
1.9 andrew 375: $users{$id} = \%user;
376: return \%user;
1.6 andrew 377: }
378:
379: sub make_project {
1.7 andrew 380: my ( $ticket, $cust ) = @_;
1.6 andrew 381:
382: my %project = (
383: id => $ticket->id,
384: queue => $ticket->queue,
385: owner => $ticket->owner,
386: title => $ticket->subject,
387: detail => 'Ticket: '
388: . $ticket->id
389: . ' Queue: '
390: . $ticket->queue
391: . ' Requestors: '
392: . join( ', ', $ticket->requestors ),
393: fees => [],
394: expenses => [],
395: );
396:
397: my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
398: my $txn_i = $txns->get_iterator;
399: while ( my $txn = $txn_i->() ) {
400: next unless $txn->time_taken;
401: next if $state->txn_is_invoiced( $txn->id );
402:
1.7 andrew 403: my $fee = make_fee( $txn, $cust->{rates}, $ticket );
404:
1.6 andrew 405: if ( !( $fee->{rate} && $fee->{count} ) ) {
406: warn "Invalid Fee, no rate or count";
407: next;
408: }
409:
1.7 andrew 410: my $invoice = $cust->{invoice};
411: next
412: if $invoice->{start}
413: && $invoice->{start} > $fee->{date};
1.6 andrew 414: next if $invoice->{end} < $fee->{date};
415:
416: push @{ $project{fees} }, $fee;
417: push @{ $project{transactions} }, $txn->id;
1.4 andrew 418: }
1.6 andrew 419:
420: return \%project;
1.4 andrew 421: }
422:
423: sub make_fee {
1.7 andrew 424: my ( $txn, $rates, $ticket ) = @_;
425:
426: # XXX Only need $ticket for the alternate subject
1.4 andrew 427:
428: my $work_time = sprintf "%.03f", $txn->time_taken / 60;
429: my $work_type = $txn->cf('WorkType');
430:
431: my %fee = (
432: id => $txn->id,
433: contents => $txn->created . ' ('
434: . $txn->id . ')' . "\n\n"
435: . ( $txn->data || $ticket->subject ),
436: count => $work_time,
437: type => $work_type,
1.6 andrew 438: date => ymd_to_DateTime( $txn->created ),
1.7 andrew 439: rate => $rates->{$work_type} || $rates->{default} || 0,
1.4 andrew 440: );
441:
442: if ( $work_type && $work_type ne 'Normal' ) {
443: $fee{detail} = $work_type . ' rate';
444: }
445:
446: return \%fee;
447: }
448:
449: sub hours_for_date {
450: my ( $invoice, $date ) = @_;
451:
452: my $hours = {};
453: if ( $invoice->{hours} ) {
454: foreach my $h ( @{ $invoice->{hours} } ) {
455: next if $h->{start} && $h->{start} > $date;
456: next if $h->{end} < $date;
457:
458: $hours = $h->{hours};
459: last;
460: }
461: }
462: return $hours;
1.1 andrew 463: }
464:
1.6 andrew 465: sub ymd_to_DateTime {
466: my ($ymd) = @_;
1.10 andrew 467: my ( $date, $time ) = split /[\sT]/, $ymd;
1.6 andrew 468: my ( $year, $month, $day ) = split '-', $date;
469: my ( $hour, $minute, $second ) = split ':', $time if $time;
470:
471: return DateTime->new(
472: year => $year,
473: month => $month,
474: day => $day,
475: hour => $hour || 0,
476: minute => $minute || 0,
477: second => $second || 0,
478: );
479: }
480:
1.1 andrew 481: package RTI::Config;
482: use strict;
483: use warnings;
484:
485: use 5.010;
486:
1.5 andrew 487: use YAML::Any qw/ LoadFile Dump Load /;
1.6 andrew 488: use File::Basename;
1.1 andrew 489:
490: sub new {
491: my ( $class, $args ) = @_;
492:
493: my $self = { file => '', };
494: bless $self, $class;
1.5 andrew 495:
1.1 andrew 496: my $file = $args->{file} || $self->_find_config;
497: $self->read_config($file);
498:
499: return $self;
500: }
501:
502: sub _find_config {
503: my ($self) = @_;
504:
505: # XXX This needs to be better
506: foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
1.6 andrew 507: foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoicing', $ENV{HOME} ) {
1.1 andrew 508: my $path = join '/', $dir, $file;
509: return $path if -e $path;
510: }
511: }
512: return;
513: }
514:
515: sub read_config {
516: my ( $self, $file ) = @_;
517:
518: $file ||= $self->{file};
519: die "$file: no such file\n" unless -e $file;
520:
521: my $c = LoadFile($file) or die "Unable to load $file\n";
522:
1.6 andrew 523: $c->{customers} ||= {};
1.1 andrew 524: if ( $c->{default} ) {
1.6 andrew 525: foreach my $cust ( values %{ $c->{customers} } ) {
1.1 andrew 526: foreach my $k ( keys %{ $c->{default} } ) {
1.5 andrew 527: $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1 andrew 528: }
529: }
530: }
531:
532: $self->{_config} = $c;
533: $self->{file} = $file;
534: }
535:
536: sub get {
537: my ( $self, $key ) = @_;
1.6 andrew 538: my $value = Load( Dump( $self->{_config}->{$key} ) );
539: if ( !$value ) {
540: given ($key) {
541: when ('state') {
542: $value = dirname( $self->{file} ) . '/rt_invoice.state'
543: }
544: }
545: }
546: return $value;
1.1 andrew 547: }
548:
549: package RTI::State;
550: use strict;
551: use warnings;
552:
553: use 5.010;
554:
555: use YAML::Any qw/ LoadFile DumpFile /;
556:
1.6 andrew 557: my $file = '';
558:
1.1 andrew 559: sub new {
1.6 andrew 560: my $class;
561: ( $class, $file ) = @_;
562:
563: my $self = { lastinvoice => 0, };
564: if ( -e $file ) {
565: $self = LoadFile($file) or die "Unable to load state: $!";
566: }
1.1 andrew 567:
568: bless $self, $class;
1.6 andrew 569:
570: die "Need to pass filename to new: $!" unless $file;
1.1 andrew 571:
572: return $self;
1.6 andrew 573: }
574:
575: sub last_invoice {
576: my ( $self, $custid ) = @_;
577: state %table;
578: if ( !%table ) {
579: foreach my $date ( sort keys %{ $self->{invoice} } ) {
580: while ( my ( $id, $inv ) = each %{ $self->{invoice}->{$date} } ) {
581: next unless $inv->{custid};
582: $table{ $inv->{custid} } = {
583: id => $id,
584: date => $date,
585: %{$inv},
586: };
587: }
588: }
589: }
590: return $table{$custid} || {};
591: }
592:
593: sub txn_is_invoiced {
594: my ( $self, $txn ) = @_;
595: state %table;
596: if ( !%table ) {
597: foreach my $date ( sort keys %{ $self->{invoice} } ) {
598: foreach my $inv ( values %{ $self->{invoice}->{$date} } ) {
599: foreach my $t ( @{ $inv->{transactions} } ) {
600: $table{$t} = 1;
601: }
602: }
603: }
604: }
605: return $table{$txn};
606: }
607:
608: sub save {
609: my ($self) = @_;
610: DumpFile( $file, {%$self} ) or die "Unable to save state: $!";
1.1 andrew 611: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>