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

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

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

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