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