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

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

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

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