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

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

1.1       andrew      1: #!/usr/bin/perl
1.20    ! andrew      2: # $AFresh1: rt_invoices.pl,v 1.19 2011/03/22 05:27:12 andrew Exp $
1.11      andrew      3: ########################################################################
                      4: # Copyright (c) 2011 Andrew Fresh <andrew@afresh1.com>
                      5: #
                      6: # Permission to use, copy, modify, and distribute this software for any
                      7: # purpose with or without fee is hereby granted, provided that the above
                      8: # copyright notice and this permission notice appear in all copies.
                      9: #
                     10: # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     11: # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12: # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     13: # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14: # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     15: # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     16: # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
                     17: ########################################################################
1.1       andrew     18: use strict;
                     19: use warnings;
                     20:
                     21: use 5.010;
                     22:
                     23: use Template;
                     24: use RT::Client::REST;
                     25: use RT::Client::REST::Ticket;
                     26: use RT::Client::REST::User;
                     27:
1.18      andrew     28: use File::Path;
1.1       andrew     29: use DateTime;
                     30:
                     31: my $config = RTI::Config->new();
1.6       andrew     32: my $state  = RTI::State->new( $config->get('state') );
1.1       andrew     33:
1.6       andrew     34: my $rt_conf = $config->get('rt');
                     35: my $rt      = RT::Client::REST->new(
                     36:     server  => $rt_conf->{server},
                     37:     timeout => $rt_conf->{timeout},
                     38: );
                     39: my $tickets = RT::Client::REST::Ticket->new( rt => $rt );
1.1       andrew     40:
1.6       andrew     41: $rt->login( username => $rt_conf->{user}, password => $rt_conf->{pass} );
                     42:
                     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.20    ! andrew    213:     my $tt = Template->new(
        !           214:         INCLUDE_PATH => $config->get('template_dir'),
        !           215:     )|| die $Template::ERROR, "\n";
        !           216:
        !           217:     $tt->process( $config->get('invoice_template'), $invoice, $file )
1.1       andrew    218:         or die $tt->error . "\n";
                    219:
1.9       andrew    220:     printf "Generated %s for %s: \$%.02f\n", $invoice->{file}, $custid,
                    221:         $invoice->{total};
1.1       andrew    222: }
                    223:
1.6       andrew    224: $state->save;
1.1       andrew    225:
                    226: sub round {
                    227:     my ($amount) = @_;
                    228:
                    229:     #$amount =~ s/\.\d\d\K.*$//;
                    230:     #return $amount;
                    231:     return sprintf "%.02f", $amount;
1.4       andrew    232: }
                    233:
1.6       andrew    234: sub find_customer_for_ticket {
                    235:     my ( $customers, $ticket ) = @_;
1.4       andrew    236:
1.6       andrew    237: INVOICE: foreach my $cust ( values %{$customers} ) {
                    238:         next INVOICE unless $cust->{match};
                    239:         foreach my $m ( @{ $cust->{match} } ) {
1.4       andrew    240:             my $type = $m->{type};
                    241:             my $thing = join ' ', $ticket->$type;
                    242:
                    243:             if ( $m->{$type} ) {
                    244:                 my $match = lc $m->{$type};
                    245:                 next INVOICE unless lc($thing) ~~ $match;
                    246:             }
                    247:             elsif ( $m->{regex} ) {
                    248:                 next INVOICE unless $thing ~~ /\Q$m->{regex}\E/;
                    249:             }
                    250:             else {
                    251:                 warn "Invalid match!";
                    252:                 next INVOICE;
                    253:             }
                    254:         }
1.6       andrew    255:         return $cust;
                    256:     }
                    257:
1.8       andrew    258:     return fake_customer( $customers, $ticket );
1.6       andrew    259: }
                    260:
                    261: sub fake_customer {
1.8       andrew    262:     my ( $customers, $ticket ) = @_;
                    263:
1.16      andrew    264:     my $cust = $config->get('default') || {};
1.8       andrew    265:
1.16      andrew    266:     ( $cust->{id} ) = $ticket->requestors;
                    267:     return unless $cust->{id};
1.8       andrew    268:
1.14      andrew    269:     $cust->{match} = [
                    270:         {   type  => 'requestors',
1.16      andrew    271:             regex => $cust->{id},
1.14      andrew    272:         }
                    273:     ];
1.13      andrew    274:
1.16      andrew    275:     if ( my $invoice = make_invoice($cust) ) {
1.13      andrew    276:         $cust->{invoice} = $invoice;
1.8       andrew    277:     }
                    278:
1.16      andrew    279:     $customers->{ $cust->{id} } = $cust;
1.8       andrew    280:     return $cust;
                    281: }
                    282:
