tax engine refactoring for Avalara and Billsoft tax vendors, #25718
[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   my $acctids = $self->{acctids} ||= [];
28   foreach my $cdr (@_) {
29     my $object = $self->{inbound} ? $cdr->cdr_termination(1) : $cdr;
30     my $svcnum = $object->svcnum; # yes, $object->svcnum.
31
32     my $subtotal = ($svcnums->{$svcnum} ||=
33       { count => 0, duration => 0, amount => 0 });
34     $subtotal->{count}++;
35     $subtotal->{amount} += $object->rated_price
36       if $object->freesidestatus ne 'no-charge';
37
38     push @$acctids, $cdr->acctid;
39   }
40 }
41
42 sub finish {
43   my $self = shift;
44   my $svcnums = $self->{svcnums};
45   my $buffer = $self->{buffer};
46   foreach my $svcnum (keys %$svcnums) {
47
48     my $subtotal = $svcnums->{$svcnum};
49     next if $subtotal->{amount} < 0.01;
50
51     my $cust_svc = qsearchs('cust_svc', { svcnum => $svcnum })
52       or die "svcnum #$svcnum not found";
53     my $phonenum = $cust_svc->svc_x->label;
54     warn "processing $phonenum\n" if $DEBUG;
55
56     $self->csv->combine(
57       $phonenum,
58       $subtotal->{count},
59       $self->money_char . sprintf('%.02f',$subtotal->{amount}),
60     );
61
62     warn "adding detail: ".$self->csv->string."\n" if $DEBUG;
63
64     push @$buffer, FS::cust_bill_pkg_detail->new({
65         amount      => $subtotal->{amount},
66         format      => 'C',
67         classnum    => '', #ignored in this format
68         duration    => '',
69         phonenum    => $phonenum,
70         accountcode => '', #ignored in this format
71         startdate   => '', #could use the earliest startdate in the bunch?
72         regionname  => '', #no, we're using prefix instead
73         detail      => $self->csv->string,
74         acctid      => $self->{acctids},
75     });
76   } #foreach $svcnum
77
78   # supposedly the compiler is smart enough to do this in place
79   @$buffer = sort { $a->{Hash}->{phonenum} cmp $b->{Hash}->{phonenum} } 
80               @$buffer;
81 }
82
83 1;