c40fcb8fe97daed30e3f4090cce231f1b93afc83
[freeside.git] / FS / FS / detail_format / sum_count.pm
1 package FS::detail_format::sum_count;
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 { 'Number of calls, one line per service' };
13
14 sub header_detail {
15   my $self = shift;
16   if ( $self->{inbound} ) {
17     'Destination,Messages,Price'
18   }
19   else {
20     'Source,Messages,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->{amount} += $object->rated_price
35       if $object->freesidestatus ne 'no-charge';
36   }
37 }
38
39 sub finish {
40   my $self = shift;
41   my $svcnums = $self->{svcnums};
42   my $buffer = $self->{buffer};
43   foreach my $svcnum (keys %$svcnums) {
44
45     my $subtotal = $svcnums->{$svcnum};
46     next if $subtotal->{amount} < 0.01;
47
48     my $cust_svc = qsearchs('cust_svc', { svcnum => $svcnum })
49       or die "svcnum #$svcnum not found";
50     my $phonenum = $cust_svc->svc_x->label;
51     warn "processing $phonenum\n" if $DEBUG;
52
53     $self->csv->combine(
54       $phonenum,
55       $subtotal->{count},
56       $self->money_char . sprintf('%.02f',$subtotal->{amount}),
57     );
58
59     warn "adding detail: ".$self->csv->string."\n" if $DEBUG;
60
61     push @$buffer, FS::cust_bill_pkg_detail->new({
62         amount      => $subtotal->{amount},
63         format      => 'C',
64         classnum    => '', #ignored in this format
65         duration    => '',
66         phonenum    => $phonenum,
67         accountcode => '', #ignored in this format
68         startdate   => '', #could use the earliest startdate in the bunch?
69         regionname  => '', #no, we're using prefix instead
70         detail      => $self->csv->string,
71     });
72   } #foreach $svcnum
73
74   # supposedly the compiler is smart enough to do this in place
75   @$buffer = sort { $a->{Hash}->{phonenum} cmp $b->{Hash}->{phonenum} } 
76               @$buffer;
77 }
78
79 1;