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

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

1.1       andrew      1: #!/usr/bin/perl
1.46    ! andrew      2: # $AFresh1: rt_invoices.pl,v 1.45 2011/12/31 02:14:32 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:
1.40      andrew     31: use lib './lib';    # XXX This is fragile, there are better ways
                     32: use RTI::Config;
                     33: use RTI::State;
1.45      andrew     34: use RTI::Util qw/ round ymd_to_DateTime /;
1.40      andrew     35:
1.1       andrew     36: my $config = RTI::Config->new();
1.6       andrew     37: my $state  = RTI::State->new( $config->get('state') );
1.1       andrew     38:
1.6       andrew     39: my $rt_conf = $config->get('rt');
                     40: my $rt      = RT::Client::REST->new(
                     41:     server  => $rt_conf->{server},
                     42:     timeout => $rt_conf->{timeout},
                     43: );
                     44: my $tickets = RT::Client::REST::Ticket->new( rt => $rt );
1.1       andrew     45:
1.6       andrew     46: $rt->login( username => $rt_conf->{user}, password => $rt_conf->{pass} );
                     47:
1.22      andrew     48: #use YAML;
1.6       andrew     49: #print Dump $config, $state; exit;
1.1       andrew     50:
1.6       andrew     51: my $customers = $config->get('customers');
1.40      andrew     52: my $startdate = set_dates($customers);
1.1       andrew     53:
                     54: my @limits = map +{
                     55:     attribute  => 'status',
                     56:     operator   => '=',
                     57:     value      => $_,
                     58:     aggregator => 'or',
                     59:     },
                     60:
                     61:     # XXX This should be a config option
                     62:     qw/ open stalled resolved /;
                     63:
1.40      andrew     64: push @limits,
                     65:     {
                     66:     attribute => 'last_updated',
                     67:     operator  => '>=',
                     68:     value     => $startdate->ymd,
                     69:     };
1.1       andrew     70:
                     71: my $results = $tickets->search(
                     72:     limits  => \@limits,
                     73:     orderby => 'id',
                     74: );
                     75:
                     76: my $count = $results->count;
                     77: print "There are $count results that matched your query\n";
                     78:
                     79: my $iterator = $results->get_iterator;
                     80: while ( my $ticket = &$iterator ) {
1.43      andrew     81:     my $cust = find_customer_for_ticket( $ticket, $customers );
1.6       andrew     82:     if ( !$cust ) {
1.10      andrew     83:         warn "No customer found for ticket " . $ticket->id;
1.7       andrew     84:         next;
                     85:     }
1.25      andrew     86:
1.41      andrew     87:     next if $cust->{no_invoice};
1.25      andrew     88:     $cust->{invoice} ||= make_invoice($cust);
1.44      andrew     89:
                     90:     die "$cust->{id} has no open invoices [" . $ticket->id . ']'
                     91:         unless $cust->{invoice};
1.1       andrew     92:
1.40      andrew     93:     say 'Ticket ' . $ticket->id . " belongs to $cust->{id}";
                     94:
1.7       andrew     95:     my $project = make_project( $ticket, $cust );
1.6       andrew     96:     next unless @{ $project->{fees} } || @{ $project->{expenses} };
1.1       andrew     97:
1.6       andrew     98:     foreach my $fee ( @{ $project->{fees} } ) {
1.25      andrew     99:         my $hours = hours_for_date( $cust->{invoice}, $fee->{date} );
1.1       andrew    100:
1.38      andrew    101:         my $type  = 'unknown';
                    102:         my $count = $fee->{count};
                    103:         while ( $type && $count > 0 && $type ne 'default' ) {
1.35      andrew    104:             $type = exists $hours->{ $fee->{type} }
                    105:                 && $hours->{ $fee->{type} } > 0 ? $fee->{type} : 'default';
                    106:
                    107:             next unless exists $hours->{$type} && $hours->{$type} > 0;
                    108:
                    109:             my $discount_time = 0;
1.38      andrew    110:             if ( $hours->{$type} > $count ) {
                    111:                 $hours->{$type} -= $count;
                    112:                 $discount_time = $count;
1.35      andrew    113:             }
                    114:             else {
                    115:                 $discount_time = $hours->{$type};
                    116:                 $hours->{$type} = 0;
                    117:             }
                    118:
                    119:             if ($discount_time) {
                    120:                 $cust->{invoice}->{discount}->{amount}
                    121:                     += round( $discount_time * $fee->{rate} );
1.36      andrew    122:                 $cust->{invoice}->{discount}->{hours}{$type}
                    123:                     += $discount_time;
1.35      andrew    124:
                    125:                 $type = '' if $type eq 'default';
1.38      andrew    126:                 $count -= $discount_time;
1.35      andrew    127:                 $fee->{detail} .= " $discount_time $type Hours Discounted";
                    128:             }
1.1       andrew    129:         }
                    130:     }
                    131:
1.25      andrew    132:     push @{ $cust->{invoice}->{projects} }, $project;
1.1       andrew    133: }
                    134:
