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

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

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

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