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

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

1.1       andrew      1: #!/usr/bin/perl
1.39    ! andrew      2: # $AFresh1: rt_invoices.pl,v 1.38 2011/06/21 00:20:28 andrew Exp $
1.11      andrew      3: ########################################################################
                      4: # Copyright (c) 2011 Andrew Fresh <andrew@afresh1.com>
                      5: #
                      6: # Permission to use, copy, modify, and distribute this software for any
                      7: # purpose with or without fee is hereby granted, provided that the above
                      8: # copyright notice and this permission notice appear in all copies.
                      9: #
                     10: # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     11: # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12: # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     13: # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14: # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     15: # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     16: # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     17: ########################################################################
1.1       andrew     18: use strict;
                     19: use warnings;
                     20:
                     21: use 5.010;
                     22:
                     23: use Template;
                     24: use RT::Client::REST;
                     25: use RT::Client::REST::Ticket;
                     26: use RT::Client::REST::User;
                     27:
1.18      andrew     28: use File::Path;
1.1       andrew     29: use DateTime;
                     30:
                     31: my $config = RTI::Config->new();
1.6       andrew     32: my $state  = RTI::State->new( $config->get('state') );
1.1       andrew     33:
1.6       andrew     34: my $rt_conf = $config->get('rt');
                     35: my $rt      = RT::Client::REST->new(
                     36:     server  => $rt_conf->{server},
                     37:     timeout => $rt_conf->{timeout},
                     38: );
                     39: my $tickets = RT::Client::REST::Ticket->new( rt => $rt );
1.1       andrew     40:
1.6       andrew     41: $rt->login( username => $rt_conf->{user}, password => $rt_conf->{pass} );
                     42:
1.22      andrew     43: #use YAML;
1.6       andrew     44: #print Dump $config, $state; exit;
1.1       andrew     45:
                     46: my $startdate;
1.3       andrew     47:
1.6       andrew     48: my $customers = $config->get('customers');
1.1       andrew     49:
                     50: my @limits = map +{
                     51:     attribute  => 'status',
                     52:     operator   => '=',
                     53:     value      => $_,
                     54:     aggregator => 'or',
                     55:     },
                     56:
                     57:     # XXX This should be a config option
                     58:     qw/ open stalled resolved /;
                     59:
                     60: if ($startdate) {
                     61:     push @limits,
                     62:         {
                     63:         attribute => 'last_updated',
                     64:         operator  => '>=',
                     65:         value     => $startdate->ymd,
                     66:         };
                     67: }
                     68:
                     69: my $results = $tickets->search(
                     70:     limits  => \@limits,
                     71:     orderby => 'id',
                     72: );
                     73:
                     74: my $count = $results->count;
                     75: print "There are $count results that matched your query\n";
                     76:
                     77: my $iterator = $results->get_iterator;
                     78: while ( my $ticket = &$iterator ) {
1.29      andrew     79:     my $cust = find_customer_for_ticket($ticket);
1.6       andrew     80:     if ( !$cust ) {
1.10      andrew     81:         warn "No customer found for ticket " . $ticket->id;
1.7       andrew     82:         next;
                     83:     }
1.25      andrew     84:
                     85:     say 'Ticket ' . $ticket->id . " belongs to $cust->{id}";
                     86:
                     87:     $cust->{invoice} ||= make_invoice($cust);
                     88:     if ( !$cust->{invoice}->{end} ) {
                     89:         say "  $cust->{id} has no open invoices [" . $ticket->id . ']';
1.4       andrew     90:         next;
                     91:     }
1.1       andrew     92:
1.7       andrew     93:     my $project = make_project( $ticket, $cust );
1.6       andrew     94:     next unless @{ $project->{fees} } || @{ $project->{expenses} };
1.1       andrew     95:
1.6       andrew     96:     foreach my $fee ( @{ $project->{fees} } ) {
1.25      andrew     97:         my $hours = hours_for_date( $cust->{invoice}, $fee->{date} );
1.1       andrew     98:
1.38      andrew     99:         my $type  = 'unknown';
                    100:         my $count = $fee->{count};
                    101:         while ( $type && $count > 0 && $type ne 'default' ) {
1.35      andrew    102:             $type = exists $hours->{ $fee->{type} }
                    103:                 && $hours->{ $fee->{type} } > 0 ? $fee->{type} : 'default';
                    104:
                    105:             next unless exists $hours->{$type} && $hours->{$type} > 0;
                    106:
                    107:             my $discount_time = 0;
1.38      andrew    108:             if ( $hours->{$type} > $count ) {
                    109:                 $hours->{$type} -= $count;
                    110:                 $discount_time = $count;
1.35      andrew    111:             }
                    112:             else {
                    113:                 $discount_time = $hours->{$type};
                    114:                 $hours->{$type} = 0;
                    115:             }
                    116:
                    117:             if ($discount_time) {
                    118:                 $cust->{invoice}->{discount}->{amount}
                    119:                     += round( $discount_time * $fee->{rate} );
1.36      andrew    120:                 $cust->{invoice}->{discount}->{hours}{$type}
                    121:                     += $discount_time;
1.35      andrew    122:
                    123:                 $type = '' if $type eq 'default';
1.38      andrew    124:                 $count -= $discount_time;
1.35      andrew    125:                 $fee->{detail} .= " $discount_time $type Hours Discounted";
                    126:             }
1.1       andrew    127:         }
                    128:     }
                    129:
1.25      andrew    130:     push @{ $cust->{invoice}->{projects} }, $project;
1.1       andrew    131: }
                    132:
1.25      andrew    133: foreach my $cust ( @{$customers} ) {
1.6       andrew    134:     my $invoice = $cust->{invoice};
1.25      andrew    135:     next unless $invoice && $invoice->{projects} && @{ $invoice->{projects} };
1.1       andrew    136:
1.29      andrew    137:     my %li = (
1.36      andrew    138:         custid       => $cust->{id},
                    139:         invdate      => DateTime->now( time_zone => 'local' )->ymd,
1.33      andrew    140:         transactions => [],
1.29      andrew    141:     );
1.7       andrew    142:
1.33      andrew    143:     my %transactions;
1.1       andrew    144:     foreach my $project ( @{ $invoice->{projects} } ) {
1.6       andrew    145:         if ( $project->{transactions} ) {
1.33      andrew    146:             %transactions = ( %transactions, %{ $project->{transactions} } );
1.6       andrew    147:         }
1.1       andrew    148:         my $subtotal = 0;
                    149:         foreach my $fee ( @{ $project->{fees} } ) {
                    150:             my $amount = round( $fee->{count} * $fee->{rate} );
                    151:             $subtotal += $amount;
                    152:         }
                    153:         foreach my $expense ( @{ $project->{expenses} } ) {
                    154:             $subtotal += round( $expense->{amount} );
                    155:         }
                    156:         $project->{total} = $subtotal;
                    157:         $invoice->{total} += $subtotal;
                    158:     }
1.33      andrew    159:     @{ $li{transactions} } = sort { $a <=> $b } keys %transactions;
1.1       andrew    160:
                    161:     if ( $invoice->{discount} ) {
                    162:         my $c = "Included Hours\n";
                    163:         if ( $invoice->{discount}{hours} ) {
                    164:             foreach my $t ( keys %{ $invoice->{discount}{hours} } ) {
1.35      andrew    165:                 my $type = $t eq 'default' ? '' : $t;
                    166:                 $c .= "\n$invoice->{discount}{hours}{$t} $type hour";
1.1       andrew    167:                 $c .= 's' if $invoice->{discount}{hours}{$t} != 1;
                    168:                 $c .= "\n";
                    169:             }
                    170:         }
                    171:         $invoice->{discount}{contents} = $c;
                    172:         $invoice->{total} -= round( $invoice->{discount}{amount} );
                    173:     }
                    174:
                    175:     if ( $invoice->{past_due} ) {
                    176:         $invoice->{total_due} = $invoice->{total} + $invoice->{past_due};
1.3       andrew    177:     }
                    178:
1.9       andrew    179:     next unless $invoice->{total} > 0 || $invoice->{total_due};
                    180:
1.6       andrew    181:     $invoice->{info} = $config->get('info');
1.19      andrew    182:     my $from = $config->get('from');
                    183:     $from = get_user($from) if !ref $from;
                    184:
                    185:     $invoice->{organization} = $from->{organization} || $from->{name};
1.29      andrew    186:     $invoice->{from} = make_address($from);
                    187:     $invoice->{to} = make_address( $cust->{address} || $cust->{id} );
1.6       andrew    188:
                    189:     $state->{lastinvoice}++;
1.29      andrew    190:     $invoice->{id}   = $state->{lastinvoice};
1.17      andrew    191:     $invoice->{file} = sprintf 'invoice_%06d.pdf', $state->{lastinvoice};
1.22      andrew    192:     $invoice->{logo} = $config->get('logo');
1.6       andrew    193:
1.10      andrew    194:     foreach my $k (qw/ file transactions start end total past_due total_due /)
                    195:     {
                    196:         my $v;
                    197:         if    ( $invoice->{$k} ) { $v = $invoice->{$k} }
                    198:         elsif ( $cust->{$k} )    { $v = $cust->{$k} }
                    199:
1.12      andrew    200:         if ( defined $v && length $v ) {
1.10      andrew    201:             if ( ref $v eq 'DateTime' ) {
                    202:                 $li{$k} = $v->ymd;
                    203:             }
                    204:             else {
                    205:                 $li{$k} = $v;
                    206:             }
                    207:         }
                    208:     }
1.39    ! andrew    209:     $state->{invoice}->{ $invoice->{id} } = \%li;
1.10      andrew    210:
1.3       andrew    211:     foreach my $key (qw/ start end /) {
                    212:         if ( exists $invoice->{$key} ) {
                    213:             $invoice->{$key} = $invoice->{$key}->strftime('%B %d, %Y');
                    214:         }
1.1       andrew    215:     }
1.18      andrew    216:
                    217:     my $invoice_dir = $config->get('invoice_dir');
                    218:     File::Path::make_path($invoice_dir);
                    219:     my $file = join '/', $invoice_dir, $invoice->{file};
                    220:
1.21      andrew    221:     my $tt = Template->new( INCLUDE_PATH => $config->get('template_dir'), )
                    222:         || die $Template::ERROR, "\n";
1.20      andrew    223:
                    224:     $tt->process( $config->get('invoice_template'), $invoice, $file )
1.1       andrew    225:         or die $tt->error . "\n";
                    226:
1.25      andrew    227:     printf "Generated %s for %s: \$%.02f\n", $invoice->{file}, $cust->{id},
1.9       andrew    228:         $invoice->{total};
1.1       andrew    229: }
                    230:
