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