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

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

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:
1.5     ! andrew    386: use YAML::Any qw/ LoadFile Dump Load /;
1.1       andrew    387:
                    388: sub new {
                    389:     my ( $class, $args ) = @_;
                    390:
                    391:     my $self = { file => '', };
                    392:     bless $self, $class;
1.5     ! andrew    393:
1.1       andrew    394:     my $file = $args->{file} || $self->_find_config;
                    395:     $self->read_config($file);
                    396:
                    397:     return $self;
                    398: }
                    399:
                    400: sub _find_config {
                    401:     my ($self) = @_;
                    402:
                    403:     # XXX This needs to be better
                    404:     foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
                    405:         foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoice', $ENV{HOME} ) {
                    406:             my $path = join '/', $dir, $file;
                    407:             return $path if -e $path;
                    408:         }
                    409:     }
                    410:     return;
                    411: }
                    412:
                    413: sub read_config {
                    414:     my ( $self, $file ) = @_;
                    415:
                    416:     $file ||= $self->{file};
                    417:     die "$file: no such file\n" unless -e $file;
                    418:
                    419:     my $c = LoadFile($file) or die "Unable to load $file\n";
                    420:
                    421:     $c->{customers} ||= [];
                    422:     if ( $c->{default} ) {
                    423:         foreach my $cust ( @{ $c->{customers} } ) {
                    424:             foreach my $k ( keys %{ $c->{default} } ) {
1.5     ! andrew    425:                 $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1       andrew    426:             }
                    427:         }
                    428:     }
                    429:
                    430:     $self->{_config} = $c;
                    431:     $self->{file}    = $file;
                    432: }
                    433:
                    434: sub get {
                    435:     my ( $self, $key ) = @_;
1.5     ! andrew    436:     return Load( Dump( $self->{_config}->{$key} ) );
1.1       andrew    437: }
                    438:
                    439: package RTI::State;
                    440: use strict;
                    441: use warnings;
                    442:
                    443: use 5.010;
                    444:
                    445: use YAML::Any qw/ LoadFile DumpFile /;
                    446:
                    447: sub new {
                    448:     my ( $class, $args ) = @_;
                    449:
                    450:     my $self = { file => '', };
                    451:     bless $self, $class;
                    452:     my $file = $args->{file} || $self->_find_config;
                    453:     $self->read_config($file);
                    454:
                    455:     return $self;
                    456: }

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