Wholesale CDR cost re-billing, RT#27555
[freeside.git] / FS / FS / part_pkg / agent_cdr.pm
1 package FS::part_pkg::agent_cdr;
2 use base qw( FS::part_pkg::recur_Common );
3
4 #kind of glommed together from cdr_termination, agent, voip_cdr
5 # some false laziness w/ all of them
6
7 use strict;
8 use vars qw( $DEBUG $me %info );
9 use FS::Record qw( qsearch );
10 use FS::PagedSearch qw( psearch );
11 use FS::agent;
12 use FS::cust_main;
13 use FS::cdr;
14
15 $DEBUG = 0;
16
17 $me = '[FS::part_pkg::agent_cdr]';
18
19 tie my %temporalities, 'Tie::IxHash',
20   'upcoming'  => "Upcoming (future)",
21   'preceding' => "Preceding (past)",
22 ;
23
24 %info = (
25   'name'      => 'Wholesale CDR cost billing, for master customers of an agent.',
26   'shortname' => 'Whilesale CDR cost billing for agent.',
27   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
28   'fields' => { #false laziness w/cdr_termination
29
30     #false laziness w/flat.pm
31     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
32                              'type' => 'select',
33                              'select_options' => \%temporalities,
34                            },
35
36     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
37                                    'subscription',
38                          'default' => '1',
39                        },
40     'recur_method'  => { 'name' => 'Recurring fee method',
41                          #'type' => 'radio',
42                          #'options' => \%recur_method,
43                          'type' => 'select',
44                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
45                        },
46
47     #false laziness w/voip_cdr.pm
48     'output_format' => { 'name' => 'CDR invoice display format',
49                          'type' => 'select',
50                          'select_options' => { FS::cdr::invoice_formats() },
51                          'default'        => 'simple2', #with source
52                        },
53     #eofalse
54
55   },
56
57   'fieldorder' => [ qw( recur_temporality recur_method cutoff_day ),
58                     FS::part_pkg::prorate_Mixin::fieldorder, 
59                     qw( output_format ),
60                   ],
61
62   'weight' => 53,
63
64 );
65
66 sub calc_recur {
67   my( $self, $cust_pkg, $sdate, $details, $param ) = @_;
68
69   #my $last_bill = $cust_pkg->last_bill;
70   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
71
72   return 0
73     if $self->recur_temporality eq 'preceding'
74     && ( $last_bill eq '' || $last_bill == 0 );
75
76   my $charges = 0;
77
78   my $output_format = $self->option('output_format', 'Hush!') || 'simple2';
79
80   #CDR calculations
81
82   #false laziness w/agent.pm
83   #almost always just one,
84   #unless you have multiple agents with same master customer0
85   my @agents = qsearch('agent', { 'agent_custnum' => $cust_pkg->custnum } );
86
87   foreach my $agent (@agents) {
88
89     warn "$me billing wholesale CDRs for agent ". $agent->agent. "\n"
90       if $DEBUG;
91
92     #not the most efficient to load them all into memory,
93     #but good enough for our current needs
94     my @cust_main = qsearch('cust_main', { 'agentnum' => $agent->agentnum } );
95
96     foreach my $cust_main (@cust_main) {
97
98       warn "$me billing agent wholesale CDRs for ". $cust_main->name_short. "\n"
99         if $DEBUG;
100
101       #eofalse laziness w/agent.pm
102
103       my @svcnum = ();
104       foreach my $cust_pkg ( $cust_main->cust_pkg ) {
105         push @svcnum, map $_->svcnum, $cust_pkg->cust_svc( svcdb=>'svc_phone' );
106       }
107
108       next unless @svcnum;
109
110       #false laziness w/cdr_termination
111
112       my $termpart = 1; #or from an option -- we're not termination, we're wholesale?  for now, use one or the other
113
114       #false lazienss w/search/cdr.html (i should be a part_termination method)
115       my $where_term =
116         "( cdr.acctid = cdr_termination.acctid AND termpart = $termpart ) ";
117       #my $join_term = "LEFT JOIN cdr_termination ON ( $where_term )";
118       my $extra_sql =
119         "AND NOT EXISTS ( SELECT 1 FROM cdr_termination WHERE $where_term )";
120
121       #eofalse laziness w/cdr_termination.pm
122
123       #false laziness w/ svc_phone->psearch_cdrs, kinda
124       my $cdr_search = psearch({
125         'table'     => 'cdr',
126         #'addl_from' => $join_term,
127         'hashref'   => {},
128         'extra_sql' => " WHERE freesidestatus IN ( 'rated', 'done' ) ".
129                        "   AND svcnum IN (". join(',', @svcnum). ") ".
130                        $extra_sql,
131         'order_by'  => 'ORDER BY startdate FOR UPDATE ',
132
133       });
134
135       #false laziness w/voip_cdr
136       $cdr_search->limit(1000);
137       $cdr_search->increment(0); #because we're adding cdr_termination as we go?
138       while ( my $cdr = $cdr_search->fetch ) {
139
140         my $cost = $cdr->rate_cost;
141         #XXX exception handling?  return undef? (and err?) ref to a scalar err?
142
143         #false laziness w/cdr_termination
144
145         #add a cdr_termination record and the charges
146
147         my $cdr_termination = new FS::cdr_termination {
148           'acctid'      => $cdr->acctid,
149           'termpart'    => $termpart,
150           'rated_price' => $cost,
151           'status'      => 'done',
152         };
153
154         my $error = $cdr_termination->insert;
155         die $error if $error; #next if $error; #or just skip this one???  why?
156
157         $charges += $cost;
158
159         # and add a line to the invoice
160
161         my $call_details = $cdr->downstream_csv( 'format' => $output_format,
162                                                  'charge' => $cost,
163                                                );
164         my $classnum = ''; #usage class?
165
166        #option to turn off?  or just use squelch_cdr for the customer probably
167         push @$details, [ 'C', $call_details, $cost, $classnum ];
168
169         #eofalse laziness w/cdr_termination
170
171       }
172
173     }
174
175   }
176
177   #eo CDR calculations
178
179   $charges += ($cust_pkg->quantity || 1) * $self->calc_recur_Common(@_);
180
181   $charges;
182 }
183
184 sub can_discount { 0; }
185
186 #?  sub hide_svc_detail { 1; }
187
188 sub is_free { 0; }
189
190 sub can_usageprice { 0; }
191
192 1;