Annotation of RT/Invoicing/rt_invoices.pl, Revision 1.7
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:
151: #foreach my $r ($ticket->requestors) {
152: # $users->id( $r );
153: # $users->retrieve;
154: # print Dump $users;
155: #}
1.7 ! andrew 156:
! 157: my $project = make_project( $ticket, $cust );
1.6 andrew 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:
1.7 ! andrew 197: my %li = ( custid => $custid, );
! 198:
1.1 andrew 199: foreach my $project ( @{ $invoice->{projects} } ) {
200: print "$project->{title}\n";
1.6 andrew 201: if ( $project->{transactions} ) {
1.7 ! andrew 202: push @{ $li{transactions} }, @{ $project->{transactions} };
1.6 andrew 203: }
1.1 andrew 204: my $subtotal = 0;
205: foreach my $fee ( @{ $project->{fees} } ) {
206: my $amount = round( $fee->{count} * $fee->{rate} );
207: print " $amount (" . ( $fee->{count} * $fee->{rate} ) . ")\n";
208: $subtotal += $amount;
209: }
210: foreach my $expense ( @{ $project->{expenses} } ) {
211: $subtotal += round( $expense->{amount} );
212: }
213: $project->{total} = $subtotal;
214: $invoice->{total} += $subtotal;
215: print " Subtotal $subtotal\n";
216: }
217:
218: if ( $invoice->{discount} ) {
219: my $c = "Included Hours\n";
220: if ( $invoice->{discount}{hours} ) {
221: foreach my $t ( keys %{ $invoice->{discount}{hours} } ) {
222: $c .= "\n$invoice->{discount}{hours}{$t} $t hour";
223: $c .= 's' if $invoice->{discount}{hours}{$t} != 1;
224: $c .= "\n";
225: }
226: }
227: $invoice->{discount}{contents} = $c;
228: $invoice->{total} -= round( $invoice->{discount}{amount} );
229: }
230:
231: if ( $invoice->{past_due} ) {
232: $invoice->{total_due} = $invoice->{total} + $invoice->{past_due};
1.3 andrew 233: }
234:
1.6 andrew 235: # XXX Here we need to "make_address"
236: $invoice->{info} = $config->get('info');
237: $invoice->{from} = $config->get('from');
238: $invoice->{to} = $cust->{address};
239:
240: $state->{lastinvoice}++;
241: $invoice->{id} = $state->{lastinvoice};
242: $invoice->{file} = 'invoice_' . $state->{lastinvoice} . '.pdf';
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";
1.7 ! andrew 253: print Dump $cust;
1.6 andrew 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 {
1.7 ! andrew 315: my ( $ticket, $cust ) = @_;
1.6 andrew 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:
1.7 ! andrew 338: my $fee = make_fee( $txn, $cust->{rates}, $ticket );
! 339:
1.6 andrew 340: if ( !( $fee->{rate} && $fee->{count} ) ) {
341: warn "Invalid Fee, no rate or count";
342: next;
343: }
344:
1.7 ! andrew 345: my $invoice = $cust->{invoice};
! 346: next
! 347: if $invoice->{start}
! 348: && $invoice->{start} > $fee->{date};
1.6 andrew 349: next if $invoice->{end} < $fee->{date};
350:
351: push @{ $project{fees} }, $fee;
352: push @{ $project{transactions} }, $txn->id;
1.4 andrew 353: }
1.6 andrew 354:
355: return \%project;
1.4 andrew 356: }
357:
358: sub make_fee {
1.7 ! andrew 359: my ( $txn, $rates, $ticket ) = @_;
! 360:
! 361: # XXX Only need $ticket for the alternate subject
1.4 andrew 362:
363: my $work_time = sprintf "%.03f", $txn->time_taken / 60;
364: my $work_type = $txn->cf('WorkType');
365:
366: my %fee = (
367: id => $txn->id,
368: contents => $txn->created . ' ('
369: . $txn->id . ')' . "\n\n"
370: . ( $txn->data || $ticket->subject ),
371: count => $work_time,
372: type => $work_type,
1.6 andrew 373: date => ymd_to_DateTime( $txn->created ),
1.7 ! andrew 374: rate => $rates->{$work_type} || $rates->{default} || 0,
1.4 andrew 375: );
376:
377: if ( $work_type && $work_type ne 'Normal' ) {
378: $fee{detail} = $work_type . ' rate';
379: }
380:
381: return \%fee;
382: }
383:
384: sub hours_for_date {
385: my ( $invoice, $date ) = @_;
386:
387: my $hours = {};
388: if ( $invoice->{hours} ) {
389: foreach my $h ( @{ $invoice->{hours} } ) {
390: next if $h->{start} && $h->{start} > $date;
391: next if $h->{end} < $date;
392:
393: $hours = $h->{hours};
394: last;
395: }
396: }
397: return $hours;
1.1 andrew 398: }
399:
1.6 andrew 400: sub ymd_to_DateTime {
401: my ($ymd) = @_;
402: my ( $date, $time ) = split ' ', $ymd;
403: my ( $year, $month, $day ) = split '-', $date;
404: my ( $hour, $minute, $second ) = split ':', $time if $time;
405:
406: return DateTime->new(
407: year => $year,
408: month => $month,
409: day => $day,
410: hour => $hour || 0,
411: minute => $minute || 0,
412: second => $second || 0,
413: );
414: }
415:
1.1 andrew 416: package RTI::Config;
417: use strict;
418: use warnings;
419:
420: use 5.010;
421:
1.5 andrew 422: use YAML::Any qw/ LoadFile Dump Load /;
1.6 andrew 423: use File::Basename;
1.1 andrew 424:
425: sub new {
426: my ( $class, $args ) = @_;
427:
428: my $self = { file => '', };
429: bless $self, $class;
1.5 andrew 430:
1.1 andrew 431: my $file = $args->{file} || $self->_find_config;
432: $self->read_config($file);
433:
434: return $self;
435: }
436:
437: sub _find_config {
438: my ($self) = @_;
439:
440: # XXX This needs to be better
441: foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
1.6 andrew 442: foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoicing', $ENV{HOME} ) {
1.1 andrew 443: my $path = join '/', $dir, $file;
444: return $path if -e $path;
445: }
446: }
447: return;
448: }
449:
450: sub read_config {
451: my ( $self, $file ) = @_;
452:
453: $file ||= $self->{file};
454: die "$file: no such file\n" unless -e $file;
455:
456: my $c = LoadFile($file) or die "Unable to load $file\n";
457:
1.6 andrew 458: $c->{customers} ||= {};
1.1 andrew 459: if ( $c->{default} ) {
1.6 andrew 460: foreach my $cust ( values %{ $c->{customers} } ) {
1.1 andrew 461: foreach my $k ( keys %{ $c->{default} } ) {
1.5 andrew 462: $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1 andrew 463: }
464: }
465: }
466:
467: $self->{_config} = $c;
468: $self->{file} = $file;
469: }
470:
471: sub get {
472: my ( $self, $key ) = @_;
1.6 andrew 473: my $value = Load( Dump( $self->{_config}->{$key} ) );
474: if ( !$value ) {
475: given ($key) {
476: when ('state') {
477: $value = dirname( $self->{file} ) . '/rt_invoice.state'
478: }
479: }
480: }
481: return $value;
1.1 andrew 482: }
483:
484: package RTI::State;
485: use strict;
486: use warnings;
487:
488: use 5.010;
489:
490: use YAML::Any qw/ LoadFile DumpFile /;
491:
1.6 andrew 492: my $file = '';
493:
1.1 andrew 494: sub new {
1.6 andrew 495: my $class;
496: ( $class, $file ) = @_;
497:
498: my $self = { lastinvoice => 0, };
499: if ( -e $file ) {
500: $self = LoadFile($file) or die "Unable to load state: $!";
501: }
1.1 andrew 502:
503: bless $self, $class;
1.6 andrew 504:
505: die "Need to pass filename to new: $!" unless $file;
1.1 andrew 506:
507: return $self;
1.6 andrew 508: }
509:
510: sub last_invoice {
511: my ( $self, $custid ) = @_;
512: state %table;
513: if ( !%table ) {
514: foreach my $date ( sort keys %{ $self->{invoice} } ) {
515: while ( my ( $id, $inv ) = each %{ $self->{invoice}->{$date} } ) {
516: next unless $inv->{custid};
517: $table{ $inv->{custid} } = {
518: id => $id,
519: date => $date,
520: %{$inv},
521: };
522: }
523: }
524: }
525: return $table{$custid} || {};
526: }
527:
528: sub txn_is_invoiced {
529: my ( $self, $txn ) = @_;
530: state %table;
531: if ( !%table ) {
532: foreach my $date ( sort keys %{ $self->{invoice} } ) {
533: foreach my $inv ( values %{ $self->{invoice}->{$date} } ) {
534: foreach my $t ( @{ $inv->{transactions} } ) {
535: $table{$t} = 1;
536: }
537: }
538: }
539: }
540: return $table{$txn};
541: }
542:
543: sub save {
544: my ($self) = @_;
545: DumpFile( $file, {%$self} ) or die "Unable to save state: $!";
1.1 andrew 546: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>