1.6       andrew    231: $state->save;
1.1       andrew    232:
                    233: sub round {
                    234:     my ($amount) = @_;
                    235:
                    236:     #$amount =~ s/\.\d\d\K.*$//;
                    237:     #return $amount;
                    238:     return sprintf "%.02f", $amount;
1.4       andrew    239: }
                    240:
1.6       andrew    241: sub find_customer_for_ticket {
1.25      andrew    242:     my ($ticket) = @_;
1.4       andrew    243:
1.25      andrew    244:     foreach my $cust ( @{$customers} ) {
1.22      andrew    245:         next unless $cust->{match};
1.6       andrew    246:         foreach my $m ( @{ $cust->{match} } ) {
1.4       andrew    247:             my $type = $m->{type};
1.29      andrew    248:             my $match
                    249:                 = exists $m->{$type}
                    250:                 ? lc( $m->{$type} )
                    251:                 : qr/\Q$m->{regex}\E/;
                    252:             my $thing = [ map {lc} $ticket->$type ];
1.4       andrew    253:
1.29      andrew    254:             if ( !$match ) {
1.4       andrew    255:                 warn "Invalid match!";
1.22      andrew    256:                 next;
1.4       andrew    257:             }
1.29      andrew    258:             return $cust if ( $match ~~ $thing );
1.4       andrew    259:         }
1.6       andrew    260:     }
                    261:
1.25      andrew    262:     # Fake customer if we didn't find one
1.16      andrew    263:     my $cust = $config->get('default') || {};
1.8       andrew    264:
1.16      andrew    265:     ( $cust->{id} ) = $ticket->requestors;
                    266:     return unless $cust->{id};
1.25      andrew    267:     push @{$customers}, $cust;
1.8       andrew    268:
1.14      andrew    269:     $cust->{match} = [
                    270:         {   type  => 'requestors',
1.16      andrew    271:             regex => $cust->{id},
1.14      andrew    272:         }
                    273:     ];
1.13      andrew    274:
1.8       andrew    275:     return $cust;
                    276: }
                    277:
1.9       andrew    278: sub get_user {
1.8       andrew    279:     my ($id) = @_;
                    280:
1.9       andrew    281:     state %users;
                    282:     return $users{$id} if $users{$id};
1.8       andrew    283:
                    284:     my %map = (
                    285:         address_one   => 'addr1',
                    286:         address_two   => 'addr2',
                    287:         email_address => 'email',
1.9       andrew    288:         real_name     => 'name',
                    289:         name          => 'username',
1.8       andrew    290:     );
                    291:
1.12      andrew    292:     my $users = RT::Client::REST::User->new( rt => $rt, id => $id );
1.8       andrew    293:     $users->retrieve;
                    294:
1.9       andrew    295:     my %user;
1.8       andrew    296:     foreach my $m ( keys %{ $users->_attributes } ) {
                    297:         next unless $users->can($m);
                    298:
                    299:         my $v = $users->$m;
                    300:         next unless $v;
                    301:
                    302:         $m = $map{$m} if exists $map{$m};
                    303:
1.9       andrew    304:         $user{$m} = $v;
1.8       andrew    305:     }
1.6       andrew    306:
1.9       andrew    307:     $users{$id} = \%user;
                    308:     return \%user;
1.13      andrew    309: }
                    310:
                    311: sub make_invoice {
1.14      andrew    312:     my ($cust) = @_;
                    313:
1.21      andrew    314:     my $day  = $cust->{day}       ||= 0;
1.16      andrew    315:     my $per  = $cust->{per}       ||= 'week';
                    316:     my $freq = $cust->{frequency} ||= 1;
1.14      andrew    317:
1.16      andrew    318:     my $day_method;
                    319:     given ($per) {
                    320:         when ('week')  { $per = 'weeks';  $day_method = 'dow' }
                    321:         when ('month') { $per = 'months'; $day_method = 'day' }
                    322:         default { die "Unknown per [$per]\n" }
                    323:     }
1.13      andrew    324:
1.28      andrew    325:     my $billend = DateTime->now( time_zone => 'local' )
                    326:         ->set( hour => 0, minute => 0, second => 0 );
1.16      andrew    327:
                    328:     # XXX This is helpful, but monthly and billday > 28 == !!!
1.28      andrew    329:     $billend->subtract( days => 1 )
                    330:         while $day && $billend->$day_method != $day;
1.16      andrew    331:
1.29      andrew    332:     my $date = $billend->clone->subtract( $per => $freq );
1.28      andrew    333:     my %invoice = ( end => $billend->clone->subtract( seconds => 1 ) );
1.16      andrew    334:
                    335:     my $lastinvoice = $state->last_invoice( $cust->{id} );
                    336:     if ( $lastinvoice->{date} ) {
                    337:         my $last_invoice_date = ymd_to_DateTime( $lastinvoice->{date} );
                    338:         $date = $last_invoice_date->clone->add( days => 1 );
                    339:
                    340:         $invoice{start} = $date->clone;
                    341:
                    342:         $startdate = $date->clone->subtract( $per => $freq )
                    343:             if !$startdate || $startdate > $date;
                    344:     }
                    345:
1.23      andrew    346:     # Is the start date more than $freq $per before the end date?
1.30      andrew    347:     return {}
                    348:         if DateTime->compare( $date->clone->add( $per => $freq ), $billend )
                    349:             > 0;
1.16      andrew    350:
                    351:     if ( $cust->{base_rate} ) {
                    352:         my ( $project, $hours ) = make_base_project(
                    353:             $cust,
1.29      andrew    354:             {   date    => $date,
                    355:                 billend => $billend,
                    356:                 per     => $per,
                    357:                 freq    => $freq,
1.16      andrew    358:             }
                    359:         );
                    360:
                    361:         if ( @{ $project->{fees} } ) {
                    362:             $invoice{end}   = $project->{end};
                    363:             $invoice{hours} = $hours;
                    364:             push @{ $invoice{projects} }, $project;
                    365:         }
                    366:     }
                    367:     elsif ( $cust->{hours} ) {
1.14      andrew    368:         $invoice{hours} = [
1.16      andrew    369:             {   end   => $invoice{end}->clone,
1.14      andrew    370:                 hours => $cust->{hours},
                    371:             }
                    372:         ];
                    373:     }
1.13      andrew    374:
1.25      andrew    375:     return {} if $invoice{start} && $invoice{end} < $invoice{start};
1.16      andrew    376:
1.13      andrew    377:     return \%invoice;
1.12      andrew    378: }
                    379:
