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

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

1.1       andrew      1: #!/usr/bin/perl
1.24    ! andrew      2: # $AFresh1: rt_invoices.pl,v 1.23 2011/04/08 18:00:16 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.16      andrew     49: while ( my ( $custid, $cust ) = each %{$customers} ) {
                     50:     $cust->{id} = $custid;
1.6       andrew     51:
1.16      andrew     52:     if ( my $invoice = make_invoice($cust) ) {
                     53:         $cust->{invoice} = $invoice;
1.1       andrew     54:     }
                     55: }
                     56:
                     57: my @limits = map +{
                     58:     attribute  => 'status',
                     59:     operator   => '=',
                     60:     value      => $_,
                     61:     aggregator => 'or',
                     62:     },
                     63:
                     64:     # XXX This should be a config option
                     65:     qw/ open stalled resolved /;
                     66:
                     67: if ($startdate) {
                     68:     push @limits,
                     69:         {
                     70:         attribute => 'last_updated',
                     71:         operator  => '>=',
                     72:         value     => $startdate->ymd,
                     73:         };
                     74: }
                     75:
                     76: my $results = $tickets->search(
                     77:     limits  => \@limits,
                     78:     orderby => 'id',
                     79: );
                     80:
                     81: my $count = $results->count;
                     82: print "There are $count results that matched your query\n";
                     83:
                     84: my $iterator = $results->get_iterator;
                     85: while ( my $ticket = &$iterator ) {
1.6       andrew     86:     my $cust = find_customer_for_ticket( $customers, $ticket );
                     87:     if ( !$cust ) {
1.10      andrew     88:         warn "No customer found for ticket " . $ticket->id;
1.7       andrew     89:         next;
                     90:     }
                     91:     if ( !$cust->{invoice} ) {
1.22      andrew     92:         say "$cust->{id} has no open invoices [" . $ticket->id . ']';
1.4       andrew     93:         next;
                     94:     }
1.22      andrew     95:     say 'Giving ticket ' . $ticket->id . " to $cust->{id}";
1.6       andrew     96:     my $invoice = $cust->{invoice};
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} } ) {
                    102:         my $hours = hours_for_date( $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.15      andrew    122:             $invoice->{discount}{amount}
                    123:                 += round( $discount_time * $fee->{rate} );
1.4       andrew    124:             $invoice->{discount}{hours}{$h_type} += $discount_time;
                    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.6       andrew    131:     push @{ $invoice->{projects} }, $project;
1.1       andrew    132: }
                    133:
1.6       andrew    134: while ( my ( $custid, $cust ) = each %{$customers} ) {
                    135:     my $invoice = $cust->{invoice};
1.1       andrew    136:     next unless $invoice->{projects} && @{ $invoice->{projects} };
                    137:
1.12      andrew    138:     my %li = ( custid => $custid, 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);
                    181:     $invoice->{to}           = make_address( $cust->{address} || $custid );
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.9       andrew    221:     printf "Generated %s for %s: \$%.02f\n", $invoice->{file}, $custid,
                    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 {
                    236:     my ( $customers, $ticket ) = @_;
1.4       andrew    237:
1.22      andrew    238:     foreach my $cust ( values %{$customers} ) {
                    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.8       andrew    253:     return fake_customer( $customers, $ticket );
1.6       andrew    254: }
                    255:
                    256: sub fake_customer {
1.8       andrew    257:     my ( $customers, $ticket ) = @_;
                    258:
1.16      andrew    259:     my $cust = $config->get('default') || {};
1.8       andrew    260:
1.16      andrew    261:     ( $cust->{id} ) = $ticket->requestors;
                    262:     return unless $cust->{id};
1.8       andrew    263:
1.14      andrew    264:     $cust->{match} = [
                    265:         {   type  => 'requestors',
1.16      andrew    266:             regex => $cust->{id},
1.14      andrew    267:         }
                    268:     ];
1.13      andrew    269:
1.16      andrew    270:     if ( my $invoice = make_invoice($cust) ) {
1.13      andrew    271:         $cust->{invoice} = $invoice;
1.8       andrew    272:     }
                    273:
1.16      andrew    274:     $customers->{ $cust->{id} } = $cust;
1.8       andrew    275:     return $cust;
                    276: }
                    277:
1.9       andrew    278: sub get_user {
1.8       andrew    279:     my ($id) = @_;
                    280:
1.9       andrew    281:     state %users;
                    282:     return $users{$id} if $users{$id};
1.8       andrew    283:
                    284:     my %map = (
                    285:         address_one   => 'addr1',
                    286:         address_two   => 'addr2',
                    287:         email_address => 'email',
1.9       andrew    288:         real_name     => 'name',
                    289:         name          => 'username',
1.8       andrew    290:     );
                    291:
1.12      andrew    292:     my $users = RT::Client::REST::User->new( rt => $rt, id => $id );
1.8       andrew    293:     $users->retrieve;
                    294:
1.9       andrew    295:     my %user;
1.8       andrew    296:     foreach my $m ( keys %{ $users->_attributes } ) {
                    297:         next unless $users->can($m);
                    298:
                    299:         my $v = $users->$m;
                    300:         next unless $v;
                    301:
                    302:         $m = $map{$m} if exists $map{$m};
                    303:
1.9       andrew    304:         $user{$m} = $v;
1.8       andrew    305:     }
1.6       andrew    306:
1.9       andrew    307:     $users{$id} = \%user;
                    308:     return \%user;
1.13      andrew    309: }
                    310:
                    311: sub make_invoice {
1.14      andrew    312:     my ($cust) = @_;
                    313:
1.21      andrew    314:     my $day  = $cust->{day}       ||= 0;
1.16      andrew    315:     my $per  = $cust->{per}       ||= 'week';
                    316:     my $freq = $cust->{frequency} ||= 1;
1.14      andrew    317:
1.16      andrew    318:     my $day_method;
                    319:     given ($per) {
                    320:         when ('week')  { $per = 'weeks';  $day_method = 'dow' }
                    321:         when ('month') { $per = 'months'; $day_method = 'day' }
                    322:         default { die "Unknown per [$per]\n" }
                    323:     }
1.13      andrew    324:
1.24    ! andrew    325:     my $billends = DateTime->now
        !           326:         ->subtract( days => 1 )
        !           327:         ->set( hour => 23, minute => 59, second => 59 );
1.16      andrew    328:
                    329:     # XXX This is helpful, but monthly and billday > 28 == !!!
1.21      andrew    330:     $billends->subtract( days => 1 )
                    331:         while $day && $billends->$day_method != $day;
1.16      andrew    332:
1.24    ! andrew    333:     my $date = $billends->clone->subtract( $per => $freq )
        !           334:         ->set( hour => 0, minute => 0, second => 0 );
1.16      andrew    335:
                    336:     my %invoice = ( end => $billends->clone->subtract( seconds => 1 ) );
                    337:
                    338:     my $lastinvoice = $state->last_invoice( $cust->{id} );
                    339:     if ( $lastinvoice->{date} ) {
                    340:         my $last_invoice_date = ymd_to_DateTime( $lastinvoice->{date} );
                    341:         $date = $last_invoice_date->clone->add( days => 1 );
                    342:
                    343:         $invoice{start} = $date->clone;
                    344:
                    345:         $startdate = $date->clone->subtract( $per => $freq )
                    346:             if !$startdate || $startdate > $date;
                    347:     }
                    348:
1.23      andrew    349:     # Is the start date more than $freq $per before the end date?
                    350:     my $diff = $billends - $date;
1.24    ! andrew    351:     return if $diff->in_units($per) < 1;
1.16      andrew    352:
                    353:     if ( $cust->{base_rate} ) {
                    354:         my ( $project, $hours ) = make_base_project(
                    355:             $cust,
                    356:             {   startdate  => $date,
                    357:                 enddate    => $billends,
                    358:                 per        => $per,
                    359:                 freq       => $freq,
                    360:                 day        => $day,
                    361:                 day_method => $day_method,
                    362:             }
                    363:         );
                    364:
                    365:         if ( @{ $project->{fees} } ) {
                    366:             $invoice{end}   = $project->{end};
                    367:             $invoice{hours} = $hours;
                    368:             push @{ $invoice{projects} }, $project;
                    369:         }
                    370:     }
                    371:     elsif ( $cust->{hours} ) {
1.14      andrew    372:         $invoice{hours} = [
1.16      andrew    373:             {   end   => $invoice{end}->clone,
1.14      andrew    374:                 hours => $cust->{hours},
                    375:             }
                    376:         ];
                    377:     }
1.13      andrew    378:
1.16      andrew    379:     return if $invoice{start} && $invoice{end} < $invoice{start};
                    380:
1.13      andrew    381:     return \%invoice;
1.12      andrew    382: }
                    383:
1.16      andrew    384: sub make_base_project {
                    385:     my ( $cust, $args ) = @_;
                    386:
                    387:     my $date       = $args->{startdate};
                    388:     my $enddate    = $args->{enddate};
                    389:     my $per        = $args->{per};
                    390:     my $freq       = $args->{freq};
                    391:     my $day        = $args->{day};
                    392:     my $day_method = $args->{day_method};
                    393:
                    394:     my $title
                    395:         = $freq == 1
                    396:         ? ucfirst( $cust->{per} . 'ly' )
                    397:         : $freq . ' ' . ucfirst( $cust->{per} );
                    398:     $title .= ' Retainer';
                    399:
                    400:     my %project = ( title => $title, start => $date->clone, fees => [], );
                    401:     my @hours;
                    402:
                    403:     while ( $date < $enddate ) {
                    404:         my $start = $date->clone;
                    405:
                    406:         $date->add( $per => $freq );
                    407:         $date = $enddate->clone if $date > $enddate;
                    408:
                    409:         # XXX This is helpful, but monthly and billday > 28 == !!!
1.21      andrew    410:         $date->subtract( days => 1 ) while $day && $date->$day_method != $day;
1.16      andrew    411:
                    412:         my $end = $date->clone->subtract( seconds => 1 );
                    413:
                    414:         last if $end < $start;
                    415:
                    416:         $project{end} = $end->clone;
                    417:
                    418:         push @{ $project{fees} },
                    419:             {
                    420:             count    => 1,
                    421:             rate     => $cust->{base_rate},
                    422:             contents => $start->ymd . ' to ' . $end->ymd,
                    423:             };
                    424:
                    425:         push @hours,
                    426:             {
                    427:             start => $start->clone,
                    428:             end   => $end->clone,
                    429:             hours => { %{ $cust->{hours} } },
                    430:             };
                    431:     }
                    432:
                    433:     return \%project, \@hours;
                    434: }
                    435:
1.12      andrew    436: sub make_address {
                    437:     my ($addr) = @_;
                    438:     my @adr;
1.16      andrew    439:
                    440:     $addr = get_user($addr) unless ref $addr;
1.12      andrew    441:
                    442:     if ( $addr->{organization} ) {
                    443:         push @adr, $addr->{organization};
                    444:     }
                    445:     elsif ( $addr->{name} && !$addr->{attn} ) {
                    446:         push @adr, $addr->{name};
                    447:     }
                    448:
                    449:     if (   ( $addr->{addr1} || $addr->{addr2} )
                    450:         && $addr->{city}
                    451:         && $addr->{state}
                    452:         && $addr->{zip} )
                    453:     {
                    454:         push @adr, $addr->{attn}  if $addr->{attn};
                    455:         push @adr, $addr->{addr1} if $addr->{addr1};
                    456:         push @adr, $addr->{addr2} if $addr->{addr2};
                    457:         push @adr,
                    458:             $addr->{city} . ', ' . $addr->{state} . '  ' . $addr->{zip};
                    459:     }
                    460:     else {
                    461:         push @adr, $addr->{email} if $addr->{email};
                    462:     }
                    463:
                    464:     return join "\n\n", @adr;
1.6       andrew    465: }
                    466:
                    467: sub make_project {
1.7       andrew    468:     my ( $ticket, $cust ) = @_;
1.6       andrew    469:
                    470:     my %project = (
                    471:         id     => $ticket->id,
                    472:         queue  => $ticket->queue,
                    473:         owner  => $ticket->owner,
                    474:         title  => $ticket->subject,
                    475:         detail => 'Ticket: '
                    476:             . $ticket->id
1.17      andrew    477:             . ' Status: '
                    478:             . $ticket->status
1.6       andrew    479:             . ' Requestors: '
                    480:             . join( ', ', $ticket->requestors ),
                    481:         fees     => [],
                    482:         expenses => [],
                    483:     );
                    484:
                    485:     my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
                    486:     my $txn_i = $txns->get_iterator;
                    487:     while ( my $txn = $txn_i->() ) {
                    488:         next unless $txn->time_taken;
                    489:         next if $state->txn_is_invoiced( $txn->id );
                    490:
1.7       andrew    491:         my $fee = make_fee( $txn, $cust->{rates}, $ticket );
                    492:
1.6       andrew    493:         if ( !( $fee->{rate} && $fee->{count} ) ) {
                    494:             warn "Invalid Fee, no rate or count";
                    495:             next;
                    496:         }
                    497:
1.7       andrew    498:         my $invoice = $cust->{invoice};
                    499:         next
                    500:             if $invoice->{start}
                    501:                 && $invoice->{start} > $fee->{date};
1.6       andrew    502:         next if $invoice->{end} < $fee->{date};
                    503:
                    504:         push @{ $project{fees} },         $fee;
                    505:         push @{ $project{transactions} }, $txn->id;
1.4       andrew    506:     }
1.6       andrew    507:
                    508:     return \%project;
1.4       andrew    509: }
                    510:
                    511: sub make_fee {
1.7       andrew    512:     my ( $txn, $rates, $ticket ) = @_;
                    513:
                    514:     # XXX Only need $ticket for the alternate subject
1.4       andrew    515:
                    516:     my $work_time = sprintf "%.03f", $txn->time_taken / 60;
                    517:     my $work_type = $txn->cf('WorkType');
                    518:
                    519:     my %fee = (
                    520:         id       => $txn->id,
                    521:         contents => $txn->created . ' ('
                    522:             . $txn->id . ')' . "\n\n"
                    523:             . ( $txn->data || $ticket->subject ),
                    524:         count => $work_time,
                    525:         type  => $work_type,
1.6       andrew    526:         date  => ymd_to_DateTime( $txn->created ),
1.7       andrew    527:         rate  => $rates->{$work_type} || $rates->{default} || 0,
1.4       andrew    528:     );
                    529:
                    530:     if ( $work_type && $work_type ne 'Normal' ) {
                    531:         $fee{detail} = $work_type . ' rate';
                    532:     }
                    533:
                    534:     return \%fee;
                    535: }
                    536:
                    537: sub hours_for_date {
                    538:     my ( $invoice, $date ) = @_;
                    539:
                    540:     my $hours = {};
                    541:     if ( $invoice->{hours} ) {
                    542:         foreach my $h ( @{ $invoice->{hours} } ) {
                    543:             next if $h->{start} && $h->{start} > $date;
                    544:             next if $h->{end} < $date;
                    545:
                    546:             $hours = $h->{hours};
                    547:             last;
                    548:         }
                    549:     }
                    550:     return $hours;
1.1       andrew    551: }
                    552:
1.6       andrew    553: sub ymd_to_DateTime {
                    554:     my ($ymd) = @_;
1.10      andrew    555:     my ( $date, $time ) = split /[\sT]/, $ymd;
1.6       andrew    556:     my ( $year, $month, $day ) = split '-', $date;
                    557:     my ( $hour, $minute, $second ) = split ':', $time if $time;
                    558:
                    559:     return DateTime->new(
                    560:         year   => $year,
                    561:         month  => $month,
                    562:         day    => $day,
                    563:         hour   => $hour || 0,
                    564:         minute => $minute || 0,
                    565:         second => $second || 0,
                    566:     );
                    567: }
                    568:
1.1       andrew    569: package RTI::Config;
                    570: use strict;
                    571: use warnings;
                    572:
                    573: use 5.010;
                    574:
1.5       andrew    575: use YAML::Any qw/ LoadFile Dump Load /;
1.22      andrew    576: use File::Spec;
1.1       andrew    577:
                    578: sub new {
                    579:     my ( $class, $args ) = @_;
                    580:
                    581:     my $self = { file => '', };
                    582:     bless $self, $class;
1.5       andrew    583:
1.1       andrew    584:     my $file = $args->{file} || $self->_find_config;
                    585:     $self->read_config($file);
                    586:
                    587:     return $self;
                    588: }
                    589:
                    590: sub _find_config {
                    591:     my ($self) = @_;
                    592:
                    593:     # XXX This needs to be better
                    594:     foreach my $file (qw/ rt_invoice.conf rt_invoice.cfg .rt_invoicerc /) {
1.6       andrew    595:         foreach my $dir ( '.', $ENV{HOME} . '/.rt_invoicing', $ENV{HOME} ) {
1.1       andrew    596:             my $path = join '/', $dir, $file;
                    597:             return $path if -e $path;
                    598:         }
                    599:     }
                    600:     return;
                    601: }
                    602:
                    603: sub read_config {
                    604:     my ( $self, $file ) = @_;
                    605:
                    606:     $file ||= $self->{file};
                    607:     die "$file: no such file\n" unless -e $file;
                    608:
                    609:     my $c = LoadFile($file) or die "Unable to load $file\n";
                    610:
1.6       andrew    611:     $c->{customers} ||= {};
1.1       andrew    612:     if ( $c->{default} ) {
1.6       andrew    613:         foreach my $cust ( values %{ $c->{customers} } ) {
1.1       andrew    614:             foreach my $k ( keys %{ $c->{default} } ) {
1.5       andrew    615:                 $cust->{$k} //= Load( Dump( $c->{default}->{$k} ) );
1.1       andrew    616:             }
                    617:         }
                    618:     }
                    619:
                    620:     $self->{_config} = $c;
                    621:     $self->{file}    = $file;
                    622: }
                    623:
                    624: sub get {
                    625:     my ( $self, $key ) = @_;
1.6       andrew    626:     my $value = Load( Dump( $self->{_config}->{$key} ) );
1.18      andrew    627:
                    628:     return $value if $value;
1.22      andrew    629:     my ($volume,$directories,$file) =File::Spec->splitpath(
                    630:          File::Spec->rel2abs( $self->{file} ));
1.18      andrew    631:
                    632:     given ($key) {
                    633:         when ('state') {
                    634:             $value = $self->{file};
                    635:             $value =~ s/(?:\.[^.]+)?$/\.state/;
                    636:         }
                    637:         when ('invoice_dir') {
1.22      andrew    638:             $value = File::Spec->catdir($volume, $directories, 'invoices' );
1.20      andrew    639:         }
                    640:         when ('template_dir') {
1.22      andrew    641:             $value = File::Spec->catdir( $volume, $directories );
1.20      andrew    642:         }
                    643:         when ('invoice_template') {
                    644:             $value = 'invoice.tex.tt';
1.22      andrew    645:         }
                    646:         when ('logo') {
                    647:             $value = File::Spec->catfile($volume, $directories, 'Logo.pdf' );
1.6       andrew    648:         }
                    649:     }
1.18      andrew    650:
1.6       andrew    651:     return $value;
1.1       andrew    652: }
                    653:
                    654: package RTI::State;
                    655: use strict;
                    656: use warnings;
                    657:
                    658: use 5.010;
                    659:
                    660: use YAML::Any qw/ LoadFile DumpFile /;
                    661:
1.6       andrew    662: my $file = '';
                    663:
1.1       andrew    664: sub new {
1.6       andrew    665:     my $class;
                    666:     ( $class, $file ) = @_;
                    667:
                    668:     my $self = { lastinvoice => 0, };
                    669:     if ( -e $file ) {
                    670:         $self = LoadFile($file) or die "Unable to load state: $!";
                    671:     }
1.1       andrew    672:
                    673:     bless $self, $class;
1.6       andrew    674:
                    675:     die "Need to pass filename to new: $!" unless $file;
1.1       andrew    676:
                    677:     return $self;
1.6       andrew    678: }
                    679:
                    680: sub last_invoice {
                    681:     my ( $self, $custid ) = @_;
                    682:     state %table;
                    683:     if ( !%table ) {
                    684:         foreach my $date ( sort keys %{ $self->{invoice} } ) {
                    685:             while ( my ( $id, $inv ) = each %{ $self->{invoice}->{$date} } ) {
                    686:                 next unless $inv->{custid};
                    687:                 $table{ $inv->{custid} } = {
                    688:                     id   => $id,
                    689:                     date => $date,
                    690:                     %{$inv},
                    691:                 };
                    692:             }
                    693:         }
                    694:     }
                    695:     return $table{$custid} || {};
                    696: }
                    697:
                    698: sub txn_is_invoiced {
                    699:     my ( $self, $txn ) = @_;
                    700:     state %table;
                    701:     if ( !%table ) {
                    702:         foreach my $date ( sort keys %{ $self->{invoice} } ) {
                    703:             foreach my $inv ( values %{ $self->{invoice}->{$date} } ) {
                    704:                 foreach my $t ( @{ $inv->{transactions} } ) {
                    705:                     $table{$t} = 1;
                    706:                 }
                    707:             }
                    708:         }
                    709:     }
                    710:     return $table{$txn};
                    711: }
                    712:
                    713: sub save {
                    714:     my ($self) = @_;
                    715:     DumpFile( $file, {%$self} ) or die "Unable to save state: $!";
1.1       andrew    716: }

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