Rate CDRs immediately, RT#15839
[freeside.git] / FS / FS / part_pkg / voip_cdr.pm
1 package FS::part_pkg::voip_cdr;
2 use base qw( FS::part_pkg::recur_Common );
3
4 use strict;
5 use vars qw( $DEBUG %info );
6 use List::Util qw(first min);
7 use Tie::IxHash;
8 use Date::Format;
9 use Text::CSV_XS;
10 use FS::Conf;
11 use FS::Record qw(qsearchs qsearch);
12 use FS::cdr;
13 #use FS::rate;
14 #use FS::rate_prefix;
15 #use FS::rate_detail;
16
17 $DEBUG = 0;
18
19 tie my %cdr_svc_method, 'Tie::IxHash',
20   'svc_phone.phonenum' => 'Phone numbers (svc_phone.phonenum)',
21   'svc_pbx.title'      => 'PBX name (svc_pbx.title)',
22   'svc_pbx.svcnum'     => 'Freeside service # (svc_pbx.svcnum)',
23 ;
24
25 tie my %rating_method, 'Tie::IxHash',
26   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
27 #  'upstream' => 'Rate calls based on upstream data: If the call type is "1", map the upstream rate ID directly to an internal rate (rate_detail), otherwise, pass the upstream price through directly.',
28   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
29   'single_price' => 'A single price per minute for all calls.',
30 ;
31
32 #tie my %cdr_location, 'Tie::IxHash',
33 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
34 #  'external' => 'External: CDR records queried directly from an external '.
35 #                'Asterisk (or other?) CDR table',
36 #;
37
38 tie my %temporalities, 'Tie::IxHash',
39   'upcoming'  => "Upcoming (future)",
40   'preceding' => "Preceding (past)",
41 ;
42
43 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
44
45 # previously "1" was "ignore"
46 tie my %unrateable_opts, 'Tie::IxHash',
47   '' => 'Exit with a fatal error',
48   1  => 'Ignore and continue',
49   2  => 'Flag for later review',
50 ;
51
52 %info = (
53   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
54   'shortname' => 'VoIP/telco CDR rating (standard)',
55   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
56   'fields' => {
57     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
58                         'type' => 'checkbox',
59                       },
60     #false laziness w/flat.pm
61     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
62                              'type' => 'select',
63                              'select_options' => \%temporalities,
64                            },
65
66     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
67                                    'subscription',
68                          'default' => '1',
69                        },
70     'recur_method'  => { 'name' => 'Recurring fee method',
71                          #'type' => 'radio',
72                          #'options' => \%recur_method,
73                          'type' => 'select',
74                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
75                        },
76
77     'cdr_svc_method' => { 'name' => 'CDR service matching method',
78                           'type' => 'radio',
79                           'options' => \%cdr_svc_method,
80                         },
81
82     'rating_method' => { 'name' => 'Rating method',
83                          'type' => 'radio',
84                          'options' => \%rating_method,
85                        },
86
87     'ratenum'   => { 'name' => 'Rate plan',
88                      'type' => 'select',
89                      'select_table' => 'rate',
90                      'select_key'   => 'ratenum',
91                      'select_label' => 'ratename',
92                    },
93                    
94     'intrastate_ratenum'   => { 'name' => 'Optional alternate intrastate rate plan',
95                      'type' => 'select',
96                      'select_table' => 'rate',
97                      'select_key'   => 'ratenum',
98                      'select_label' => 'ratename',
99                      'disable_empty' => 0,
100                      'empty_label'   => '',
101                    },
102
103     'min_included' => { 'name' => 'Minutes included when using the "single price per minute" rating method or when using the "prefix" rating method ("region group" billing)',
104                     },
105
106     'min_charge' => { 'name' => 'Charge per minute when using "single price per minute" rating method',
107                     },
108
109     'sec_granularity' => { 'name' => 'Granularity when using "single price per minute" rating method',
110                            'type' => 'select',
111                            'select_options' => \%granularity,
112                          },
113
114     'ignore_unrateable' => { 'name' => 'Handling of calls without a rate in the rate table',
115                              'type' => 'select',
116                              'select_options' => \%unrateable_opts,
117                            },
118
119     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
120                           'default' => '+1',
121                         },
122
123     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
124                        'type' => 'checkbox'
125                      },
126
127     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
128                            'default' => '1',
129                          },
130
131 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
132 #                                    'type' => 'checkbox',
133 #                                  },
134
135     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
136                                 'default' => '011',
137                               },
138
139     'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
140                             'type' => 'checkbox',
141                           },
142
143     'use_amaflags' => { 'name' => 'Only charge for CDRs where the amaflags field is set to "2" ("BILL"/"BILLING").',
144                         'type' => 'checkbox',
145                       },
146
147     'use_carrierid' => { 'name' => 'Only charge for CDRs where the Carrier ID is set to: ',
148                          },
149
150     'use_cdrtypenum' => { 'name' => 'Only charge for CDRs where the CDR Type is set to: ',
151                          },
152     
153     'ignore_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is set to: ',
154                          },
155     
156     'ignore_disposition' => { 'name' => 'Do not charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
157                          },
158     
159     'disposition_in' => { 'name' => 'Only charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
160                          },
161
162     'skip_dst_prefix' => { 'name' => 'Do not charge for CDRs where the destination number starts with any of these values: ',
163     },
164
165     'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values: ',
166                        },
167
168     'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
169                                 },
170
171     'skip_src_length_more' => { 'name' => 'Do not charge for CDRs where the source is more than this many digits:',
172                               },
173
174     'noskip_src_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where source is equal or greater than the specified digits, when accountcode is toll free',
175                                                   'type' => 'checkbox',
176                                                 },
177
178     'accountcode_tollfree_ratenum' => {
179       'name' => 'Optional alternate rate plan when accountcode is toll free: ',
180       'type' => 'select',
181       'select_table'  => 'rate',
182       'select_key'    => 'ratenum',
183       'select_label'  => 'ratename',
184       'disable_empty' => 0,
185       'empty_label'   => '',
186     },
187
188     'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
189                               },
190
191     'noskip_dst_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where dst is less than the specified digits, when accountcode is toll free',
192                                                   'type' => 'checkbox',
193                                                 },
194
195     'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value: ',
196                       },
197
198     'skip_max_callers' => { 'name' => 'Do not charge for CDRs where max_callers is less than or equal to this value: ',
199                           },
200
201     'use_duration'   => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
202                           'type' => 'checkbox',
203                         },
204
205     '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes (also ignore any carrierid check): ',
206                       },
207
208     #false laziness w/cdr_termination.pm
209     'output_format' => { 'name' => 'CDR invoice display format',
210                          'type' => 'select',
211                          'select_options' => { FS::cdr::invoice_formats() },
212                          'default'        => 'default', #XXX test
213                        },
214
215     'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not): ',
216                        },
217
218     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
219                           'type' => 'checkbox',
220                         },
221
222     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
223                           'type' => 'checkbox',
224                        },
225     #eofalse
226
227     'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call (as well any setup fee, upon first payment).  Useful for prepaid.',
228                            'type' => 'checkbox',
229                          },
230
231     'bill_inactive_svcs' => { 'name' => 'Bill for all phone numbers that were active during the billing period',
232                               'type' => 'checkbox',
233                             },
234
235     'count_available_phones' => { 'name' => 'Consider for tax purposes the number of lines to be svc_phones that may be provisioned rather than those that actually are.',
236                            'type' => 'checkbox',
237                          },
238
239     #XXX also have option for an external db?  these days we suck them into ours
240 #    'cdr_location' => { 'name' => 'CDR database location'
241 #                        'type' => 'select',
242 #                        'select_options' => \%cdr_location,
243 #                        'select_callback' => {
244 #                          'external' => {
245 #                            'enable' => [ 'datasrc', 'username', 'password' ],
246 #                          },
247 #                          'internal' => {
248 #                            'disable' => [ 'datasrc', 'username', 'password' ],
249 #                          }
250 #                        },
251 #                      },
252 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
253 #                   'disabled' => 'Y',
254 #                 },
255 #    'username' => { 'name' => 'External database username',
256 #                    'disabled' => 'Y',
257 #                  },
258 #    'password' => { 'name' => 'External database password',
259 #                    'disabled' => 'Y',
260 #                  },
261
262   },
263   'fieldorder' => [qw(
264                        recur_temporality
265                        recur_method cutoff_day ),
266                        FS::part_pkg::prorate_Mixin::fieldorder,
267                     qw(
268                        cdr_svc_method
269                        rating_method ratenum intrastate_ratenum 
270                        min_charge min_included sec_granularity
271                        ignore_unrateable
272                        default_prefix
273                        disable_src
274                        domestic_prefix international_prefix
275                        disable_tollfree
276                        use_amaflags
277                        use_carrierid 
278                        use_cdrtypenum ignore_cdrtypenum
279                        ignore_disposition disposition_in
280                        skip_dcontext skip_dst_prefix 
281                        skip_dstchannel_prefix skip_src_length_more 
282                        noskip_src_length_accountcode_tollfree
283                        accountcode_tollfree_ratenum
284                        skip_dst_length_less
285                        noskip_dst_length_accountcode_tollfree
286                        skip_lastapp
287                        skip_max_callers
288                        use_duration
289                        411_rewrite
290                        output_format usage_mandate summarize_usage usage_section
291                        bill_every_call bill_inactive_svcs
292                        count_available_phones suspend_bill 
293                      )
294                   ],
295   'weight' => 40,
296 );
297
298 sub price_info {
299     my $self = shift;
300     my $str = $self->SUPER::price_info;
301     $str .= " plus usage" if $str;
302     $str;
303 }
304
305 sub calc_recur {
306   my $self = shift;
307   my($cust_pkg, $sdate, $details, $param ) = @_;
308
309   my $charges = 0;
310
311   $charges += $self->calc_usage(@_);
312   $charges += $self->calc_recur_Common(@_);
313
314   $charges;
315
316 }
317
318 sub calc_cancel {
319   my $self = shift;
320   my($cust_pkg, $sdate, $details, $param ) = @_;
321
322   $self->calc_usage(@_);
323 }
324
325 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
326
327 sub calc_usage {
328   my $self = shift;
329   my($cust_pkg, $sdate, $details, $param ) = @_;
330
331   #my $last_bill = $cust_pkg->last_bill;
332   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
333
334   return 0
335     if $self->recur_temporality eq 'preceding'
336     && ( $last_bill eq '' || $last_bill == 0 );
337
338   my $charges = 0;
339
340   my $included_min = $self->option('min_included', 1) || 0; #single price rating
341
342   my $cdr_svc_method    = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
343   my $rating_method     = $self->option('rating_method') || 'prefix';
344   my $region_group_included_min = $self->option('min_included',1) || 0;
345   my %region_group_included_min = ();
346
347   my $output_format     = $self->option('output_format', 'Hush!')
348                           || ( $rating_method eq 'upstream_simple'
349                                  ? 'simple'
350                                  : 'default'
351                              );
352
353   my $use_duration = $self->option('use_duration');
354
355   my $csv = new Text::CSV_XS;
356
357   my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
358
359   my @cust_svc;
360   if( $self->option('bill_inactive_svcs',1) ) {
361     #XXX in this mode do we need to restrict the set of CDRs by date also?
362     @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
363   }
364   else {
365     @cust_svc = $cust_pkg->cust_svc;
366   }
367   @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
368
369   foreach my $cust_svc (@cust_svc) {
370
371     my $svc_x;
372     if( $self->option('bill_inactive_svcs',1) ) {
373       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
374     }
375     else {
376       $svc_x = $cust_svc->svc_x;
377     }
378
379     my %options = (
380         'disable_src'    => $self->option('disable_src'),
381         'default_prefix' => $self->option('default_prefix'),
382         'cdrtypenum'     => $self->option('use_cdrtypenum'),
383         'status'         => '',
384         'for_update'     => 1,
385       );  # $last_bill, $$sdate )
386     $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
387
388     my @invoice_details_sort;
389
390     #first rate any outstanding CDRs not yet rated
391     foreach my $cdr (
392       $svc_x->get_cdrs( %options )
393     ) {
394
395       my $error = $cdr->rate(
396         'part_pkg'                          => $self,
397         'svcnum'                            => $svc_x->svcnum,
398         'single_price_included_min'         => \$included_min,
399         'region_group_included_min'         => \$region_group_included_min,
400         'region_group_included_min_hashref' => \%region_group_included_min,
401       );
402       die $error if $error; #??
403
404     } # $cdr
405
406     #then add details to invoices & get a total
407     $options{'status'} = 'rated';
408     foreach my $cdr (
409       $svc_x->get_cdrs( %options )
410     ) {
411
412       my $classnum = '';
413       my @call_details = ();
414       
415       if ( $rating_method eq 'prefix' ) {
416
417         $classnum = $cdr->rated_classnum;
418
419         unless ( $self->sum_usage ) {
420           @call_details = ($cdr->downstream_csv(
421             'format'         => $output_format,
422             'granularity'    => $cdr->rated_granularity, 
423             'seconds'        =>($use_duration ? $cdr->duration : $cdr->billsec),
424             'charge'         => $cdr->rated_price,
425             'pretty_dst'     => $cdr->rated_pretty_dst,
426             'dst_regionname' => $cdr->rated_regionname,
427           ));
428         }
429
430
431       } elsif ( $rating_method eq 'upstream_simple' ) {
432
433         $classnum = $cdr->calltypenum; #? meaningful these days?
434
435         @call_details = ($cdr->downstream_csv(
436           'format' => $output_format,
437           'charge' => $cdr->rated_price,
438         ));
439
440       } elsif ( $rating_method eq 'single_price' ) {
441
442         my $granularity = length($self->option_cacheable('sec_granularity'))
443                             ? $self->option_cacheable('sec_granularity')
444                             : 60;
445
446         @call_details = ($cdr->downstream_csv(
447           'format'      => $output_format,
448           'charge'      => $cdr->rated_price,
449           'seconds'     => ($use_duration ? $cdr->duration : $cdr->billsec),
450           'granularity' => $granularity,
451         ));
452
453       } else {
454         die "don't know how to rate CDRs using method: $rating_method\n";
455       }
456
457       $charges += $cdr->rated_price;
458
459       #if ( $cdr->rated_price > 0 ) {
460       # generate a detail record for every call; filter out
461       # $cdr->rated_price == 0 # later.
462       my $call_details;
463       my $phonenum = $svc_x->phonenum;
464
465       if ( scalar(@call_details) == 1 ) {
466         $call_details =
467         { format      => 'C',
468           detail      => $call_details[0],
469           amount      => $cdr->rated_price,
470           classnum    => $classnum,
471           phonenum    => $phonenum,
472           accountcode => $cdr->accountcode,
473           startdate   => $cdr->startdate,
474           duration    => $cdr->rated_seconds,
475           regionname  => $cdr->rated_regionname,
476         };
477       } else { #only used for $rating_method eq 'upstream' now
478         # and for sum_ formats
479         $csv->combine(@call_details);
480         $call_details =
481         { format      => 'C',
482           detail      => $csv->string,
483           amount      => $cdr->rated_price,
484           classnum    => $classnum,
485           phonenum    => $phonenum,
486           accountcode => $cdr->accountcode,
487           startdate   => $cdr->startdate,
488           duration    => $cdr->rated_seconds,
489           regionname  => $cdr->rated_regionname,
490         };
491       }
492       $call_details->{'ratename'} = $cdr->rated_ratename;
493
494       push @invoice_details_sort, [ $call_details, $cdr->calldate_unix ];
495       #} $charge > 0
496
497       my $error = $cdr->set_status('done');
498       die $error if $error; #??
499
500     }
501
502     if ( !$self->sum_usage ) {
503       #sort them
504       my @sorted_invoice_details = 
505         sort { @{$a}[1] <=> @{$b}[1] } @invoice_details_sort;
506       foreach my $sorted_call_detail ( @sorted_invoice_details ) {
507         my $d = $sorted_call_detail->[0];
508         push @$details, $d if $d->{amount} > 0;
509       }
510     }
511     else { #$self->sum_usage
512         push @$details, $self->sum_detail($svc_x, \@invoice_details_sort);
513     }
514   } # $cust_svc
515
516   unshift @$details, { format => 'C',
517                        detail => FS::cdr::invoice_header($output_format),
518                      }
519     if @$details && $rating_method ne 'upstream';
520
521   $charges;
522 }
523
524 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
525 sub check_chargable {
526   my( $self, $cdr, %flags ) = @_;
527
528   return 'amaflags != 2'
529     if $self->option_cacheable('use_amaflags') && $cdr->amaflags != 2;
530
531   return "disposition NOT IN ( $self->option_cacheable('disposition_in') )"
532     if $self->option_cacheable('disposition_in') =~ /\S/
533     && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('disposition_in'));
534   
535   return "disposition IN ( $self->option_cacheable('ignore_disposition') )"
536     if $self->option_cacheable('ignore_disposition') =~ /\S/
537     && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('ignore_disposition'));
538
539   foreach(split(/\s*,\s*/, $self->option_cacheable('skip_dst_prefix'))) {
540     return "dst starts with '$_'"
541     if length($_) && substr($cdr->dst,0,length($_)) eq $_;
542   }
543
544   return "carrierid != $self->option_cacheable('use_carrierid')"
545     if length($self->option_cacheable('use_carrierid'))
546     && $cdr->carrierid ne $self->option_cacheable('use_carrierid') #ne otherwise 0 matches ''
547     && ! $flags{'da_rewrote'};
548
549   # unlike everything else, use_cdrtypenum is applied in FS::svc_x::get_cdrs.
550   return "cdrtypenum != $self->option_cacheable('use_cdrtypenum')"
551     if length($self->option_cacheable('use_cdrtypenum'))
552     && $cdr->cdrtypenum ne $self->option_cacheable('use_cdrtypenum'); #ne otherwise 0 matches ''
553   
554   return "cdrtypenum == $self->option_cacheable('ignore_cdrtypenum')"
555     if length($self->option_cacheable('ignore_cdrtypenum'))
556     && $cdr->cdrtypenum eq $self->option_cacheable('ignore_cdrtypenum'); #eq otherwise 0 matches ''
557
558   return "dcontext IN ( $self->option_cacheable('skip_dcontext') )"
559     if $self->option_cacheable('skip_dcontext') =~ /\S/
560     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $self->option_cacheable('skip_dcontext'));
561
562   my $len_prefix = length($self->option_cacheable('skip_dstchannel_prefix'));
563   return "dstchannel starts with $self->option_cacheable('skip_dstchannel_prefix')"
564     if $len_prefix
565     && substr($cdr->dstchannel,0,$len_prefix) eq $self->option_cacheable('skip_dstchannel_prefix');
566
567   my $dst_length = $self->option_cacheable('skip_dst_length_less');
568   return "destination less than $dst_length digits"
569     if $dst_length && length($cdr->dst) < $dst_length
570     && ! ( $self->option_cacheable('noskip_dst_length_accountcode_tollfree')
571             && $cdr->is_tollfree('accountcode')
572          );
573
574   return "lastapp is $self->option_cacheable('skip_lastapp')"
575     if length($self->option_cacheable('skip_lastapp')) && $cdr->lastapp eq $self->option_cacheable('skip_lastapp');
576
577   my $src_length = $self->option_cacheable('skip_src_length_more');
578   if ( $src_length ) {
579
580     if ( $self->option_cacheable('noskip_src_length_accountcode_tollfree') ) {
581
582       if ( $cdr->is_tollfree('accountcode') ) {
583         return "source less than or equal to $src_length digits"
584           if length($cdr->src) <= $src_length;
585       } else {
586         return "source more than $src_length digits"
587           if length($cdr->src) > $src_length;
588       }
589
590     } else {
591       return "source more than $src_length digits"
592         if length($cdr->src) > $src_length;
593     }
594
595   }
596
597   return "max_callers <= ". $self->option_cacheable('skip_max_callers')
598     if length($self->option_cacheable('skip_max_callers'))
599       and length($cdr->max_callers)
600       and $cdr->max_callers <= $self->option_cacheable('skip_max_callers');
601
602   #all right then, rate it
603   '';
604 }
605
606 sub is_free {
607   0;
608 }
609
610 #  This equates svc_phone records; perhaps svc_phone should have a field
611 #  to indicate it represents a line
612 sub calc_units {    
613   my($self, $cust_pkg ) = @_;
614   my $count = 0;
615   if ( $self->option('count_available_phones', 1)) {
616     map { $count += ( $_->quantity || 0 ) }
617       grep { $_->part_svc->svcdb eq 'svc_phone' }
618       $cust_pkg->part_pkg->pkg_svc;
619   } else {
620     $count = 
621       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
622   }
623   $count;
624 }
625
626 # tells whether cust_bill_pkg_detail should return a single line for 
627 # each phonenum
628 sub sum_usage {
629   my $self = shift;
630   $self->option('output_format') =~ /^sum_/;
631 }
632
633 sub sum_detail {
634   my $self = shift;
635   my $svc_x = shift;
636   my $invoice_details = shift || [];
637   return () if !@$invoice_details;
638   my $details_by_rate = {};
639   # combine the entire set of CDRs
640   foreach ( @$invoice_details ) {
641     my $d = $_->[0];
642     my $sum = $details_by_rate->{ $d->{ratename} } ||= {
643       amount      => 0,
644       format      => 'C',
645       classnum    => '', #XXX
646       duration    => 0,
647       phonenum    => $svc_x->phonenum,
648       accountcode => '', #XXX
649       startdate   => '', #XXX
650       regionname  => '',
651       count       => 0,
652     };
653     $sum->{amount} += $d->{amount};
654     $sum->{duration} += $d->{duration};
655     $sum->{count}++;
656   }
657   my @details;
658   foreach my $ratename ( sort keys(%$details_by_rate) ) {
659     my $sum = $details_by_rate->{$ratename};
660     next if $sum->{count} == 0;
661     my $total_cdr = FS::cdr->new({
662         'billsec' => $sum->{duration},
663         'src'     => $sum->{phonenum},
664       });
665     $sum->{detail} = $total_cdr->downstream_csv(
666       format    => $self->option('output_format'),
667       seconds   => $sum->{duration},
668       charge    => sprintf('%.2f',$sum->{amount}),
669       ratename  => $ratename,
670       phonenum  => $sum->{phonenum},
671       count     => $sum->{count},
672     );
673     push @details, $sum;
674   }
675   @details;
676 }
677
678 # and whether cust_bill should show a detail line for the service label 
679 # (separate from usage details)
680 sub hide_svc_detail {
681   my $self = shift;
682   $self->option('output_format') =~ /^sum_/;
683 }
684
685
686 1;
687