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

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

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

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