detail format refactor, #15535
[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 parent 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   }
36 }
37
38 sub finish {
39   my $self = shift;
40   my $svcnums = $self->{svcnums};
41   my $buffer = $self->{buffer};
42   foreach my $svcnum (keys %$svcnums) {
43
44     my $cust_svc = qsearchs('cust_svc', { svcnum => $svcnum })
45       or die "svcnum #$svcnum not found";
46     my $phonenum = $cust_svc->svc_x->label;
47     warn "processing $phonenum\n" if $DEBUG;
48
49     my $subtotal = $svcnums->{$svcnum};
50
51     $self->csv->combine(
52       $phonenum,
53       $subtotal->{count},
54       $self->money_char . sprintf('%.02f',$subtotal->{amount}),
55     );
56
57     warn "adding detail: ".$self->csv->string."\n" if $DEBUG;
58
59     push @$buffer, FS::cust_bill_pkg_detail->new({
60         amount      => $subtotal->{amount},
61         format      => 'C',
62         classnum    => '', #ignored in this format
63         duration    => '',
64         phonenum    => $phonenum,
65         accountcode => '', #ignored in this format
66         startdate   => '', #could use the earliest startdate in the bunch?
67         regionname  => '', #no, we're using prefix instead
68         detail      => $self->csv->string,
69     });
70   } #foreach $svcnum
71
72   # supposedly the compiler is smart enough to do this in place
73   @$buffer = sort { $a->{Hash}->{phonenum} cmp $b->{Hash}->{phonenum} } 
74               @$buffer;
75 }
76
77 1;