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

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

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

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