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

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

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

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