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

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

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

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