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

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

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

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