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

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

1.1       andrew      1: #!/usr/bin/perl
1.41    ! andrew      2: # $AFresh1: rt_invoices.pl,v 1.40 2011/12/22 04:52: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.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:     $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.41    ! andrew    323:     return if $cust->{no_invoice};
1.40      andrew    324:     return unless $cust->{billstart};
1.14      andrew    325:
1.40      andrew    326:     my %invoice = ( end => $cust->{billend}->clone->subtract( seconds => 1 ) );
                    327:     $invoice{start} = $cust->{startinvoicedate}->clone
                    328:         if $cust->{startinvoicedate};
1.16      andrew    329:
1.40      andrew    330:     return if $invoice{start} && $invoice{start} > $invoice{end};
1.16      andrew    331:
                    332:     if ( $cust->{base_rate} ) {
1.40      andrew    333:         my ( $project, $hours ) = make_base_project( $cust );
1.16      andrew    334:
                    335:         if ( @{ $project->{fees} } ) {
                    336:             $invoice{end}   = $project->{end};
                    337:             $invoice{hours} = $hours;
                    338:             push @{ $invoice{projects} }, $project;
                    339:         }
                    340:     }
                    341:     elsif ( $cust->{hours} ) {
1.14      andrew    342:         $invoice{hours} = [
1.16      andrew    343:             {   end   => $invoice{end}->clone,
1.14      andrew    344:                 hours => $cust->{hours},
                    345:             }
                    346:         ];
                    347:     }
1.13      andrew    348:
                    349:     return \%invoice;
1.12      andrew    350: }
                    351:
1.16      andrew    352: sub make_base_project {
1.40      andrew    353:     my ( $cust ) = @_;
1.16      andrew    354:
1.40      andrew    355:     my $date    = $cust->{billstart}->clone;
                    356:     my $billend = $cust->{billend}->clone;
                    357:     my ($freq) = get_billing_frequency($cust);
1.16      andrew    358:
                    359:     my $title
1.40      andrew    360:         = $cust->{frequency} == 1
1.16      andrew    361:         ? ucfirst( $cust->{per} . 'ly' )
                    362:         : $freq . ' ' . ucfirst( $cust->{per} );
                    363:     $title .= ' Retainer';
                    364:
                    365:     my %project = ( title => $title, start => $date->clone, fees => [], );
                    366:     my @hours;
                    367:
1.28      andrew    368:     while ( $date < $billend ) {
1.16      andrew    369:         my $start = $date->clone;
                    370:
1.40      andrew    371:         $date->add( $freq );
1.16      andrew    372:
1.40      andrew    373:         my $end = $date > $billend ? $billend->clone : $date->clone;
                    374:         $end->subtract( seconds => 1 );
1.16      andrew    375:
                    376:         $project{end} = $end->clone;
                    377:
                    378:         push @{ $project{fees} },
                    379:             {
                    380:             count    => 1,
                    381:             rate     => $cust->{base_rate},
                    382:             contents => $start->ymd . ' to ' . $end->ymd,
                    383:             };
                    384:
                    385:         push @hours,
                    386:             {
                    387:             start => $start->clone,
                    388:             end   => $end->clone,
                    389:             hours => { %{ $cust->{hours} } },
                    390:             };
                    391:     }
                    392:
                    393:     return \%project, \@hours;
                    394: }
                    395:
1.12      andrew    396: sub make_address {
                    397:     my ($addr) = @_;
                    398:     my @adr;
1.16      andrew    399:
                    400:     $addr = get_user($addr) unless ref $addr;
1.12      andrew    401:
                    402:     if ( $addr->{organization} ) {
                    403:         push @adr, $addr->{organization};
                    404:     }
                    405:     elsif ( $addr->{name} && !$addr->{attn} ) {
                    406:         push @adr, $addr->{name};
                    407:     }
                    408:
                    409:     if (   ( $addr->{addr1} || $addr->{addr2} )
                    410:         && $addr->{city}
                    411:         && $addr->{state}
                    412:         && $addr->{zip} )
                    413:     {
                    414:         push @adr, $addr->{attn}  if $addr->{attn};
                    415:         push @adr, $addr->{addr1} if $addr->{addr1};
                    416:         push @adr, $addr->{addr2} if $addr->{addr2};
                    417:         push @adr,
                    418:             $addr->{city} . ', ' . $addr->{state} . '  ' . $addr->{zip};
                    419:     }
                    420:     else {
                    421:         push @adr, $addr->{email} if $addr->{email};
                    422:     }
                    423:
                    424:     return join "\n\n", @adr;
1.6       andrew    425: }
                    426:
                    427: sub make_project {
1.7       andrew    428:     my ( $ticket, $cust ) = @_;
1.6       andrew    429:
                    430:     my %project = (
                    431:         id     => $ticket->id,
                    432:         queue  => $ticket->queue,
                    433:         owner  => $ticket->owner,
                    434:         title  => $ticket->subject,
                    435:         detail => 'Ticket: '
                    436:             . $ticket->id
1.17      andrew    437:             . ' Status: '
                    438:             . $ticket->status
1.6       andrew    439:             . ' Requestors: '
                    440:             . join( ', ', $ticket->requestors ),
                    441:         fees     => [],
                    442:         expenses => [],
                    443:     );
                    444:
                    445:     my $txns = $ticket->transactions( type => [qw(Comment Correspond)] );
                    446:     my $txn_i = $txns->get_iterator;
                    447:     while ( my $txn = $txn_i->() ) {
1.33      andrew    448:         next if $state->txn_is_invoiced( $txn->id );
                    449:
1.36      andrew    450:         if ( my $expense = make_expense( $txn, $ticket ) ) {
1.33      andrew    451:             push @{ $project{expenses} }, $expense;
                    452:             $project{transactions}{ $txn->id } = 1;
                    453:         }
                    454:
1.6       andrew    455:         next unless $txn->time_taken;
                    456:
1.7       andrew    457:         my $fee = make_fee( $txn, $cust->{rates}, $ticket );
                    458:
1.6       andrew    459:         if ( !( $fee->{rate} && $fee->{count} ) ) {
                    460:             warn "Invalid Fee, no rate or count";
                    461:             next;
                    462:         }
                    463:
1.7       andrew    464:         my $invoice = $cust->{invoice};
1.29      andrew    465:         if ( $invoice->{start} && $invoice->{start} > $fee->{date} ) {
                    466:             warn "Ticket "
                    467:                 . $ticket->id
                    468:                 . " has uninvoiced Transaction "
                    469:                 . $txn->id . "\n";
1.27      andrew    470:             next;
                    471:         }
1.6       andrew    472:         next if $invoice->{end} < $fee->{date};
                    473:
1.36      andrew    474:         push @{ $project{fees} }, $fee;
1.33      andrew    475:         $project{transactions}{ $txn->id } = 1;
1.4       andrew    476:     }
1.6       andrew    477:
                    478:     return \%project;
1.4       andrew    479: }
                    480:
                    481: sub make_fee {
1.7       andrew    482:     my ( $txn, $rates, $ticket ) = @_;
                    483:
                    484:     # XXX Only need $ticket for the alternate subject
1.4       andrew    485:
                    486:     my $work_time = sprintf "%.03f", $txn->time_taken / 60;
                    487:     my $work_type = $txn->cf('WorkType');
1.34      andrew    488:
                    489:     if ( $work_type =~ s/\s*Onsite//i ) {
1.36      andrew    490:
1.34      andrew    491:         # XXX Do something special for onsite activities
                    492:     }
                    493:
                    494:     $work_type =~ s/^\s+|\s+$//g;
                    495:     $work_type ||= 'Normal';
1.4       andrew    496:
                    497:     my %fee = (
                    498:         id       => $txn->id,
                    499:         contents => $txn->created . ' ('
                    500:             . $txn->id . ')' . "\n\n"
                    501:             . ( $txn->data || $ticket->subject ),
                    502:         count => $work_time,
                    503:         type  => $work_type,
1.6       andrew    504:         date  => ymd_to_DateTime( $txn->created ),
1.7       andrew    505:         rate  => $rates->{$work_type} || $rates->{default} || 0,
1.4       andrew    506:     );
                    507:
                    508:     if ( $work_type && $work_type ne 'Normal' ) {
                    509:         $fee{detail} = $work_type . ' rate';
                    510:     }
                    511:
                    512:     return \%fee;
1.33      andrew    513: }
                    514:
                    515: sub make_expense {
                    516:     my ( $txn, $ticket ) = @_;
                    517:
                    518:     my $amount = $txn->cf('ExpenseAmount') or return;
                    519:
                    520:     my %expense = (
                    521:         id       => $txn->id,
                    522:         contents => $txn->created . ' ('
                    523:             . $txn->id . ')' . "\n\n"
                    524:             . ( $txn->data || $ticket->subject ),
                    525:         amount => $amount,
                    526:         date   => ymd_to_DateTime( $txn->created ),
1.36      andrew    527:
1.33      andrew    528:         # detail => ???,
                    529:     );
                    530:
                    531:     return \%expense;
1.4       andrew    532: }
                    533:
                    534: sub hours_for_date {
                    535:     my ( $invoice, $date ) = @_;
                    536:
                    537:     my $hours = {};
                    538:     if ( $invoice->{hours} ) {
                    539:         foreach my $h ( @{ $invoice->{hours} } ) {
                    540:             next if $h->{start} && $h->{start} > $date;
                    541:             next if $h->{end} < $date;
                    542:
                    543:             $hours = $h->{hours};
                    544:             last;
                    545:         }
                    546:     }
                    547:     return $hours;
1.1       andrew    548: }
                    549:
1.6       andrew    550: sub ymd_to_DateTime {
                    551:     my ($ymd) = @_;
1.10      andrew    552:     my ( $date, $time ) = split /[\sT]/, $ymd;
1.6       andrew    553:     my ( $year, $month, $day ) = split '-', $date;
                    554:     my ( $hour, $minute, $second ) = split ':', $time if $time;
                    555:
                    556:     return DateTime->new(
1.28      andrew    557:         year      => $year,
                    558:         month     => $month,
                    559:         day       => $day,
                    560:         hour      => $hour || 0,
                    561:         minute    => $minute || 0,
                    562:         second    => $second || 0,
                    563:         time_zone => 'local',
1.6       andrew    564:     );
                    565: }
                    566:
1.40      andrew    567: sub get_billing_frequency {
                    568:     my ($cust) = @_;
                    569:     my $per  = $cust->{per}       || 'week';
                    570:     my $freq = $cust->{frequency} || 1;
1.1       andrew    571:
1.40      andrew    572:     my $day_method;
                    573:     given ($per) {
                    574:         when ('week')  { $per = 'weeks';  $day_method = 'dow' }
                    575:         when ('month') { $per = 'months'; $day_method = 'day' }
                    576:         default { die "Unknown per [$per]\n" }
                    577:     }
1.1       andrew    578:
1.40      andrew    579:     return DateTime::Duration->new($per => $freq), $day_method;
1.1       andrew    580: }
                    581:
1.40      andrew    582: sub set_dates {
                    583:     my ($customers) = @_;
                    584:
                    585:     my $newest_invoice;
                    586:     my $max_duration;
1.1       andrew    587:
1.40      andrew    588:     foreach my $cust ( @{$customers} ) {
                    589:         set_cust_dates($cust);
1.1       andrew    590:
1.40      andrew    591:         my ($freq) = get_billing_frequency($cust);
                    592:         $max_duration = $freq
                    593:             if !$max_duration
                    594:                 || DateTime::Duration->compare( $freq, $max_duration ) > 0;
1.1       andrew    595:
1.40      andrew    596:         if ( $cust->{startinvoicedate} ) {
                    597:             my $date = $cust->{startinvoicedate}->clone;
                    598:             $newest_invoice = $date->clone
                    599:                 if !$newest_invoice || $newest_invoice < $date;
1.1       andrew    600:         }
                    601:     }
                    602:
1.40      andrew    603:     return $newest_invoice->clone->subtract($max_duration)
                    604:         ->subtract( days => 1 );
1.1       andrew    605: }
                    606:
1.40      andrew    607: sub set_cust_dates {
                    608:     my ($cust) = @_;
1.18      andrew    609:
1.40      andrew    610:     my $day = $cust->{day} || 0;
                    611:     my ( $freq, $day_method ) = get_billing_frequency($cust);
1.18      andrew    612:
1.41    ! andrew    613:     my $end = DateTime->now( time_zone => 'local' )
1.40      andrew    614:         ->set( hour => 0, minute => 0, second => 0 );
1.18      andrew    615:
1.41    ! andrew    616:     my $start = $end->clone->subtract($freq);
1.1       andrew    617:
1.40      andrew    618:     # XXX This is helpful, but monthly and billday > 28 == !!!
1.41    ! andrew    619:     $end->subtract( days => 1 )
        !           620:         while $day && $end->$day_method != $day;
1.1       andrew    621:
1.40      andrew    622:     my $lastinvoice = $state->last_invoice( $cust->{id} );
                    623:     if ( $lastinvoice && $lastinvoice->{end} ) {
1.41    ! andrew    624:         $start = ymd_to_DateTime( $lastinvoice->{end} )->add( days => 1 );
        !           625:         $cust->{startinvoicedate} = $start->clone;
1.6       andrew    626:     }
1.1       andrew    627:
1.41    ! andrew    628:     $cust->{no_invoice} = 1 if $start->clone->add($freq) > $end;
        !           629:     $cust->{billend}    = $end;
        !           630:     $cust->{billstart}  = $start;
1.1       andrew    631: }

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