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

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

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

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