1.44      andrew    135:
                    136: if ( my $unpaid_invoices = $state->unpaid_invoices() ) {
                    137:     foreach my $custid ( keys %{$unpaid_invoices} ) {
1.46    ! andrew    138:         my %project  = ( title => 'Unpaid Invoices', fees => [], );
1.44      andrew    139:         my $past_due = 0;
1.46    ! andrew    140:         my $unpaid   = 0;
1.44      andrew    141:
                    142:         my $cust;
                    143:         foreach ( @{$customers} ) {
                    144:             if ( $_->{id} eq $custid ) {
                    145:                 $cust = $_;
                    146:                 last;
                    147:             }
                    148:         }
                    149:         $cust ||= fake_customer($custid);
                    150:
1.46    ! andrew    151:         foreach my $id (
        !           152:             sort { $a <=> $b }
        !           153:             keys %{ $unpaid_invoices->{$custid} }
        !           154:             )
1.44      andrew    155:         {
                    156:             my $unpaid  = $state->get_invoice($id);
                    157:             my $invdate = ymd_to_DateTime( $unpaid->{invdate} );
                    158:
1.46    ! andrew    159:             my $content
        !           160:                 = sprintf( "Invoice %06d from %s", $id, $invdate->ymd );
        !           161:             if ( $cust->{duedate}
        !           162:                 && DateTime->compare( $invdate, $cust->{duedate} ) > 0 )
        !           163:             {
        !           164:                 $content = "PAST DUE: $content";
        !           165:                 $past_due += $unpaid_invoices->{$custid}->{$id};
        !           166:             }
        !           167:             else {
        !           168:                 $unpaid += $unpaid_invoices->{$custid}->{$id};
        !           169:             }
1.44      andrew    170:
                    171:             push @{ $project{fees} },
                    172:                 {
1.46    ! andrew    173:                 id       => $id,
        !           174:                 contents => $content,
        !           175:                 count    => 1,
        !           176:                 rate     => $unpaid_invoices->{$custid}->{$id},
1.44      andrew    177:                 };
                    178:         }
                    179:
                    180:         if ($past_due) {
                    181:             $cust->{invoice} ||= make_invoice();
                    182:
                    183:             $cust->{invoice}->{past_due} = $past_due;
1.46    ! andrew    184:             $cust->{invoice}->{unpaid}   = $unpaid;
1.44      andrew    185:             $cust->{invoice}->{total_due}
1.46    ! andrew    186:                 = $cust->{invoice}->{total} + $past_due + $unpaid;
1.44      andrew    187:
                    188:             unshift @{ $cust->{invoice}->{projects} }, \%project;
                    189:         }
                    190:     }
                    191: }
                    192:
1.25      andrew    193: foreach my $cust ( @{$customers} ) {
1.6       andrew    194:     my $invoice = $cust->{invoice};
1.25      andrew    195:     next unless $invoice && $invoice->{projects} && @{ $invoice->{projects} };
1.1       andrew    196:
1.43      andrew    197:     $invoice->{custid}       = $cust->{id};
1.40      andrew    198:     $invoice->{transactions} = [];
1.7       andrew    199:
1.33      andrew    200:     my %transactions;
1.1       andrew    201:     foreach my $project ( @{ $invoice->{projects} } ) {
1.6       andrew    202:         if ( $project->{transactions} ) {
1.33      andrew    203:             %transactions = ( %transactions, %{ $project->{transactions} } );
1.6       andrew    204:         }
1.1       andrew    205:         my $subtotal = 0;
                    206:         foreach my $fee ( @{ $project->{fees} } ) {
                    207:             my $amount = round( $fee->{count} * $fee->{rate} );
                    208:             $subtotal += $amount;
                    209:         }
                    210:         foreach my $expense ( @{ $project->{expenses} } ) {
                    211:             $subtotal += round( $expense->{amount} );
                    212:         }
                    213:         $project->{total} = $subtotal;
                    214:         $invoice->{total} += $subtotal;
                    215:     }
1.40      andrew    216:     @{ $invoice->{transactions} } = sort { $a <=> $b } keys %transactions;
1.1       andrew    217:
                    218:     if ( $invoice->{discount} ) {
                    219:         my $c = "Included Hours\n";
                    220:         if ( $invoice->{discount}{hours} ) {
                    221:             foreach my $t ( keys %{ $invoice->{discount}{hours} } ) {
1.35      andrew    222:                 my $type = $t eq 'default' ? '' : $t;
                    223:                 $c .= "\n$invoice->{discount}{hours}{$t} $type hour";
1.1       andrew    224:                 $c .= 's' if $invoice->{discount}{hours}{$t} != 1;
                    225:                 $c .= "\n";
                    226:             }
                    227:         }
                    228:         $invoice->{discount}{contents} = $c;
                    229:         $invoice->{total} -= round( $invoice->{discount}{amount} );
                    230:     }
                    231:
1.9       andrew    232:     next unless $invoice->{total} > 0 || $invoice->{total_due};
                    233:
1.6       andrew    234:     $invoice->{info} = $config->get('info');
1.19      andrew    235:     my $from = $config->get('from');
                    236:     $from = get_user($from) if !ref $from;
                    237:
1.40      andrew    238:     $invoice->{id} = $state->next_invoice_id;
                    239:     $invoice->{file} = sprintf 'invoice_%06d.pdf', $invoice->{id};
                    240:
1.19      andrew    241:     $invoice->{organization} = $from->{organization} || $from->{name};
1.29      andrew    242:     $invoice->{from} = make_address($from);
1.40      andrew    243:     $invoice->{to}   = make_address( $cust->{address} || $cust->{id} );
                    244:     $invoice->{logo} = $config->get('logo');
1.6       andrew    245:
1.43      andrew    246:     $state->add_invoice($invoice);
1.10      andrew    247:
1.18      andrew    248:     my $invoice_dir = $config->get('invoice_dir');
                    249:     File::Path::make_path($invoice_dir);
                    250:     my $file = join '/', $invoice_dir, $invoice->{file};
                    251:
1.21      andrew    252:     my $tt = Template->new( INCLUDE_PATH => $config->get('template_dir'), )
                    253:         || die $Template::ERROR, "\n";
1.20      andrew    254:
                    255:     $tt->process( $config->get('invoice_template'), $invoice, $file )
1.1       andrew    256:         or die $tt->error . "\n";
                    257:
1.25      andrew    258:     printf "Generated %s for %s: \$%.02f\n", $invoice->{file}, $cust->{id},
1.9       andrew    259:         $invoice->{total};
1.40      andrew    260:
1.1       andrew    261: }
                    262:
1.6       andrew    263: $state->save;
1.1       andrew    264:
1.6       andrew    265: sub find_customer_for_ticket {
1.43      andrew    266:     my ( $ticket, $customers ) = @_;
1.4       andrew    267:
1.25      andrew    268:     foreach my $cust ( @{$customers} ) {
1.22      andrew    269:         next unless $cust->{match};
1.6       andrew    270:         foreach my $m ( @{ $cust->{match} } ) {
1.4       andrew    271:             my $type = $m->{type};
1.29      andrew    272:             my $match
                    273:                 = exists $m->{$type}
                    274:                 ? lc( $m->{$type} )
                    275:                 : qr/\Q$m->{regex}\E/;
                    276:             my $thing = [ map {lc} $ticket->$type ];
1.4       andrew    277:
1.29      andrew    278:             if ( !$match ) {
1.4       andrew    279:                 warn "Invalid match!";
1.22      andrew    280:                 next;
1.4       andrew    281:             }
1.29      andrew    282:             return $cust if ( $match ~~ $thing );
1.4       andrew    283:         }
1.6       andrew    284:     }
                    285:
1.44      andrew    286:     return fake_customer($ticket->requestors);
                    287: }
                    288:
                    289: sub fake_customer {
                    290:     my ($custid) = @_;
                    291:     return unless $custid;
                    292:
1.40      andrew    293:     my $cust = $config->new_customer;
1.25      andrew    294:     push @{$customers}, $cust;
1.8       andrew    295:
1.44      andrew    296:     $cust->{id} = $custid;
1.14      andrew    297:     $cust->{match} = [
                    298:         {   type  => 'requestors',
1.16      andrew    299:             regex => $cust->{id},
1.14      andrew    300:         }
                    301:     ];
1.13      andrew    302:
1.40      andrew    303:     set_cust_dates($cust);
1.8       andrew    304:     return $cust;
                    305: }
                    306:
1.9       andrew    307: sub get_user {
1.8       andrew    308:     my ($id) = @_;
                    309:
1.9       andrew    310:     state %users;
                    311:     return $users{$id} if $users{$id};
1.8       andrew    312:
                    313:     my %map = (
                    314:         address_one   => 'addr1',
                    315:         address_two   => 'addr2',
                    316:         email_address => 'email',
1.9       andrew    317:         real_name     => 'name',
                    318:         name          => 'username',
1.8       andrew    319:     );
                    320:
1.12      andrew    321:     my $users = RT::Client::REST::User->new( rt => $rt, id => $id );
1.8       andrew    322:     $users->retrieve;
                    323:
1.9       andrew    324:     my %user;
1.8       andrew    325:     foreach my $m ( keys %{ $users->_attributes } ) {
                    326:         next unless $users->can($m);
                    327:
                    328:         my $v = $users->$m;
                    329:         next unless $v;
                    330:
                    331:         $m = $map{$m} if exists $map{$m};
                    332:
1.9       andrew    333:         $user{$m} = $v;
1.8       andrew    334:     }
1.6       andrew    335:
1.9       andrew    336:     $users{$id} = \%user;
                    337:     return \%user;
1.13      andrew    338: }
                    339:
                    340: sub make_invoice {
1.14      andrew    341:     my ($cust) = @_;
                    342:
1.43      andrew    343:     my %invoice
                    344:         = ( end => $cust->{billend}->clone->subtract( seconds => 1 ) );
                    345:     $invoice{start} = $cust->{startinvoicedate}->clone
1.40      andrew    346:         if $cust->{startinvoicedate};
1.16      andrew    347:
                    348:     if ( $cust->{base_rate} ) {
1.43      andrew    349:         my ( $project, $hours ) = make_base_project($cust);
1.16      andrew    350:
                    351:         if ( @{ $project->{fees} } ) {
                    352:             $invoice{end}   = $project->{end};
                    353:             $invoice{hours} = $hours;
                    354:             push @{ $invoice{projects} }, $project;
                    355:         }
                    356:     }
                    357:     elsif ( $cust->{hours} ) {
1.14      andrew    358:         $invoice{hours} = [
1.16      andrew    359:             {   end   => $invoice{end}->clone,
1.14      andrew    360:                 hours => $cust->{hours},
                    361:             }
                    362:         ];
                    363:     }
1.13      andrew    364:
                    365:     return \%invoice;
1.12      andrew    366: }
                    367:
1.16      andrew    368: sub make_base_project {
1.43      andrew    369:     my ($cust) = @_;
1.16      andrew    370:
1.40      andrew    371:     my $date    = $cust->{billstart}->clone;
                    372:     my $billend = $cust->{billend}->clone;
1.43      andrew    373:     my ($freq)  = get_billing_frequency($cust);
1.16      andrew    374:
                    375:     my $title
1.40      andrew    376:         = $cust->{frequency} == 1
1.16      andrew    377:         ? ucfirst( $cust->{per} . 'ly' )
                    378:         : $freq . ' ' . ucfirst( $cust->{per} );
                    379:     $title .= ' Retainer';
                    380:
                    381:     my %project = ( title => $title, start => $date->clone, fees => [], );
                    382:     my @hours;
                    383:
1.28      andrew    384:     while ( $date < $billend ) {
1.16      andrew    385:         my $start = $date->clone;
                    386:
1.43      andrew    387:         $date->add($freq);
1.16      andrew    388:
1.40      andrew    389:         my $end = $date > $billend ? $billend->clone : $date->clone;
                    390:         $end->subtract( seconds => 1 );
1.16      andrew    391:
                    392:         $project{end} = $end->clone;
                    393:
                    394:         push @{ $project{fees} },
                    395:             {
                    396:             count    => 1,
                    397:             rate     => $cust->{base_rate},
                    398:             contents => $start->ymd . ' to ' . $end->ymd,
                    399:             };
                    400:
                    401:         push @hours,
                    402:             {
                    403:             start => $start->clone,
                    404:             end   => $end->clone,
                    405:             hours => { %{ $cust->{hours} } },
                    406:             };
                    407:     }
                    408:
                    409:     return \%project, \@hours;
                    410: }
                    411:
1.12      andrew    412: sub make_address {
                    413:     my ($addr) = @_;
                    414:     my @adr;
1.16      andrew    415:
                    416:     $addr = get_user($addr) unless ref $addr;
1.12      andrew    417:
                    418:     if ( $addr->{organization} ) {
                    419:         push @adr, $addr->{organization};
                    420:     }
                    421:     elsif ( $addr->{name} && !$addr->{attn} ) {
                    422:         push @adr, $addr->{name};
                    423:     }
                    424:
                    425:     if (   ( $addr->{addr1} || $addr->{addr2} )
                    426:         && $addr->{city}
                    427:         && $addr->{state}
                    428:         && $addr->{zip} )
                    429:     {
                    430:         push @adr, $addr->{attn}  if $addr->{attn};
                    431:         push @adr, $addr->{addr1} if $addr->{addr1};
                    432:         push @adr, $addr->{addr2} if $addr->{addr2};
                    433:         push @adr,
                    434:             $addr->{city} . ', ' . $addr->{state} . '  ' . $addr->{zip};
                    435:     }
                    436:     else {
                    437:         push @adr, $addr->{email} if $addr->{email};
                    438:     }
                    439:
                    440:     return join "\n\n", @adr;
1.6       andrew    441: }
                    442:
                    443: sub make_project {
1.7       andrew    444:     my ( $ticket, $cust ) = @_;
1.6       andrew    445:
                    446:     my %project = (
                    447:         id     => $ticket->id,
                    448:         queue  => $ticket->queue,
                    449:         owner  => $ticket->owner,
                    450:         title  => $ticket->subject,
                    451:         detail => 'Ticket: '
                    452:             . $ticket->id
1.17      andrew    453:             . ' Status: '
                    454:             . $ticket->status
1.6       andrew    455:             . ' Requestors: '
                    456:             . join( ', ', $ticket->requestors ),
                    457:         fees     => [],
                    458:         expenses => [],
                    459:     );
                    460:
                    461:     my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
                    462:     my $txn_i = $txns->get_iterator;
                    463:     while ( my $txn = $txn_i->() ) {
1.33      andrew    464:         next if $state->txn_is_invoiced( $txn->id );
                    465:
1.36      andrew    466:         if ( my $expense = make_expense( $txn, $ticket ) ) {
1.33      andrew    467:             push @{ $project{expenses} }, $expense;
                    468:             $project{transactions}{ $txn->id } = 1;
                    469:         }
                    470:
1.6       andrew    471:         next unless $txn->time_taken;
                    472:
1.7       andrew    473:         my $fee = make_fee( $txn, $cust->{rates}, $ticket );
                    474:
1.6       andrew    475:         if ( !( $fee->{rate} && $fee->{count} ) ) {
                    476:             warn "Invalid Fee, no rate or count";
                    477:             next;
                    478:         }
                    479:
1.7       andrew    480:         my $invoice = $cust->{invoice};
1.29      andrew    481:         if ( $invoice->{start} && $invoice->{start} > $fee->{date} ) {
                    482:             warn "Ticket "
                    483:                 . $ticket->id
                    484:                 . " has uninvoiced Transaction "
                    485:                 . $txn->id . "\n";
1.27      andrew    486:             next;
                    487:         }
1.6       andrew    488:         next if $invoice->{end} < $fee->{date};
                    489:
1.36      andrew    490:         push @{ $project{fees} }, $fee;
1.33      andrew    491:         $project{transactions}{ $txn->id } = 1;
1.4       andrew    492:     }
1.6       andrew    493:
                    494:     return \%project;
1.4       andrew    495: }
                    496:
                    497: sub make_fee {
1.7       andrew    498:     my ( $txn, $rates, $ticket ) = @_;
                    499:
                    500:     # XXX Only need $ticket for the alternate subject
1.4       andrew    501:
                    502:     my $work_time = sprintf "%.03f", $txn->time_taken / 60;
                    503:     my $work_type = $txn->cf('WorkType');
1.34      andrew    504:
                    505:     if ( $work_type =~ s/\s*Onsite//i ) {
1.36      andrew    506:
1.34      andrew    507:         # XXX Do something special for onsite activities
                    508:     }
                    509:
                    510:     $work_type =~ s/^\s+|\s+$//g;
                    511:     $work_type ||= 'Normal';
1.4       andrew    512:
                    513:     my %fee = (
                    514:         id       => $txn->id,
                    515:         contents => $txn->created . ' ('
                    516:             . $txn->id . ')' . "\n\n"
                    517:             . ( $txn->data || $ticket->subject ),
                    518:         count => $work_time,
                    519:         type  => $work_type,
1.6       andrew    520:         date  => ymd_to_DateTime( $txn->created ),
1.7       andrew    521:         rate  => $rates->{$work_type} || $rates->{default} || 0,
1.4       andrew    522:     );
                    523:
                    524:     if ( $work_type && $work_type ne 'Normal' ) {
                    525:         $fee{detail} = $work_type . ' rate';
                    526:     }
                    527:
                    528:     return \%fee;
1.33      andrew    529: }
                    530:
                    531: sub make_expense {
                    532:     my ( $txn, $ticket ) = @_;
                    533:
                    534:     my $amount = $txn->cf('ExpenseAmount') or return;
                    535:
                    536:     my %expense = (
                    537:         id       => $txn->id,
                    538:         contents => $txn->created . ' ('
                    539:             . $txn->id . ')' . "\n\n"
                    540:             . ( $txn->data || $ticket->subject ),
                    541:         amount => $amount,
                    542:         date   => ymd_to_DateTime( $txn->created ),
1.36      andrew    543:
1.33      andrew    544:         # detail => ???,
                    545:     );
                    546:
                    547:     return \%expense;
1.4       andrew    548: }
                    549:
                    550: sub hours_for_date {
                    551:     my ( $invoice, $date ) = @_;
                    552:
                    553:     my $hours = {};
                    554:     if ( $invoice->{hours} ) {
                    555:         foreach my $h ( @{ $invoice->{hours} } ) {
                    556:             next if $h->{start} && $h->{start} > $date;
                    557:             next if $h->{end} < $date;
                    558:
                    559:             $hours = $h->{hours};
                    560:             last;
                    561:         }
                    562:     }
                    563:     return $hours;
1.6       andrew    564: }
                    565:
1.40      andrew    566: sub get_billing_frequency {
                    567:     my ($cust) = @_;
                    568:     my $per  = $cust->{per}       || 'week';
                    569:     my $freq = $cust->{frequency} || 1;
1.1       andrew    570:
1.40      andrew    571:     my $day_method;
                    572:     given ($per) {
                    573:         when ('week')  { $per = 'weeks';  $day_method = 'dow' }
                    574:         when ('month') { $per = 'months'; $day_method = 'day' }
                    575:         default { die "Unknown per [$per]\n" }
                    576:     }
1.1       andrew    577:
1.43      andrew    578:     return DateTime::Duration->new( $per => $freq ), $day_method;
1.1       andrew    579: }
                    580:
1.40      andrew    581: sub set_dates {
                    582:     my ($customers) = @_;
1.43      andrew    583:
1.40      andrew    584:     my $newest_invoice;
                    585:     my $max_duration;
1.1       andrew    586:
1.40      andrew    587:     foreach my $cust ( @{$customers} ) {
                    588:         set_cust_dates($cust);
1.1       andrew    589:
1.40      andrew    590:         my ($freq) = get_billing_frequency($cust);
                    591:         $max_duration = $freq
                    592:             if !$max_duration
                    593:                 || DateTime::Duration->compare( $freq, $max_duration ) > 0;
1.1       andrew    594:
1.40      andrew    595:         if ( $cust->{startinvoicedate} ) {
                    596:             my $date = $cust->{startinvoicedate}->clone;
                    597:             $newest_invoice = $date->clone
                    598:                 if !$newest_invoice || $newest_invoice < $date;
1.1       andrew    599:         }
                    600:     }
                    601:
1.40      andrew    602:     return $newest_invoice->clone->subtract($max_duration)
                    603:         ->subtract( days => 1 );
1.1       andrew    604: }
                    605:
1.40      andrew    606: sub set_cust_dates {
                    607:     my ($cust) = @_;
1.18      andrew    608:
1.40      andrew    609:     my $day = $cust->{day} || 0;
                    610:     my ( $freq, $day_method ) = get_billing_frequency($cust);
1.18      andrew    611:
1.41      andrew    612:     my $end = DateTime->now( time_zone => 'local' )
1.40      andrew    613:         ->set( hour => 0, minute => 0, second => 0 );
1.18      andrew    614:
1.41      andrew    615:     my $start = $end->clone->subtract($freq);
1.1       andrew    616:
1.40      andrew    617:     # XXX This is helpful, but monthly and billday > 28 == !!!
1.43      andrew    618:     $end->subtract( days => 1 ) while $day && $end->$day_method != $day;
1.1       andrew    619:
1.40      andrew    620:     my $lastinvoice = $state->last_invoice( $cust->{id} );
                    621:     if ( $lastinvoice && $lastinvoice->{end} ) {
1.41      andrew    622:         $start = ymd_to_DateTime( $lastinvoice->{end} )->add( days => 1 );
                    623:         $cust->{startinvoicedate} = $start->clone;
1.6       andrew    624:     }
1.42      andrew    625:
                    626:     $cust->{duedate}
                    627:         = $cust->{net}
                    628:         ? DateTime->now->subtract( days => $cust->{net} )
                    629:         : 0;
1.1       andrew    630:
1.41      andrew    631:     $cust->{no_invoice} = 1 if $start->clone->add($freq) > $end;
                    632:     $cust->{billend}    = $end;
                    633:     $cust->{billstart}  = $start;
1.1       andrew    634: }

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