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

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

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

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