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

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

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

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