1.16      andrew    380: sub make_base_project {
                    381:     my ( $cust, $args ) = @_;
                    382:
1.28      andrew    383:     my $date    = $args->{date};
                    384:     my $billend = $args->{billend};
                    385:     my $per     = $args->{per};
                    386:     my $freq    = $args->{freq};
1.16      andrew    387:
                    388:     my $title
                    389:         = $freq == 1
                    390:         ? ucfirst( $cust->{per} . 'ly' )
                    391:         : $freq . ' ' . ucfirst( $cust->{per} );
                    392:     $title .= ' Retainer';
                    393:
                    394:     my %project = ( title => $title, start => $date->clone, fees => [], );
                    395:     my @hours;
                    396:
1.28      andrew    397:     while ( $date < $billend ) {
1.16      andrew    398:         my $start = $date->clone;
                    399:
                    400:         $date->add( $per => $freq );
                    401:
                    402:         my $end = $date->clone->subtract( seconds => 1 );
1.28      andrew    403:         $end = $billend->clone->subtract( seconds => 1 ) if $date > $billend;
1.16      andrew    404:
                    405:         $project{end} = $end->clone;
                    406:
                    407:         push @{ $project{fees} },
                    408:             {
                    409:             count    => 1,
                    410:             rate     => $cust->{base_rate},
                    411:             contents => $start->ymd . ' to ' . $end->ymd,
                    412:             };
                    413:
                    414:         push @hours,
                    415:             {
                    416:             start => $start->clone,
                    417:             end   => $end->clone,
                    418:             hours => { %{ $cust->{hours} } },
                    419:             };
                    420:     }
                    421:
                    422:     return \%project, \@hours;
                    423: }
                    424:
