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