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

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

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

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