1.12      andrew    425: sub make_address {
                    426:     my ($addr) = @_;
                    427:     my @adr;
1.16      andrew    428:
                    429:     $addr = get_user($addr) unless ref $addr;
1.12      andrew    430:
                    431:     if ( $addr->{organization} ) {
                    432:         push @adr, $addr->{organization};
                    433:     }
                    434:     elsif ( $addr->{name} && !$addr->{attn} ) {
                    435:         push @adr, $addr->{name};
                    436:     }
                    437:
                    438:     if (   ( $addr->{addr1} || $addr->{addr2} )
                    439:         && $addr->{city}
                    440:         && $addr->{state}
                    441:         && $addr->{zip} )
                    442:     {
                    443:         push @adr, $addr->{attn}  if $addr->{attn};
                    444:         push @adr, $addr->{addr1} if $addr->{addr1};
                    445:         push @adr, $addr->{addr2} if $addr->{addr2};
                    446:         push @adr,
                    447:             $addr->{city} . ', ' . $addr->{state} . '  ' . $addr->{zip};
                    448:     }
                    449:     else {
                    450:         push @adr, $addr->{email} if $addr->{email};
                    451:     }
                    452:
                    453:     return join "\n\n", @adr;
1.6       andrew    454: }
                    455:
                    456: sub make_project {
1.7       andrew    457:     my ( $ticket, $cust ) = @_;
1.6       andrew    458:
                    459:     my %project = (
                    460:         id     => $ticket->id,
                    461:         queue  => $ticket->queue,
                    462:         owner  => $ticket->owner,
                    463:         title  => $ticket->subject,
                    464:         detail => 'Ticket: '
                    465:             . $ticket->id
1.17      andrew    466:             . ' Status: '
                    467:             . $ticket->status
1.6       andrew    468:             . ' Requestors: '
                    469:             . join( ', ', $ticket->requestors ),
                    470:         fees     => [],
                    471:         expenses => [],
                    472:     );
                    473:
                    474:     my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
                    475:     my $txn_i = $txns->get_iterator;
                    476:     while ( my $txn = $txn_i->() ) {
1.33      andrew    477:         next if $state->txn_is_invoiced( $txn->id );
                    478:
1.36      andrew    479:         if ( my $expense = make_expense( $txn, $ticket ) ) {
1.33      andrew    480:             push @{ $project{expenses} }, $expense;
                    481:             $project{transactions}{ $txn->id } = 1;
                    482:         }
                    483:
1.6       andrew    484:         next unless $txn->time_taken;
                    485:
1.7       andrew    486:         my $fee = make_fee( $txn, $cust->{rates}, $ticket );
                    487:
1.6       andrew    488:         if ( !( $fee->{rate} && $fee->{count} ) ) {
                    489:             warn "Invalid Fee, no rate or count";
                    490:             next;
                    491:         }
                    492:
1.7       andrew    493:         my $invoice = $cust->{invoice};
1.29      andrew    494:         if ( $invoice->{start} && $invoice->{start} > $fee->{date} ) {
                    495:             warn "Ticket "
                    496:                 . $ticket->id
                    497:                 . " has uninvoiced Transaction "
                    498:                 . $txn->id . "\n";
1.27      andrew    499:             next;
                    500:         }
1.6       andrew    501:         next if $invoice->{end} < $fee->{date};
                    502:
1.36      andrew    503:         push @{ $project{fees} }, $fee;
1.33      andrew    504:         $project{transactions}{ $txn->id } = 1;
1.4       andrew    505:     }
1.6       andrew    506:
                    507:     return \%project;
1.4       andrew    508: }
                    509:
                    510: sub make_fee {
1.7       andrew    511:     my ( $txn, $rates, $ticket ) = @_;
                    512:
                    513:     # XXX Only need $ticket for the alternate subject
1.4       andrew    514:
                    515:     my $work_time = sprintf "%.03f", $txn->time_taken / 60;
                    516:     my $work_type = $txn->cf('WorkType');
1.34      andrew    517:
                    518:     if ( $work_type =~ s/\s*Onsite//i ) {
1.36      andrew    519:
1.34      andrew    520:         # XXX Do something special for onsite activities
                    521:     }
                    522:
                    523:     $work_type =~ s/^\s+|\s+$//g;
                    524:     $work_type ||= 'Normal';
1.4       andrew    525:
                    526:     my %fee = (
                    527:         id       => $txn->id,
                    528:         contents => $txn->created . ' ('
                    529:             . $txn->id . ')' . "\n\n"
                    530:             . ( $txn->data || $ticket->subject ),
                    531:         count => $work_time,
                    532:         type  => $work_type,
1.6       andrew    533:         date  => ymd_to_DateTime( $txn->created ),
1.7       andrew    534:         rate  => $rates->{$work_type} || $rates->{default} || 0,
1.4       andrew    535:     );
                    536:
                    537:     if ( $work_type && $work_type ne 'Normal' ) {
                    538:         $fee{detail} = $work_type . ' rate';
                    539:     }
                    540:
                    541:     return \%fee;
1.33      andrew    542: }
                    543:
                    544: sub make_expense {
                    545:     my ( $txn, $ticket ) = @_;
                    546:
                    547:     my $amount = $txn->cf('ExpenseAmount') or return;
                    548:
                    549:     my %expense = (
                    550:         id       => $txn->id,
                    551:         contents => $txn->created . ' ('
                    552:             . $txn->id . ')' . "\n\n"
                    553:             . ( $txn->data || $ticket->subject ),
                    554:         amount => $amount,
                    555:         date   => ymd_to_DateTime( $txn->created ),
1.36      andrew    556:
1.33      andrew    557:         # detail => ???,
                    558:     );
                    559:
                    560:     return \%expense;
1.4       andrew    561: }
                    562:
                    563: sub hours_for_date {
                    564:     my ( $invoice, $date ) = @_;
                    565:
                    566:     my $hours = {};
                    567:     if ( $invoice->{hours} ) {
                    568:         foreach my $h ( @{ $invoice->{hours} } ) {
                    569:             next if $h->{start} && $h->{start} > $date;
                    570:             next if $h->{end} < $date;
                    571:
                    572:             $hours = $h->{hours};
                    573:             last;
                    574:         }
                    575:     }
                    576:     return $hours;
1.1       andrew    577: }
                    578:
1.6       andrew    579: sub ymd_to_DateTime {
                    580:     my ($ymd) = @_;
1.10      andrew    581:     my ( $date, $time ) = split /[\sT]/, $ymd;
1.6       andrew    582:     my ( $year, $month, $day ) = split '-', $date;
                    583:     my ( $hour, $minute, $second ) = split ':', $time if $time;
                    584:
                    585:     return DateTime->new(
1.28      andrew    586:         year      => $year,
                    587:         month     => $month,
                    588:         day       => $day,
                    589:         hour      => $hour || 0,
                    590:         minute    => $minute || 0,
                    591:         second    => $second || 0,
                    592:         time_zone => 'local',
1.6       andrew    593:     );
                    594: }
                    595:
1.1       andrew    596: package RTI::Config;
                    597: use strict;
                    598: use warnings;
                    599:
                    600: use 5.010;
                    601:
1.5       andrew    602: use YAML::Any qw/ LoadFile Dump Load /;
1.22      andrew    603: use File::Spec;
1.1       andrew    604:
                    605: sub new {
                    606:     my ( $class, $args ) = @_;
                    607:
                    608:     my $self = { file => '', };
                    609:     bless $self, $class;
1.5       andrew    610:
1.1       andrew    611:     my $file = $args->{file} || $self->_find_config;
                    612:     $self->read_config($file);
                    613:
                    614:     return $self;
                    615: }
                    616:
                    617: sub _find_config {
                    618:     my ($self) = @_;
                    619:
                    620:     # XXX This needs to be better
                    621:     foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
1.6       andrew    622:         foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoicing', $ENV{HOME} ) {
1.1       andrew    623:             my $path = join '/', $dir, $file;
                    624:             return $path if -e $path;
                    625:         }
                    626:     }
                    627:     return;
                    628: }
                    629:
                    630: sub read_config {
                    631:     my ( $self, $file ) = @_;
                    632:
                    633:     $file ||= $self->{file};
                    634:     die "$file: no such file\n" unless -e $file;
                    635:
                    636:     my $c = LoadFile($file) or die "Unable to load $file\n";
                    637:
1.25      andrew    638:     $c->{customers} ||= [];
1.1       andrew    639:     if ( $c->{default} ) {
1.25      andrew    640:         foreach my $cust ( @{ $c->{customers} } ) {
1.1       andrew    641:             foreach my $k ( keys %{ $c->{default} } ) {
1.5       andrew    642:                 $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1       andrew    643:             }
                    644:         }
                    645:     }
                    646:
                    647:     $self->{_config} = $c;
                    648:     $self->{file}    = $file;
                    649: }
                    650:
                    651: sub get {
                    652:     my ( $self, $key ) = @_;
1.6       andrew    653:     my $value = Load( Dump( $self->{_config}->{$key} ) );
1.18      andrew    654:
                    655:     return $value if $value;
1.29      andrew    656:     my ( $volume, $directories, $file )
                    657:         = File::Spec->splitpath( File::Spec->rel2abs( $self->{file} ) );
1.18      andrew    658:
                    659:     given ($key) {
                    660:         when ('state') {
                    661:             $value = $self->{file};
                    662:             $value =~ s/(?:\.[^.]+)?$/\.state/;
                    663:         }
                    664:         when ('invoice_dir') {
1.29      andrew    665:             $value = File::Spec->catdir( $volume, $directories, 'invoices' );
1.20      andrew    666:         }
                    667:         when ('template_dir') {
1.22      andrew    668:             $value = File::Spec->catdir( $volume, $directories );
1.20      andrew    669:         }
                    670:         when ('invoice_template') {
                    671:             $value = 'invoice.tex.tt';
1.22      andrew    672:         }
                    673:         when ('logo') {
1.29      andrew    674:             $value = File::Spec->catfile( $volume, $directories, 'Logo.pdf' );
1.6       andrew    675:         }
                    676:     }
1.18      andrew    677:
1.6       andrew    678:     return $value;
1.1       andrew    679: }
                    680:
                    681: package RTI::State;
                    682: use strict;
                    683: use warnings;
                    684:
                    685: use 5.010;
                    686:
                    687: use YAML::Any qw/ LoadFile DumpFile /;
                    688:
1.6       andrew    689: my $file = '';
                    690:
1.1       andrew    691: sub new {
1.6       andrew    692:     my $class;
                    693:     ( $class, $file ) = @_;
                    694:
                    695:     my $self = { lastinvoice => 0, };
                    696:     if ( -e $file ) {
                    697:         $self = LoadFile($file) or die "Unable to load state: $!";
                    698:     }
1.1       andrew    699:
                    700:     bless $self, $class;
1.6       andrew    701:
                    702:     die "Need to pass filename to new: $!" unless $file;
1.1       andrew    703:
                    704:     return $self;
1.6       andrew    705: }
                    706:
                    707: sub last_invoice {
                    708:     my ( $self, $custid ) = @_;
                    709:     state %table;
                    710:     if ( !%table ) {
                    711:         foreach my $date ( sort keys %{ $self->{invoice} } ) {
                    712:             while ( my ( $id, $inv ) = each %{ $self->{invoice}->{$date} } ) {
                    713:                 next unless $inv->{custid};
                    714:                 $table{ $inv->{custid} } = {
                    715:                     id   => $id,
                    716:                     date => $date,
                    717:                     %{$inv},
                    718:                 };
                    719:             }
                    720:         }
                    721:     }
                    722:     return $table{$custid} || {};
                    723: }
                    724:
                    725: sub txn_is_invoiced {
                    726:     my ( $self, $txn ) = @_;
                    727:     state %table;
                    728:     if ( !%table ) {
                    729:         foreach my $date ( sort keys %{ $self->{invoice} } ) {
                    730:             foreach my $inv ( values %{ $self->{invoice}->{$date} } ) {
                    731:                 foreach my $t ( @{ $inv->{transactions} } ) {
                    732:                     $table{$t} = 1;
                    733:                 }
                    734:             }
                    735:         }
                    736:     }
                    737:     return $table{$txn};
                    738: }
                    739:
                    740: sub save {
                    741:     my ($self) = @_;
                    742:     DumpFile( $file, {%$self} ) or die "Unable to save state: $!";
1.1       andrew    743: }

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