1b967b407d35b7e29a6f95698717dca0a6fc2dd2
[freeside.git] / FS / FS / detail_format / sum_duration.pm
1 package FS::detail_format::sum_duration;
2
3 use strict;
4 use vars qw( $DEBUG );
5 use base qw(FS::detail_format);
6 use FS::Record qw(qsearchs);
7 use FS::cust_svc;
8 use FS::svc_Common; # for label
9
10 $DEBUG = 0;
11
12 sub name { 'Summary, one line per service' };
13
14 sub header_detail {
15   my $self = shift;
16   if ( $self->{inbound} ) {
17     'Destination,Calls,Duration,Price'
18   }
19   else {
20     'Source,Calls,Duration,Price'
21   }
22 }
23
24 sub append {
25   my $self = shift;
26   my $svcnums = ($self->{svcnums} ||= {});
27   foreach my $cdr (@_) {
28     my $object = $self->{inbound} ? $cdr->cdr_termination(1) : $cdr;
29     my $svcnum = $object->svcnum; # yes, $object->svcnum.
30
31     my $subtotal = ($svcnums->{$svcnum} ||=
32       { count => 0, duration => 0, amount => 0 });
33     $subtotal->{count}++;
34     $subtotal->{duration} += $object->rated_seconds;
35     $subtotal->{amount} += $object->rated_price
36       if $object->freesidestatus ne 'no-charge';
37   }
38 }
39
40 sub finish {
41   my $self = shift;
42   my $svcnums = $self->{svcnums};
43   my $buffer = $self->{buffer};
44   foreach my $svcnum (keys %$svcnums) {
45
46     my $subtotal = $svcnums->{$svcnum};
47     next if $subtotal->{amount} < 0.01;
48
49     my $cust_svc = qsearchs('cust_svc', { svcnum => $svcnum })
50       or die "svcnum #$svcnum not found";
51     my $phonenum = $cust_svc->svc_x->label;
52     warn "processing $phonenum\n" if $DEBUG;
53
54     $self->csv->combine(
55       $phonenum,
56       $subtotal->{count},
57       int($subtotal->{duration}/60) . ' min',
58       $self->money_char . sprintf('%.02f',$subtotal->{amount}),
59     );
60
61     warn "adding detail: ".$self->csv->string."\n" if $DEBUG;
62
63     push @$buffer, FS::cust_bill_pkg_detail->new({
64         amount      => $subtotal->{amount},
65         format      => 'C',
66         classnum    => '', #ignored in this format
67         duration    => $subtotal->{duration},
68         phonenum    => $phonenum,
69         accountcode => '', #ignored in this format
70         startdate   => '', #could use the earliest startdate in the bunch?
71         regionname  => '', #no, we're using prefix instead
72         detail      => $self->csv->string,
73     });
74   } #foreach $svcnum
75
76   # supposedly the compiler is smart enough to do this in place
77   @$buffer = sort { $a->{Hash}->{phonenum} cmp $b->{Hash}->{phonenum} } 
78               @$buffer;
79 }
80
81 1;