1.9       andrew    283: sub get_user {
1.8       andrew    284:     my ($id) = @_;
                    285:
1.9       andrew    286:     state %users;
                    287:     return $users{$id} if $users{$id};
1.8       andrew    288:
                    289:     my %map = (
                    290:         address_one   => 'addr1',
                    291:         address_two   => 'addr2',
                    292:         email_address => 'email',
1.9       andrew    293:         real_name     => 'name',
                    294:         name          => 'username',
1.8       andrew    295:     );
                    296:
1.12      andrew    297:     my $users = RT::Client::REST::User->new( rt => $rt, id => $id );
1.8       andrew    298:     $users->retrieve;
                    299:
1.9       andrew    300:     my %user;
1.8       andrew    301:     foreach my $m ( keys %{ $users->_attributes } ) {
                    302:         next unless $users->can($m);
                    303:
                    304:         my $v = $users->$m;
                    305:         next unless $v;
                    306:
                    307:         $m = $map{$m} if exists $map{$m};
                    308:
1.9       andrew    309:         $user{$m} = $v;
1.8       andrew    310:     }
1.6       andrew    311:
1.9       andrew    312:     $users{$id} = \%user;
                    313:     return \%user;
1.13      andrew    314: }
                    315:
                    316: sub make_invoice {
1.14      andrew    317:     my ($cust) = @_;
                    318:
1.16      andrew    319:     my $day  = $cust->{day}       ||= 1;
                    320:     my $per  = $cust->{per}       ||= 'week';
                    321:     my $freq = $cust->{frequency} ||= 1;
1.14      andrew    322:
1.16      andrew    323:     my $day_method;
                    324:     given ($per) {
                    325:         when ('week')  { $per = 'weeks';  $day_method = 'dow' }
                    326:         when ('month') { $per = 'months'; $day_method = 'day' }
                    327:         default { die "Unknown per [$per]\n" }
                    328:     }
1.13      andrew    329:
1.16      andrew    330:     my $billends = DateTime->now->set( hour => 0, minute => 0, second => 0 );
                    331:
                    332:     # XXX This is helpful, but monthly and billday > 28 == !!!
                    333:     $billends->subtract( days => 1 ) while $billends->$day_method != $day;
                    334:
                    335:     my $date = $billends->clone->subtract( $per => $freq );
                    336:
                    337:     my %invoice = ( end => $billends->clone->subtract( seconds => 1 ) );
                    338:
                    339:     my $lastinvoice = $state->last_invoice( $cust->{id} );
                    340:     if ( $lastinvoice->{date} ) {
                    341:         my $last_invoice_date = ymd_to_DateTime( $lastinvoice->{date} );
                    342:         $date = $last_invoice_date->clone->add( days => 1 );
                    343:
                    344:         $invoice{start} = $date->clone;
                    345:
                    346:         $startdate = $date->clone->subtract( $per => $freq )
                    347:             if !$startdate || $startdate > $date;
                    348:     }
                    349:
                    350:     return if $billends <= $date;
                    351:
                    352:     if ( $cust->{base_rate} ) {
                    353:         my ( $project, $hours ) = make_base_project(
                    354:             $cust,
                    355:             {   startdate  => $date,
                    356:                 enddate    => $billends,
                    357:                 per        => $per,
                    358:                 freq       => $freq,
                    359:                 day        => $day,
                    360:                 day_method => $day_method,
                    361:             }
                    362:         );
                    363:
                    364:         if ( @{ $project->{fees} } ) {
                    365:             $invoice{end}   = $project->{end};
                    366:             $invoice{hours} = $hours;
                    367:             push @{ $invoice{projects} }, $project;
                    368:         }
                    369:     }
                    370:     elsif ( $cust->{hours} ) {
1.14      andrew    371:         $invoice{hours} = [
1.16      andrew    372:             {   end   => $invoice{end}->clone,
1.14      andrew    373:                 hours => $cust->{hours},
                    374:             }
                    375:         ];
                    376:     }
1.13      andrew    377:
1.16      andrew    378:     return if $invoice{start} && $invoice{end} < $invoice{start};
                    379:
1.13      andrew    380:     return \%invoice;
1.12      andrew    381: }
                    382:
1.16      andrew    383: sub make_base_project {
                    384:     my ( $cust, $args ) = @_;
                    385:
                    386:     my $date       = $args->{startdate};
                    387:     my $enddate    = $args->{enddate};
                    388:     my $per        = $args->{per};
                    389:     my $freq       = $args->{freq};
                    390:     my $day        = $args->{day};
                    391:     my $day_method = $args->{day_method};
                    392:
                    393:     my $title
                    394:         = $freq == 1
                    395:         ? ucfirst( $cust->{per} . 'ly' )
                    396:         : $freq . ' ' . ucfirst( $cust->{per} );
                    397:     $title .= ' Retainer';
                    398:
                    399:     my %project = ( title => $title, start => $date->clone, fees => [], );
                    400:     my @hours;
                    401:
                    402:     while ( $date < $enddate ) {
                    403:         my $start = $date->clone;
                    404:
                    405:         $date->add( $per => $freq );
                    406:         $date = $enddate->clone if $date > $enddate;
                    407:
                    408:         # XXX This is helpful, but monthly and billday > 28 == !!!
                    409:         $date->subtract( days => 1 ) while $date->$day_method != $day;
                    410:
                    411:         my $end = $date->clone->subtract( seconds => 1 );
                    412:
                    413:         last if $end < $start;
                    414:
                    415:         $project{end} = $end->clone;
                    416:
                    417:         push @{ $project{fees} },
                    418:             {
                    419:             count    => 1,
                    420:             rate     => $cust->{base_rate},
                    421:             contents => $start->ymd . ' to ' . $end->ymd,
                    422:             };
                    423:
                    424:         push @hours,
                    425:             {
                    426:             start => $start->clone,
                    427:             end   => $end->clone,
                    428:             hours => { %{ $cust->{hours} } },
                    429:             };
                    430:     }
                    431:
                    432:     return \%project, \@hours;
                    433: }
                    434:
1.12      andrew    435: sub make_address {
                    436:     my ($addr) = @_;
                    437:     my @adr;
1.16      andrew    438:
                    439:     $addr = get_user($addr) unless ref $addr;
1.12      andrew    440:
                    441:     if ( $addr->{organization} ) {
                    442:         push @adr, $addr->{organization};
                    443:     }
                    444:     elsif ( $addr->{name} && !$addr->{attn} ) {
                    445:         push @adr, $addr->{name};
                    446:     }
                    447:
                    448:     if (   ( $addr->{addr1} || $addr->{addr2} )
                    449:         && $addr->{city}
                    450:         && $addr->{state}
                    451:         && $addr->{zip} )
                    452:     {
                    453:         push @adr, $addr->{attn}  if $addr->{attn};
                    454:         push @adr, $addr->{addr1} if $addr->{addr1};
                    455:         push @adr, $addr->{addr2} if $addr->{addr2};
                    456:         push @adr,
                    457:             $addr->{city} . ', ' . $addr->{state} . '  ' . $addr->{zip};
                    458:     }
                    459:     else {
                    460:         push @adr, $addr->{email} if $addr->{email};
                    461:     }
                    462:
                    463:     return join "\n\n", @adr;
1.6       andrew    464: }
                    465:
                    466: sub make_project {
1.7       andrew    467:     my ( $ticket, $cust ) = @_;
1.6       andrew    468:
                    469:     my %project = (
                    470:         id     => $ticket->id,
                    471:         queue  => $ticket->queue,
                    472:         owner  => $ticket->owner,
                    473:         title  => $ticket->subject,
                    474:         detail => 'Ticket: '
                    475:             . $ticket->id
1.17      andrew    476:             . ' Status: '
                    477:             . $ticket->status
1.6       andrew    478:             . ' Requestors: '
                    479:             . join( ', ', $ticket->requestors ),
                    480:         fees     => [],
                    481:         expenses => [],
                    482:     );
                    483:
                    484:     my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
                    485:     my $txn_i = $txns->get_iterator;
                    486:     while ( my $txn = $txn_i->() ) {
                    487:         next unless $txn->time_taken;
                    488:         next if $state->txn_is_invoiced( $txn->id );
                    489:
1.7       andrew    490:         my $fee = make_fee( $txn, $cust->{rates}, $ticket );
                    491:
1.6       andrew    492:         if ( !( $fee->{rate} && $fee->{count} ) ) {
                    493:             warn "Invalid Fee, no rate or count";
                    494:             next;
                    495:         }
                    496:
1.7       andrew    497:         my $invoice = $cust->{invoice};
                    498:         next
                    499:             if $invoice->{start}
                    500:                 && $invoice->{start} > $fee->{date};
1.6       andrew    501:         next if $invoice->{end} < $fee->{date};
                    502:
                    503:         push @{ $project{fees} },         $fee;
                    504:         push @{ $project{transactions} }, $txn->id;
1.4       andrew    505:     }
1.6       andrew    506:
                    507:     return \%project;
1.4       andrew    508: }
                    509:
                    510: sub make_fee {
1.7       andrew    511:     my ( $txn, $rates, $ticket ) = @_;
                    512:
                    513:     # XXX Only need $ticket for the alternate subject
1.4       andrew    514:
                    515:     my $work_time = sprintf "%.03f", $txn->time_taken / 60;
                    516:     my $work_type = $txn->cf('WorkType');
                    517:
                    518:     my %fee = (
                    519:         id       => $txn->id,
                    520:         contents => $txn->created . ' ('
                    521:             . $txn->id . ')' . "\n\n"
                    522:             . ( $txn->data || $ticket->subject ),
                    523:         count => $work_time,
                    524:         type  => $work_type,
1.6       andrew    525:         date  => ymd_to_DateTime( $txn->created ),
1.7       andrew    526:         rate  => $rates->{$work_type} || $rates->{default} || 0,
1.4       andrew    527:     );
                    528:
                    529:     if ( $work_type && $work_type ne 'Normal' ) {
                    530:         $fee{detail} = $work_type . ' rate';
                    531:     }
                    532:
                    533:     return \%fee;
                    534: }
                    535:
                    536: sub hours_for_date {
                    537:     my ( $invoice, $date ) = @_;
                    538:
                    539:     my $hours = {};
                    540:     if ( $invoice->{hours} ) {
                    541:         foreach my $h ( @{ $invoice->{hours} } ) {
                    542:             next if $h->{start} && $h->{start} > $date;
                    543:             next if $h->{end} < $date;
                    544:
                    545:             $hours = $h->{hours};
                    546:             last;
                    547:         }
                    548:     }
                    549:     return $hours;
1.1       andrew    550: }
                    551:
1.6       andrew    552: sub ymd_to_DateTime {
                    553:     my ($ymd) = @_;
1.10      andrew    554:     my ( $date, $time ) = split /[\sT]/, $ymd;
1.6       andrew    555:     my ( $year, $month, $day ) = split '-', $date;
                    556:     my ( $hour, $minute, $second ) = split ':', $time if $time;
                    557:
                    558:     return DateTime->new(
                    559:         year   => $year,
                    560:         month  => $month,
                    561:         day    => $day,
                    562:         hour   => $hour || 0,
                    563:         minute => $minute || 0,
                    564:         second => $second || 0,
                    565:     );
                    566: }
                    567:
1.1       andrew    568: package RTI::Config;
                    569: use strict;
                    570: use warnings;
                    571:
                    572: use 5.010;
                    573:
1.5       andrew    574: use YAML::Any qw/ LoadFile Dump Load /;
1.6       andrew    575: use File::Basename;
1.1       andrew    576:
                    577: sub new {
                    578:     my ( $class, $args ) = @_;
                    579:
                    580:     my $self = { file => '', };
                    581:     bless $self, $class;
1.5       andrew    582:
1.1       andrew    583:     my $file = $args->{file} || $self->_find_config;
                    584:     $self->read_config($file);
                    585:
                    586:     return $self;
                    587: }
                    588:
                    589: sub _find_config {
                    590:     my ($self) = @_;
                    591:
                    592:     # XXX This needs to be better
                    593:     foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
1.6       andrew    594:         foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoicing', $ENV{HOME} ) {
1.1       andrew    595:             my $path = join '/', $dir, $file;
                    596:             return $path if -e $path;
                    597:         }
                    598:     }
                    599:     return;
                    600: }
                    601:
                    602: sub read_config {
                    603:     my ( $self, $file ) = @_;
                    604:
                    605:     $file ||= $self->{file};
                    606:     die "$file: no such file\n" unless -e $file;
                    607:
                    608:     my $c = LoadFile($file) or die "Unable to load $file\n";
                    609:
1.6       andrew    610:     $c->{customers} ||= {};
1.1       andrew    611:     if ( $c->{default} ) {
1.6       andrew    612:         foreach my $cust ( values %{ $c->{customers} } ) {
1.1       andrew    613:             foreach my $k ( keys %{ $c->{default} } ) {
1.5       andrew    614:                 $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1       andrew    615:             }
                    616:         }
                    617:     }
                    618:
                    619:     $self->{_config} = $c;
                    620:     $self->{file}    = $file;
                    621: }
                    622:
                    623: sub get {
                    624:     my ( $self, $key ) = @_;
1.6       andrew    625:     my $value = Load( Dump( $self->{_config}->{$key} ) );
1.18      andrew    626:
                    627:     return $value if $value;
                    628:
                    629:     given ($key) {
                    630:         when ('state') {
                    631:             $value = $self->{file};
                    632:             $value =~ s/(?:\.[^.]+)?$/\.state/;
                    633:         }
                    634:         when ('invoice_dir') {
                    635:             $value = dirname( $self->{file} ) . '/invoices';
1.20    ! andrew    636:         }
        !           637:         when ('template_dir') {
        !           638:             $value = dirname( $self->{file} );
        !           639:         }
        !           640:         when ('invoice_template') {
        !           641:             $value = 'invoice.tex.tt';
1.6       andrew    642:         }
                    643:     }
1.18      andrew    644:
1.6       andrew    645:     return $value;
1.1       andrew    646: }
                    647:
                    648: package RTI::State;
                    649: use strict;
                    650: use warnings;
                    651:
                    652: use 5.010;
                    653:
                    654: use YAML::Any qw/ LoadFile DumpFile /;
                    655:
1.6       andrew    656: my $file = '';
                    657:
1.1       andrew    658: sub new {
1.6       andrew    659:     my $class;
                    660:     ( $class, $file ) = @_;
                    661:
                    662:     my $self = { lastinvoice => 0, };
                    663:     if ( -e $file ) {
                    664:         $self = LoadFile($file) or die "Unable to load state: $!";
                    665:     }
1.1       andrew    666:
                    667:     bless $self, $class;
1.6       andrew    668:
                    669:     die "Need to pass filename to new: $!" unless $file;
1.1       andrew    670:
                    671:     return $self;
1.6       andrew    672: }
                    673:
                    674: sub last_invoice {
                    675:     my ( $self, $custid ) = @_;
                    676:     state %table;
                    677:     if ( !%table ) {
                    678:         foreach my $date ( sort keys %{ $self->{invoice} } ) {
                    679:             while ( my ( $id, $inv ) = each %{ $self->{invoice}->{$date} } ) {
                    680:                 next unless $inv->{custid};
                    681:                 $table{ $inv->{custid} } = {
                    682:                     id   => $id,
                    683:                     date => $date,
                    684:                     %{$inv},
                    685:                 };
                    686:             }
                    687:         }
                    688:     }
                    689:     return $table{$custid} || {};
                    690: }
                    691:
                    692: sub txn_is_invoiced {
                    693:     my ( $self, $txn ) = @_;
                    694:     state %table;
                    695:     if ( !%table ) {
                    696:         foreach my $date ( sort keys %{ $self->{invoice} } ) {
                    697:             foreach my $inv ( values %{ $self->{invoice}->{$date} } ) {
                    698:                 foreach my $t ( @{ $inv->{transactions} } ) {
                    699:                     $table{$t} = 1;
                    700:                 }
                    701:             }
                    702:         }
                    703:     }
                    704:     return $table{$txn};
                    705: }
                    706:
                    707: sub save {
                    708:     my ($self) = @_;
                    709:     DumpFile( $file, {%$self} ) or die "Unable to save state: $!";
1.1       andrew    710: }

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