Annotation of RT/Invoicing/rt_invoices.pl, Revision 1.12
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 );
1.1 andrew 40:
1.6 andrew 41: $rt->login( username => $rt_conf->{user}, password => $rt_conf->{pass} );
42:
43: #print Dump $config, $state; exit;
1.1 andrew 44:
45: my $startdate;
1.3 andrew 46:
1.6 andrew 47: my $customers = $config->get('customers');
48: CUSTOMER: while ( my ( $custid, $cust ) = each %{$customers} ) {
49:
50: my %invoice = ( end => DateTime->now, );
1.1 andrew 51:
52: if ( $cust->{base_rate} ) {
1.3 andrew 53: my $day = $cust->{day} || 1;
1.1 andrew 54: my $freq = $cust->{frequency} || 1;
55:
1.7 andrew 56: my $per;
1.3 andrew 57: my $day_method;
1.1 andrew 58: given ( $cust->{per} ) {
1.3 andrew 59: when ('week') { $per = 'weeks'; $day_method = 'dow' }
60: when ('month') { $per = 'months'; $day_method = 'day' }
1.1 andrew 61: default { die "Unknown per [$cust->{per}]\n" }
62: }
63:
1.6 andrew 64: my $billends
1.3 andrew 65: = DateTime->now->set( hour => 0, minute => 0, second => 0 );
1.7 andrew 66: $billends->subtract( days => 1 ) while $billends->$day_method != $day;
1.3 andrew 67:
1.6 andrew 68: my $date = $billends->clone->subtract( $per => $freq );
69:
70: my $lastinvoice = $state->last_invoice($custid);
71: if ( $lastinvoice->{date} ) {
72: my $last_invoice_date = ymd_to_DateTime( $lastinvoice->{date} );
73: $date = $last_invoice_date->clone->add( days => 1 );
74: }
1.1 andrew 75:
1.7 andrew 76: next CUSTOMER if $billends <= $date;
77:
1.1 andrew 78: my $title
79: = $freq == 1
80: ? ucfirst( $cust->{per} . 'ly' )
81: : $freq . ' ' . ucfirst( $cust->{per} );
82: $title .= ' Retainer';
83:
84: my %project = ( title => $title, fees => [], );
85:
1.6 andrew 86: while ( $date < $billends ) {
1.3 andrew 87: my $start = $date->clone;
88:
89: $date->add( $per => $freq );
1.6 andrew 90: $date = $billends->clone if $date > $billends;
1.7 andrew 91:
92: # XXX This is helpful, but monthly and billday > 28 == !!!
93: $date->subtract( days => 1 ) while $date->$day_method != $day;
1.3 andrew 94:
1.6 andrew 95: my $end = $date->clone->subtract( seconds => 1 );
1.3 andrew 96:
1.7 andrew 97: next if $end < $start;
98:
1.4 andrew 99: $startdate = $start->clone if !$startdate || $startdate > $start;
1.3 andrew 100: $invoice{start} ||= $start->clone;
101: $invoice{end} = $end->clone;
1.1 andrew 102: my %hours = (
1.3 andrew 103: start => $start->clone,
104: end => $end->clone,
1.1 andrew 105: hours => { %{ $cust->{hours} } },
106: );
107:
1.3 andrew 108: push @{ $invoice{hours} }, \%hours;
109: push @{ $project{fees} },
1.1 andrew 110: {
111: count => 1,
112: rate => $cust->{base_rate},
1.3 andrew 113: contents => $start->ymd . ' to ' . $end->ymd,
1.1 andrew 114: };
115:
116: }
117:
1.3 andrew 118: if ( @{ $project{fees} } ) {
1.2 andrew 119: push @{ $invoice{projects} }, \%project;
120: }
1.1 andrew 121: }
122:
1.12 ! andrew 123: $cust->{address} ||= get_user($custid);
1.6 andrew 124: $cust->{invoice} = \%invoice;
1.1 andrew 125: }
126:
127: my @limits = map +{
128: attribute => 'status',
129: operator => '=',
130: value => $_,
131: aggregator => 'or',
132: },
133:
134: # XXX This should be a config option
135: qw/ open stalled resolved /;
136:
137: if ($startdate) {
138: push @limits,
139: {
140: attribute => 'last_updated',
141: operator => '>=',
142: value => $startdate->ymd,
143: };
144: }
145:
146: my $results = $tickets->search(
147: limits => \@limits,
148: orderby => 'id',
149: );
150:
151: my $count = $results->count;
152: print "There are $count results that matched your query\n";
153:
154: my $iterator = $results->get_iterator;
155: while ( my $ticket = &$iterator ) {
1.6 andrew 156: my $cust = find_customer_for_ticket( $customers, $ticket );
157: if ( !$cust ) {
1.10 andrew 158: warn "No customer found for ticket " . $ticket->id;
1.7 andrew 159: next;
160: }
161: if ( !$cust->{invoice} ) {
1.12 ! andrew 162:
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.12 ! andrew 207: my %li = ( custid => $custid, invdate => DateTime->now->ymd, );
1.7 andrew 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');
1.12 ! andrew 246: $invoice->{from} = make_address( $config->get('from') );
! 247: $invoice->{to} = make_address( $cust->{address} );
1.6 andrew 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:
1.12 ! andrew 259: if ( defined $v && length $v ) {
1.10 andrew 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.12 ! andrew 328: $cust->{address} = 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:
1.12 ! andrew 360: my $users = RT::Client::REST::User->new( rt => $rt, id => $id );
1.8 andrew 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.12 ! andrew 377: }
! 378:
! 379: sub make_address {
! 380: my ($addr) = @_;
! 381: my @adr;
! 382:
! 383: if ( $addr->{organization} ) {
! 384: push @adr, $addr->{organization};
! 385: }
! 386: elsif ( $addr->{name} && !$addr->{attn} ) {
! 387: push @adr, $addr->{name};
! 388: }
! 389:
! 390: if ( ( $addr->{addr1} || $addr->{addr2} )
! 391: && $addr->{city}
! 392: && $addr->{state}
! 393: && $addr->{zip} )
! 394: {
! 395: push @adr, $addr->{attn} if $addr->{attn};
! 396: push @adr, $addr->{addr1} if $addr->{addr1};
! 397: push @adr, $addr->{addr2} if $addr->{addr2};
! 398: push @adr,
! 399: $addr->{city} . ', ' . $addr->{state} . ' ' . $addr->{zip};
! 400: }
! 401: else {
! 402: push @adr, $addr->{email} if $addr->{email};
! 403: }
! 404:
! 405: return join "\n\n", @adr;
1.6 andrew 406: }
407:
408: sub make_project {
1.7 andrew 409: my ( $ticket, $cust ) = @_;
1.6 andrew 410:
411: my %project = (
412: id => $ticket->id,
413: queue => $ticket->queue,
414: owner => $ticket->owner,
415: title => $ticket->subject,
416: detail => 'Ticket: '
417: . $ticket->id
418: . ' Queue: '
419: . $ticket->queue
420: . ' Requestors: '
421: . join( ', ', $ticket->requestors ),
422: fees => [],
423: expenses => [],
424: );
425:
426: my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
427: my $txn_i = $txns->get_iterator;
428: while ( my $txn = $txn_i->() ) {
429: next unless $txn->time_taken;
430: next if $state->txn_is_invoiced( $txn->id );
431:
1.7 andrew 432: my $fee = make_fee( $txn, $cust->{rates}, $ticket );
433:
1.6 andrew 434: if ( !( $fee->{rate} && $fee->{count} ) ) {
435: warn "Invalid Fee, no rate or count";
436: next;
437: }
438:
1.7 andrew 439: my $invoice = $cust->{invoice};
440: next
441: if $invoice->{start}
442: && $invoice->{start} > $fee->{date};
1.6 andrew 443: next if $invoice->{end} < $fee->{date};
444:
445: push @{ $project{fees} }, $fee;
446: push @{ $project{transactions} }, $txn->id;
1.4 andrew 447: }
1.6 andrew 448:
449: return \%project;
1.4 andrew 450: }
451:
452: sub make_fee {
1.7 andrew 453: my ( $txn, $rates, $ticket ) = @_;
454:
455: # XXX Only need $ticket for the alternate subject
1.4 andrew 456:
457: my $work_time = sprintf "%.03f", $txn->time_taken / 60;
458: my $work_type = $txn->cf('WorkType');
459:
460: my %fee = (
461: id => $txn->id,
462: contents => $txn->created . ' ('
463: . $txn->id . ')' . "\n\n"
464: . ( $txn->data || $ticket->subject ),
465: count => $work_time,
466: type => $work_type,
1.6 andrew 467: date => ymd_to_DateTime( $txn->created ),
1.7 andrew 468: rate => $rates->{$work_type} || $rates->{default} || 0,
1.4 andrew 469: );
470:
471: if ( $work_type && $work_type ne 'Normal' ) {
472: $fee{detail} = $work_type . ' rate';
473: }
474:
475: return \%fee;
476: }
477:
478: sub hours_for_date {
479: my ( $invoice, $date ) = @_;
480:
481: my $hours = {};
482: if ( $invoice->{hours} ) {
483: foreach my $h ( @{ $invoice->{hours} } ) {
484: next if $h->{start} && $h->{start} > $date;
485: next if $h->{end} < $date;
486:
487: $hours = $h->{hours};
488: last;
489: }
490: }
491: return $hours;
1.1 andrew 492: }
493:
1.6 andrew 494: sub ymd_to_DateTime {
495: my ($ymd) = @_;
1.10 andrew 496: my ( $date, $time ) = split /[\sT]/, $ymd;
1.6 andrew 497: my ( $year, $month, $day ) = split '-', $date;
498: my ( $hour, $minute, $second ) = split ':', $time if $time;
499:
500: return DateTime->new(
501: year => $year,
502: month => $month,
503: day => $day,
504: hour => $hour || 0,
505: minute => $minute || 0,
506: second => $second || 0,
507: );
508: }
509:
1.1 andrew 510: package RTI::Config;
511: use strict;
512: use warnings;
513:
514: use 5.010;
515:
1.5 andrew 516: use YAML::Any qw/ LoadFile Dump Load /;
1.6 andrew 517: use File::Basename;
1.1 andrew 518:
519: sub new {
520: my ( $class, $args ) = @_;
521:
522: my $self = { file => '', };
523: bless $self, $class;
1.5 andrew 524:
1.1 andrew 525: my $file = $args->{file} || $self->_find_config;
526: $self->read_config($file);
527:
528: return $self;
529: }
530:
531: sub _find_config {
532: my ($self) = @_;
533:
534: # XXX This needs to be better
535: foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
1.6 andrew 536: foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoicing', $ENV{HOME} ) {
1.1 andrew 537: my $path = join '/', $dir, $file;
538: return $path if -e $path;
539: }
540: }
541: return;
542: }
543:
544: sub read_config {
545: my ( $self, $file ) = @_;
546:
547: $file ||= $self->{file};
548: die "$file: no such file\n" unless -e $file;
549:
550: my $c = LoadFile($file) or die "Unable to load $file\n";
551:
1.6 andrew 552: $c->{customers} ||= {};
1.1 andrew 553: if ( $c->{default} ) {
1.6 andrew 554: foreach my $cust ( values %{ $c->{customers} } ) {
1.1 andrew 555: foreach my $k ( keys %{ $c->{default} } ) {
1.5 andrew 556: $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1 andrew 557: }
558: }
559: }
560:
561: $self->{_config} = $c;
562: $self->{file} = $file;
563: }
564:
565: sub get {
566: my ( $self, $key ) = @_;
1.6 andrew 567: my $value = Load( Dump( $self->{_config}->{$key} ) );
568: if ( !$value ) {
569: given ($key) {
570: when ('state') {
571: $value = dirname( $self->{file} ) . '/rt_invoice.state'
572: }
573: }
574: }
575: return $value;
1.1 andrew 576: }
577:
578: package RTI::State;
579: use strict;
580: use warnings;
581:
582: use 5.010;
583:
584: use YAML::Any qw/ LoadFile DumpFile /;
585:
1.6 andrew 586: my $file = '';
587:
1.1 andrew 588: sub new {
1.6 andrew 589: my $class;
590: ( $class, $file ) = @_;
591:
592: my $self = { lastinvoice => 0, };
593: if ( -e $file ) {
594: $self = LoadFile($file) or die "Unable to load state: $!";
595: }
1.1 andrew 596:
597: bless $self, $class;
1.6 andrew 598:
599: die "Need to pass filename to new: $!" unless $file;
1.1 andrew 600:
601: return $self;
1.6 andrew 602: }
603:
604: sub last_invoice {
605: my ( $self, $custid ) = @_;
606: state %table;
607: if ( !%table ) {
608: foreach my $date ( sort keys %{ $self->{invoice} } ) {
609: while ( my ( $id, $inv ) = each %{ $self->{invoice}->{$date} } ) {
610: next unless $inv->{custid};
611: $table{ $inv->{custid} } = {
612: id => $id,
613: date => $date,
614: %{$inv},
615: };
616: }
617: }
618: }
619: return $table{$custid} || {};
620: }
621:
622: sub txn_is_invoiced {
623: my ( $self, $txn ) = @_;
624: state %table;
625: if ( !%table ) {
626: foreach my $date ( sort keys %{ $self->{invoice} } ) {
627: foreach my $inv ( values %{ $self->{invoice}->{$date} } ) {
628: foreach my $t ( @{ $inv->{transactions} } ) {
629: $table{$t} = 1;
630: }
631: }
632: }
633: }
634: return $table{$txn};
635: }
636:
637: sub save {
638: my ($self) = @_;
639: DumpFile( $file, {%$self} ) or die "Unable to save state: $!";
1.1 andrew 640: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>