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

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

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

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