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

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

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

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