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

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

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

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