comment nit
[freeside.git] / FS / FS / svc_phone.pm
1 package FS::svc_phone;
2
3 use strict;
4 use base qw( FS::svc_Domain_Mixin FS::location_Mixin FS::svc_Common );
5 use vars qw( $DEBUG $me @pw_set $conf $phone_name_max );
6 use Data::Dumper;
7 use Scalar::Util qw( blessed );
8 use FS::Conf;
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::PagedSearch qw( psearch );
11 use FS::Msgcat qw(gettext);
12 use FS::part_svc;
13 use FS::phone_device;
14 use FS::svc_pbx;
15 use FS::svc_domain;
16 use FS::cust_location;
17 use FS::phone_avail;
18
19 $me = '[' . __PACKAGE__ . ']';
20 $DEBUG = 0;
21
22 #avoid l 1 and o O 0
23 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
24
25 #ask FS::UID to run this stuff for us later
26 FS::UID->install_callback( sub { 
27   $conf = new FS::Conf;
28   $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
29 }
30 );
31
32 =head1 NAME
33
34 FS::svc_phone - Object methods for svc_phone records
35
36 =head1 SYNOPSIS
37
38   use FS::svc_phone;
39
40   $record = new FS::svc_phone \%hash;
41   $record = new FS::svc_phone { 'column' => 'value' };
42
43   $error = $record->insert;
44
45   $error = $new_record->replace($old_record);
46
47   $error = $record->delete;
48
49   $error = $record->check;
50
51   $error = $record->suspend;
52
53   $error = $record->unsuspend;
54
55   $error = $record->cancel;
56
57 =head1 DESCRIPTION
58
59 An FS::svc_phone object represents a phone number.  FS::svc_phone inherits
60 from FS::Record.  The following fields are currently supported:
61
62 =over 4
63
64 =item svcnum
65
66 primary key
67
68 =item countrycode
69
70 =item phonenum
71
72 =item sim_imsi
73
74 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
75
76 =item sip_password
77
78 =item pin
79
80 Voicemail PIN
81
82 =item phone_name
83
84 =item pbxsvc
85
86 Optional svcnum from svc_pbx
87
88 =item forwarddst
89
90 Forwarding destination
91
92 =item email
93
94 Email address for virtual fax (fax-to-email) services
95
96 =item lnp_status
97
98 LNP Status (can be null, native, portedin, portingin, portin-reject,
99 portingout, portout-reject)
100
101 =item portable
102
103 =item lrn
104
105 =item lnp_desired_due_date
106
107 =item lnp_due_date
108
109 =item lnp_other_provider
110
111 If porting the number in or out, name of the losing or winning provider, 
112 respectively.
113
114 =item lnp_other_provider_account
115
116 Account number of other provider. See lnp_other_provider.
117
118 =item lnp_reject_reason
119
120 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
121 optional reject reason.
122
123 =back
124
125 =head1 METHODS
126
127 =over 4
128
129 =item new HASHREF
130
131 Creates a new phone number.  To add the number to the database, see L<"insert">.
132
133 Note that this stores the hash reference, not a distinct copy of the hash it
134 points to.  You can ask the object for a copy with the I<hash> method.
135
136 =cut
137
138 # the new method can be inherited from FS::Record, if a table method is defined
139 #
140 sub table_info {
141  my %dis2 = ( disable_inventory=>1, disable_select=>1 );
142   {
143     'name' => 'Phone number',
144     'sorts' => 'phonenum',
145     'display_weight' => 60,
146     'cancel_weight'  => 80,
147     'fields' => {
148         'svcnum'       => 'Service',
149         'countrycode'  => { label => 'Country code',
150                             type  => 'text',
151                             disable_inventory => 1,
152                             disable_select => 1,
153                           },
154         'phonenum'     => 'Phone number',
155         'sim_imsi'     => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
156         'pin'          => { label => 'Voicemail PIN', #'Personal Identification Number',
157                             type  => 'text',
158                             disable_inventory => 1,
159                             disable_select => 1,
160                           },
161         'sip_password' => 'SIP password',
162         'phone_name'   => 'Name',
163         'pbxsvc'       => { label => 'PBX',
164                             type  => 'select-svc_pbx.html',
165                             disable_inventory => 1,
166                             disable_select => 1, #UI wonky, pry works otherwise
167                           },
168         'domsvc'    => {
169                          label     => 'Domain',
170                          type      => 'select',
171                          select_table => 'svc_domain',
172                          select_key   => 'svcnum',
173                          select_label => 'domain',
174                          disable_inventory => 1,
175                        },
176         'locationnum' => {
177                            label => 'E911 location',
178                            disable_inventory => 1,
179                            disable_select    => 1,
180                          },
181         'forwarddst' => {       label => 'Forward Destination', 
182                                 %dis2,
183                         },
184         'email' => {            label => 'Email',
185                                 %dis2,
186                     },
187         'lnp_status' => {       label => 'LNP Status',
188                                 type => 'select-lnp_status.html',
189                                 %dis2,
190                         },
191         'lnp_reject_reason' => { 
192                                 label => 'LNP Reject Reason',
193                                 %dis2,
194                         },
195         'portable' =>   {       label => 'Portable?', %dis2, },
196         'lrn'   =>      {       label => 'LRN', 
197                                 disable_inventory => 1, 
198                         },
199         'lnp_desired_due_date' =>
200                         { label => 'LNP Desired Due Date', %dis2 },
201         'lnp_due_date' =>
202                         { label => 'LNP Due Date', %dis2 },
203         'lnp_other_provider' =>
204                         {       label => 'LNP Other Provider', 
205                                 disable_inventory => 1, 
206                         },
207         'lnp_other_provider_account' =>
208                         {       label => 'LNP Other Provider Account #', 
209                                 %dis2 
210                         },
211     },
212   };
213 }
214
215 sub table { 'svc_phone'; }
216
217 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
218
219 =item search_sql STRING
220
221 Class method which returns an SQL fragment to search for the given string.
222
223 =cut
224
225 sub search_sql {
226   my( $class, $string ) = @_;
227
228   my $conf = new FS::Conf;
229
230   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
231     $string =~ s/\W//g;
232   } else {
233     $string =~ s/\D//g;
234   }
235
236   my $ccode = (    $conf->exists('default_phone_countrycode')
237                 && $conf->config('default_phone_countrycode')
238               )
239                 ? $conf->config('default_phone_countrycode') 
240                 : '1';
241
242   $string =~ s/^$ccode//;
243
244   $class->search_sql_field('phonenum', $string );
245 }
246
247 =item label
248
249 Returns the phone number.
250
251 =cut
252
253 sub label {
254   my $self = shift;
255   my $phonenum = $self->phonenum; #XXX format it better
256   my $label = $phonenum;
257   $label .= '@'.$self->domain if $self->domsvc;
258   $label .= ' ('.$self->phone_name.')' if $self->phone_name;
259   $label;
260 }
261
262 =item insert
263
264 Adds this phone number to the database.  If there is an error, returns the
265 error, otherwise returns false.
266
267 =cut
268
269 sub insert {
270   my $self = shift;
271   my %options = @_;
272
273   if ( $DEBUG ) {
274     warn "[$me] insert called on $self: ". Dumper($self).
275          "\nwith options: ". Dumper(%options);
276   }
277
278   local $SIG{HUP} = 'IGNORE';
279   local $SIG{INT} = 'IGNORE';
280   local $SIG{QUIT} = 'IGNORE';
281   local $SIG{TERM} = 'IGNORE';
282   local $SIG{TSTP} = 'IGNORE';
283   local $SIG{PIPE} = 'IGNORE';
284
285   my $oldAutoCommit = $FS::UID::AutoCommit;
286   local $FS::UID::AutoCommit = 0;
287   my $dbh = dbh;
288
289   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
290   #make it more of a base class than a mixin... :)
291   if ( $options{'cust_location'} ) {
292     my $error = $options{'cust_location'}->find_or_insert;
293     if ( $error ) {
294       $dbh->rollback if $oldAutoCommit;
295       return "inserting cust_location (transaction rolled back): $error";
296     }
297     $self->locationnum( $options{'cust_location'}->locationnum );
298   }
299   #what about on-the-fly edits?  if the ui supports it?
300
301   my $error = $self->SUPER::insert(%options);
302   if ( $error ) {
303     $dbh->rollback if $oldAutoCommit;
304     return $error;
305   }
306
307   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
308   '';
309
310 }
311
312 =item delete
313
314 Delete this record from the database.
315
316 =cut
317
318 sub delete {
319   my $self = shift;
320
321   local $SIG{HUP} = 'IGNORE';
322   local $SIG{INT} = 'IGNORE';
323   local $SIG{QUIT} = 'IGNORE';
324   local $SIG{TERM} = 'IGNORE';
325   local $SIG{TSTP} = 'IGNORE';
326   local $SIG{PIPE} = 'IGNORE';
327
328   my $oldAutoCommit = $FS::UID::AutoCommit;
329   local $FS::UID::AutoCommit = 0;
330   my $dbh = dbh;
331
332   foreach my $phone_device ( $self->phone_device ) {
333     my $error = $phone_device->delete;
334     if ( $error ) {
335       $dbh->rollback if $oldAutoCommit;
336       return $error;
337     }
338   }
339
340   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
341   foreach my $phone_avail ( @phone_avail ) {
342     $phone_avail->svcnum('');
343     my $error = $phone_avail->replace;
344     if ( $error ) {
345       $dbh->rollback if $oldAutoCommit;
346       return $error;
347     }
348   }
349
350   my $error = $self->SUPER::delete;
351   if ( $error ) {
352     $dbh->rollback if $oldAutoCommit;
353     return $error;
354   }
355
356   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
357   '';
358
359 }
360
361 =item replace OLD_RECORD
362
363 Replaces the OLD_RECORD with this one in the database.  If there is an error,
364 returns the error, otherwise returns false.
365
366 =cut
367
368 sub replace {
369   my $new = shift;
370
371   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
372               ? shift
373               : $new->replace_old;
374
375   my %options = @_;
376
377   if ( $DEBUG ) {
378     warn "[$me] replacing $old with $new\n".
379          "\nwith options: ". Dumper(%options);
380   }
381
382   local $SIG{HUP} = 'IGNORE';
383   local $SIG{INT} = 'IGNORE';
384   local $SIG{QUIT} = 'IGNORE';
385   local $SIG{TERM} = 'IGNORE';
386   local $SIG{TSTP} = 'IGNORE';
387   local $SIG{PIPE} = 'IGNORE';
388
389   my $oldAutoCommit = $FS::UID::AutoCommit;
390   local $FS::UID::AutoCommit = 0;
391   my $dbh = dbh;
392
393   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
394   #make it more of a base class than a mixin... :)
395   if ( $options{'cust_location'}
396          && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
397     my $error = $options{'cust_location'}->insert;
398     if ( $error ) {
399       $dbh->rollback if $oldAutoCommit;
400       return "inserting cust_location (transaction rolled back): $error";
401     }
402     $new->locationnum( $options{'cust_location'}->locationnum );
403   }
404   #what about on-the-fly edits?  if the ui supports it?
405
406   # LNP data validation
407  return 'Invalid LNP status' # if someone does really stupid stuff
408     if (  ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
409         || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
410         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
411         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
412         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
413         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
414         || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
415         );
416
417   my $error = $new->SUPER::replace($old, %options);
418   if ( $error ) {
419     $dbh->rollback if $oldAutoCommit;
420     return $error if $error;
421   }
422
423   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
424   ''; #no error
425 }
426
427 =item suspend
428
429 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
430
431 =item unsuspend
432
433 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
434
435 =item cancel
436
437 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
438
439 =item check
440
441 Checks all fields to make sure this is a valid phone number.  If there is
442 an error, returns the error, otherwise returns false.  Called by the insert
443 and replace methods.
444
445 =cut
446
447 # the check method should currently be supplied - FS::Record contains some
448 # data checking routines
449
450 sub check {
451   my $self = shift;
452
453   my $conf = new FS::Conf;
454
455   my $phonenum = $self->phonenum;
456   my $phonenum_check_method;
457   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
458     $phonenum =~ s/\W//g;
459     $phonenum_check_method = 'ut_alpha';
460   } else {
461     $phonenum =~ s/\D//g;
462     $phonenum_check_method = 'ut_number';
463   }
464   $self->phonenum($phonenum);
465
466   $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
467
468   my $error = 
469     $self->ut_numbern('svcnum')
470     || $self->ut_numbern('countrycode')
471     || $self->$phonenum_check_method('phonenum')
472     || $self->ut_numbern('sim_imsi')
473     || $self->ut_anything('sip_password')
474     || $self->ut_numbern('pin')
475     || $self->ut_textn('phone_name')
476     || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx',    'svcnum' )
477     || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
478     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
479     || $self->ut_numbern('forwarddst')
480     || $self->ut_textn('email')
481     || $self->ut_numbern('lrn')
482     || $self->ut_numbern('lnp_desired_due_date')
483     || $self->ut_numbern('lnp_due_date')
484     || $self->ut_textn('lnp_other_provider')
485     || $self->ut_textn('lnp_other_provider_account')
486     || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
487                                 'native', 'portin-reject', 'portout-reject'])
488     || $self->ut_enumn('portable', ['','Y'])
489     || $self->ut_textn('lnp_reject_reason')
490   ;
491   return $error if $error;
492
493   return 'Illegal IMSI (not 14-15 digits)' #shorter?
494     if length($self->sim_imsi)
495     && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
496
497     # LNP data validation
498     return 'Cannot set LNP fields: no LNP in progress'
499         if ( ($self->lnp_desired_due_date || $self->lnp_due_date 
500             || $self->lnp_other_provider || $self->lnp_other_provider_account
501             || $self->lnp_reject_reason) 
502             && (!$self->lnp_status || $self->lnp_status eq 'native') );
503     return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
504         if ($self->lnp_reject_reason && (!$self->lnp_status 
505                             || $self->lnp_status !~ /^port(in|out)-reject$/) );
506     return 'Cannot port-out a non-portable number' 
507         if (!$self->portable && $self->lnp_status eq 'portingout');
508
509
510   return 'Name ('. $self->phone_name.
511          ") is longer than $phone_name_max characters"
512     if $phone_name_max && length($self->phone_name) > $phone_name_max;
513
514   $self->countrycode(1) unless $self->countrycode;
515
516   unless ( length($self->pin) ) {
517     my $random_pin = $conf->config('svc_phone-random_pin');
518     if ( $random_pin =~ /^\d+$/ ) {
519       $self->pin(
520         join('', map int(rand(10)), 0..($random_pin-1))
521       );
522     }
523   }
524
525   unless ( length($self->sip_password) ) { # option for this?
526
527     $self->sip_password(
528       join('', map $pw_set[ int(rand $#pw_set) ], (0..16) )
529     );
530
531   }
532
533   $self->SUPER::check;
534 }
535
536 =item _check duplicate
537
538 Internal method to check for duplicate phone numers.
539
540 =cut
541
542 #false laziness w/svc_acct.pm's _check_duplicate.
543 sub _check_duplicate {
544   my $self = shift;
545
546   my $global_unique = $conf->config('global_unique-phonenum') || 'none';
547   return '' if $global_unique eq 'disabled';
548
549   $self->lock_table;
550
551   my @dup_ccphonenum =
552     grep { !$self->svcnum || $_->svcnum != $self->svcnum }
553     qsearch( 'svc_phone', {
554       'countrycode' => $self->countrycode,
555       'phonenum'    => $self->phonenum,
556     });
557
558   return gettext('phonenum_in_use')
559     if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
560
561   my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
562   unless ( $part_svc ) {
563     return 'unknown svcpart '. $self->svcpart;
564   }
565
566   if ( @dup_ccphonenum ) {
567
568     my $exports = FS::part_export::export_info('svc_phone');
569     my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
570
571     foreach my $part_export ( $part_svc->part_export ) {
572
573       #this will catch to the same exact export
574       my @svcparts = map { $_->svcpart } $part_export->export_svc;
575
576       $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
577         foreach @svcparts;
578
579     }
580
581     foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
582       my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
583       if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
584         return "duplicate phone number ".
585                $self->countrycode. ' '. $self->phonenum.
586                ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
587                " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
588       }
589     }
590
591   }
592
593   return '';
594
595 }
596
597 =item check_pin
598
599 Checks the supplied PIN against the PIN in the database.  Returns true for a
600 sucessful authentication, false if no match.
601
602 =cut
603
604 sub check_pin {
605   my($self, $check_pin) = @_;
606   length($self->pin) && $check_pin eq $self->pin;
607 }
608
609 =item radius_reply
610
611 =cut
612
613 sub radius_reply {
614   my $self = shift;
615   #XXX Session-Timeout!  holy shit, need rlm_perl to ask for this in realtime
616   ();
617 }
618
619 =item radius_check
620
621 =cut
622
623 sub radius_check {
624   my $self = shift;
625   my %check = ();
626
627   my $conf = new FS::Conf;
628
629   $check{'User-Password'} = $conf->config('svc_phone-radius-default_password');
630
631   %check;
632 }
633
634 sub radius_groups {
635   ();
636 }
637
638 =item phone_device
639
640 Returns any FS::phone_device records associated with this service.
641
642 =cut
643
644 sub phone_device {
645   my $self = shift;
646   qsearch('phone_device', { 'svcnum' => $self->svcnum } );
647 }
648
649 #override location_Mixin version cause we want to try the cust_pkg location
650 #in between us and cust_main
651 # XXX what to do in the unlinked case???  return a pseudo-object that returns
652 # empty fields?
653 sub cust_location_or_main {
654   my $self = shift;
655   return $self->cust_location if $self->locationnum;
656   my $cust_pkg = $self->cust_svc->cust_pkg;
657   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
658 }
659
660 =item psearch_cdrs OPTIONS
661
662 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records 
663 associated with this service.  By default, "associated with" means that 
664 either the "src" or the "charged_party" field of the CDR matches the 
665 "phonenum" field of the service.  To access the CDRs themselves, call
666 "->fetch" on the resulting object.
667
668 =over 2
669
670 Accepts the following options:
671
672 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
673
674 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
675
676 =item inbound => 1: Return CDRs for inbound calls.  With "status", will filter 
677 on inbound processing status.
678
679 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
680 with the chosen prefix.
681
682 =item begin, end: Start and end of a date range, as unix timestamp.
683
684 =item cdrtypenum: Only return CDRs with this type.
685
686 =item calltypenum: Only return CDRs with this call type.
687
688 =item disable_src => 1: Only match on "charged_party", not "src".
689
690 =item nonzero: Only return CDRs where duration > 0.
691
692 =item by_svcnum: not supported for svc_phone
693
694 =item billsec_sum: Instead of returning all of the CDRs, return a single
695 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over 
696 the entire result set.
697
698 =back
699
700 =cut
701
702 sub psearch_cdrs {
703
704   my($self, %options) = @_;
705   my @fields;
706   my %hash;
707   my @where;
708
709   if ( $options{'inbound'} ) {
710
711     @fields = ( 'dst' );
712     if ( exists($options{'status'}) ) {
713       my $status = $options{'status'};
714       if ( $status ) {
715         push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
716           'WHERE cdr.acctid = cdr_termination.acctid '.
717           "AND cdr_termination.status = '$status' ". #quoting kludge
718           'AND cdr_termination.termpart = 1 )';
719       } else {
720         push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
721           'WHERE cdr.acctid = cdr_termination.acctid '.
722           'AND cdr_termination.termpart = 1 )';
723       }
724     }
725
726   } else {
727
728     @fields = ( 'charged_party' );
729     push @fields, 'src' if !$options{'disable_src'};
730     $hash{'freesidestatus'} = $options{'status'}
731       if exists($options{'status'});
732   }
733
734   if ($options{'cdrtypenum'}) {
735     $hash{'cdrtypenum'} = $options{'cdrtypenum'};
736   }
737   if ($options{'calltypenum'}) {
738     $hash{'calltypenum'} = $options{'calltypenum'};
739   }
740   
741   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
742
743   my $number = $self->phonenum;
744
745   my $prefix = $options{'default_prefix'};
746
747   my @orwhere =  map " $_ = '$number'        ", @fields;
748   push @orwhere, map " $_ = '$prefix$number' ", @fields
749     if defined($prefix) && length($prefix);
750   if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
751     push @orwhere, map " $_ = '$1$number' ", @fields
752   }
753
754   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
755
756   if ( $options{'begin'} ) {
757     push @where, 'startdate >= '. $options{'begin'};
758   }
759   if ( $options{'end'} ) {
760     push @where, 'startdate < '.  $options{'end'};
761   }
762   if ( $options{'nonzero'} ) {
763     push @where, 'duration > 0';
764   }
765
766   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
767
768   psearch( {
769       'table'      => 'cdr',
770       'hashref'    => \%hash,
771       'extra_sql'  => $extra_sql,
772       'order_by'   => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
773       'select'     => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
774   } );
775 }
776
777 =item get_cdrs (DEPRECATED)
778
779 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a 
780 single list.  Arguments are the same as for psearch_cdrs.  This can take 
781 an unreasonably large amount of memory and is best avoided.
782
783 =cut
784
785 sub get_cdrs {
786   my $self = shift;
787   my $psearch = $self->psearch_cdrs(@_);
788   qsearch ( $psearch->{query} )
789 }
790
791 =item sum_cdrs
792
793 Takes the same options as psearch_cdrs, but returns a single row containing
794 "count" (the number of CDRs) and the sums of the following fields: duration,
795 billsec, rated_price, rated_seconds, rated_minutes.
796
797 Note that if any calls are not rated, their rated_* fields will be null.
798 If you want to use those fields, pass the 'status' option to limit to 
799 calls that have been rated.  This is intentional; please don't "fix" it.
800
801 =cut
802
803 sub sum_cdrs {
804   my $self = shift;
805   my $psearch = $self->psearch_cdrs(@_);
806   $psearch->{query}->{'select'} = join(',',
807     'COUNT(*) AS count',
808     map { "SUM($_) AS $_" }
809       qw(duration billsec rated_price rated_seconds rated_minutes)
810   );
811   # hack
812   $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
813   qsearchs ( $psearch->{query} );
814 }
815
816 =back
817
818 =head1 BUGS
819
820 =head1 SEE ALSO
821
822 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
823 L<FS::cust_pkg>, schema.html from the base documentation.
824
825 =cut
826
827 1;
828