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