[BACK]Return to rt_invoices.pl CVS log [TXT][DIR] Up to [local] / RT / Invoicing

Annotation of RT/Invoicing/rt_invoices.pl, Revision 1.4

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>