NG auth: autocreate records for external users, RT#21563
[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          && ( ! $self->locationnum || $self->locationnum == -1 ) ) {
293     my $error = $options{'cust_location'}->insert;
294     if ( $error ) {
295       $dbh->rollback if $oldAutoCommit;
296       return "inserting cust_location (transaction rolled back): $error";
297     }
298     $self->locationnum( $options{'cust_location'}->locationnum );
299   }
300   #what about on-the-fly edits?  if the ui supports it?
301
302   my $error = $self->SUPER::insert(%options);
303   if ( $error ) {
304     $dbh->rollback if $oldAutoCommit;
305     return $error;
306   }
307
308   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
309   '';
310
311 }
312
313 =item delete
314
315 Delete this record from the database.
316
317 =cut
318
319 sub delete {
320   my $self = shift;
321
322   local $SIG{HUP} = 'IGNORE';
323   local $SIG{INT} = 'IGNORE';
324   local $SIG{QUIT} = 'IGNORE';
325   local $SIG{TERM} = 'IGNORE';
326   local $SIG{TSTP} = 'IGNORE';
327   local $SIG{PIPE} = 'IGNORE';
328
329   my $oldAutoCommit = $FS::UID::AutoCommit;
330   local $FS::UID::AutoCommit = 0;
331   my $dbh = dbh;
332
333   foreach my $phone_device ( $self->phone_device ) {
334     my $error = $phone_device->delete;
335     if ( $error ) {
336       $dbh->rollback if $oldAutoCommit;
337       return $error;
338     }
339   }
340
341   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
342   foreach my $phone_avail ( @phone_avail ) {
343     $phone_avail->svcnum('');
344     my $error = $phone_avail->replace;
345     if ( $error ) {
346       $dbh->rollback if $oldAutoCommit;
347       return $error;
348     }
349   }
350
351   my $error = $self->SUPER::delete;
352   if ( $error ) {
353     $dbh->rollback if $oldAutoCommit;
354     return $error;
355   }
356
357   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
358   '';
359
360 }
361
362 # the delete method can be inherited from FS::Record
363
364 =item replace OLD_RECORD
365
366 Replaces the OLD_RECORD with this one in the database.  If there is an error,
367 returns the error, otherwise returns false.
368
369 =cut
370
371 sub replace {
372   my $new = shift;
373
374   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
375               ? shift
376               : $new->replace_old;
377
378   my %options = @_;
379
380   if ( $DEBUG ) {
381     warn "[$me] replacing $old with $new\n".
382          "\nwith options: ". Dumper(%options);
383   }
384
385   local $SIG{HUP} = 'IGNORE';
386   local $SIG{INT} = 'IGNORE';
387   local $SIG{QUIT} = 'IGNORE';
388   local $SIG{TERM} = 'IGNORE';
389   local $SIG{TSTP} = 'IGNORE';
390   local $SIG{PIPE} = 'IGNORE';
391
392   my $oldAutoCommit = $FS::UID::AutoCommit;
393   local $FS::UID::AutoCommit = 0;
394   my $dbh = dbh;
395
396   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
397   #make it more of a base class than a mixin... :)
398   if ( $options{'cust_location'}
399          && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
400     my $error = $options{'cust_location'}->insert;
401     if ( $error ) {
402       $dbh->rollback if $oldAutoCommit;
403       return "inserting cust_location (transaction rolled back): $error";
404     }
405     $new->locationnum( $options{'cust_location'}->locationnum );
406   }
407   #what about on-the-fly edits?  if the ui supports it?
408
409   # LNP data validation
410  return 'Invalid LNP status' # if someone does really stupid stuff
411     if (  ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
412         || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
413         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
414         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
415         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
416         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
417         || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
418         );
419
420   my $error = $new->SUPER::replace($old, %options);
421   if ( $error ) {
422     $dbh->rollback if $oldAutoCommit;
423     return $error if $error;
424   }
425
426   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
427   ''; #no error
428 }
429
430 =item suspend
431
432 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
433
434 =item unsuspend
435
436 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
437
438 =item cancel
439
440 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
441
442 =item check
443
444 Checks all fields to make sure this is a valid phone number.  If there is
445 an error, returns the error, otherwise returns false.  Called by the insert
446 and replace methods.
447
448 =cut
449
450 # the check method should currently be supplied - FS::Record contains some
451 # data checking routines
452
453 sub check {
454   my $self = shift;
455
456   my $conf = new FS::Conf;
457
458   my $phonenum = $self->phonenum;
459   my $phonenum_check_method;
460   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
461     $phonenum =~ s/\W//g;
462     $phonenum_check_method = 'ut_alpha';
463   } else {
464     $phonenum =~ s/\D//g;
465     $phonenum_check_method = 'ut_number';
466   }
467   $self->phonenum($phonenum);
468
469   $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
470
471   my $error = 
472     $self->ut_numbern('svcnum')
473     || $self->ut_numbern('countrycode')
474     || $self->$phonenum_check_method('phonenum')
475     || $self->ut_numbern('sim_imsi')
476     || $self->ut_anything('sip_password')
477     || $self->ut_numbern('pin')
478     || $self->ut_textn('phone_name')
479     || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx',    'svcnum' )
480     || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
481     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
482     || $self->ut_numbern('forwarddst')
483     || $self->ut_textn('email')
484     || $self->ut_numbern('lrn')
485     || $self->ut_numbern('lnp_desired_due_date')
486     || $self->ut_numbern('lnp_due_date')
487     || $self->ut_textn('lnp_other_provider')
488     || $self->ut_textn('lnp_other_provider_account')
489     || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
490                                 'native', 'portin-reject', 'portout-reject'])
491     || $self->ut_enumn('portable', ['','Y'])
492     || $self->ut_textn('lnp_reject_reason')
493   ;
494   return $error if $error;
495
496   return 'Illegal IMSI (not 14-15 digits)' #shorter?
497     if length($self->sim_imsi)
498     && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
499
500     # LNP data validation
501     return 'Cannot set LNP fields: no LNP in progress'
502         if ( ($self->lnp_desired_due_date || $self->lnp_due_date 
503             || $self->lnp_other_provider || $self->lnp_other_provider_account
504             || $self->lnp_reject_reason) 
505             && (!$self->lnp_status || $self->lnp_status eq 'native') );
506     return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
507         if ($self->lnp_reject_reason && (!$self->lnp_status 
508                             || $self->lnp_status !~ /^port(in|out)-reject$/) );
509     return 'Cannot port-out a non-portable number' 
510         if (!$self->portable && $self->lnp_status eq 'portingout');
511
512
513   return 'Name ('. $self->phone_name.
514          ") is longer than $phone_name_max characters"
515     if $phone_name_max && length($self->phone_name) > $phone_name_max;
516
517   $self->countrycode(1) unless $self->countrycode;
518
519   unless ( length($self->pin) ) {
520     my $random_pin = $conf->config('svc_phone-random_pin');
521     if ( $random_pin =~ /^\d+$/ ) {
522       $self->pin(
523         join('', map int(rand(10)), 0..($random_pin-1))
524       );
525     }
526   }
527
528   unless ( length($self->sip_password) ) { # option for this?
529
530     $self->sip_password(
531       join('', map $pw_set[ int(rand $#pw_set) ], (0..16) )
532     );
533
534   }
535
536   $self->SUPER::check;
537 }
538
539 =item _check duplicate
540
541 Internal method to check for duplicate phone numers.
542
543 =cut
544
545 #false laziness w/svc_acct.pm's _check_duplicate.
546 sub _check_duplicate {
547   my $self = shift;
548
549   my $global_unique = $conf->config('global_unique-phonenum') || 'none';
550   return '' if $global_unique eq 'disabled';
551
552   $self->lock_table;
553
554   my @dup_ccphonenum =
555     grep { !$self->svcnum || $_->svcnum != $self->svcnum }
556     qsearch( 'svc_phone', {
557       'countrycode' => $self->countrycode,
558       'phonenum'    => $self->phonenum,
559     });
560
561   return gettext('phonenum_in_use')
562     if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
563
564   my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
565   unless ( $part_svc ) {
566     return 'unknown svcpart '. $self->svcpart;
567   }
568
569   if ( @dup_ccphonenum ) {
570
571     my $exports = FS::part_export::export_info('svc_phone');
572     my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
573
574     foreach my $part_export ( $part_svc->part_export ) {
575
576       #this will catch to the same exact export
577       my @svcparts = map { $_->svcpart } $part_export->export_svc;
578
579       $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
580         foreach @svcparts;
581
582     }
583
584     foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
585       my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
586       if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
587         return "duplicate phone number ".
588                $self->countrycode. ' '. $self->phonenum.
589                ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
590                " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
591       }
592     }
593
594   }
595
596   return '';
597
598 }
599
600 =item check_pin
601
602 Checks the supplied PIN against the PIN in the database.  Returns true for a
603 sucessful authentication, false if no match.
604
605 =cut
606
607 sub check_pin {
608   my($self, $check_pin) = @_;
609   length($self->pin) && $check_pin eq $self->pin;
610 }
611
612 =item radius_reply
613
614 =cut
615
616 sub radius_reply {
617   my $self = shift;
618   #XXX Session-Timeout!  holy shit, need rlm_perl to ask for this in realtime
619   ();
620 }
621
622 =item radius_check
623
624 =cut
625
626 sub radius_check {
627   my $self = shift;
628   my %check = ();
629
630   my $conf = new FS::Conf;
631
632   $check{'User-Password'} = $conf->config('svc_phone-radius-default_password');
633
634   %check;
635 }
636
637 sub radius_groups {
638   ();
639 }
640
641 =item phone_device
642
643 Returns any FS::phone_device records associated with this service.
644
645 =cut
646
647 sub phone_device {
648   my $self = shift;
649   qsearch('phone_device', { 'svcnum' => $self->svcnum } );
650 }
651
652 #override location_Mixin version cause we want to try the cust_pkg location
653 #in between us and cust_main
654 # XXX what to do in the unlinked case???  return a pseudo-object that returns
655 # empty fields?
656 sub cust_location_or_main {
657   my $self = shift;
658   return $self->cust_location if $self->locationnum;
659   my $cust_pkg = $self->cust_svc->cust_pkg;
660   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
661 }
662
663 =item psearch_cdrs OPTIONS
664
665 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records 
666 associated with this service.  By default, "associated with" means that 
667 either the "src" or the "charged_party" field of the CDR matches the 
668 "phonenum" field of the service.  To access the CDRs themselves, call
669 "->fetch" on the resulting object.
670
671 =over 2
672
673 Accepts the following options:
674
675 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
676
677 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
678
679 =item inbound => 1: Return CDRs for inbound calls.  With "status", will filter 
680 on inbound processing status.
681
682 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
683 with the chosen prefix.
684
685 =item begin, end: Start and end of a date range, as unix timestamp.
686
687 =item cdrtypenum: Only return CDRs with this type number.
688
689 =item disable_src => 1: Only match on "charged_party", not "src".
690
691 =item nonzero: Only return CDRs where duration > 0.
692
693 =item by_svcnum: not supported for svc_phone
694
695 =item billsec_sum: Instead of returning all of the CDRs, return a single
696 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over 
697 the entire result set.
698
699 =back
700
701 =cut
702
703 sub psearch_cdrs {
704
705   my($self, %options) = @_;
706   my @fields;
707   my %hash;
708   my @where;
709
710   if ( $options{'inbound'} ) {
711
712     @fields = ( 'dst' );
713     if ( exists($options{'status'}) ) {
714       my $status = $options{'status'};
715       if ( $status ) {
716         push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
717           'WHERE cdr.acctid = cdr_termination.acctid '.
718           "AND cdr_termination.status = '$status' ". #quoting kludge
719           'AND cdr_termination.termpart = 1 )';
720       } else {
721         push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
722           'WHERE cdr.acctid = cdr_termination.acctid '.
723           'AND cdr_termination.termpart = 1 )';
724       }
725     }
726
727   } else {
728
729     @fields = ( 'charged_party' );
730     push @fields, 'src' if !$options{'disable_src'};
731     $hash{'freesidestatus'} = $options{'status'}
732       if exists($options{'status'});
733   }
734
735   if ($options{'cdrtypenum'}) {
736     $hash{'cdrtypenum'} = $options{'cdrtypenum'};
737   }
738   
739   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
740
741   my $number = $self->phonenum;
742
743   my $prefix = $options{'default_prefix'};
744
745   my @orwhere =  map " $_ = '$number'        ", @fields;
746   push @orwhere, map " $_ = '$prefix$number' ", @fields
747     if defined($prefix) && length($prefix);
748   if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
749     push @orwhere, map " $_ = '$1$number' ", @fields
750   }
751
752   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
753
754   if ( $options{'begin'} ) {
755     push @where, 'startdate >= '. $options{'begin'};
756   }
757   if ( $options{'end'} ) {
758     push @where, 'startdate < '.  $options{'end'};
759   }
760   if ( $options{'nonzero'} ) {
761     push @where, 'duration > 0';
762   }
763
764   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
765
766   psearch( {
767       'table'      => 'cdr',
768       'hashref'    => \%hash,
769       'extra_sql'  => $extra_sql,
770       'order_by'   => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
771       'select'     => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
772   } );
773 }
774
775 =item get_cdrs (DEPRECATED)
776
777 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a 
778 single list.  Arguments are the same as for psearch_cdrs.  This can take 
779 an unreasonably large amount of memory and is best avoided.
780
781 =cut
782
783 sub get_cdrs {
784   my $self = shift;
785   my $psearch = $self->psearch_cdrs(@_);
786   qsearch ( $psearch->{query} )
787 }
788
789 =item sum_cdrs
790
791 Takes the same options as psearch_cdrs, but returns a single row containing
792 "count" (the number of CDRs) and the sums of the following fields: duration,
793 billsec, rated_price, rated_seconds, rated_minutes.
794
795 Note that if any calls are not rated, their rated_* fields will be null.
796 If you want to use those fields, pass the 'status' option to limit to 
797 calls that have been rated.  This is intentional; please don't "fix" it.
798
799 =cut
800
801 sub sum_cdrs {
802   my $self = shift;
803   my $psearch = $self->psearch_cdrs(@_);
804   $psearch->{query}->{'select'} = join(',',
805     'COUNT(*) AS count',
806     map { "SUM($_) AS $_" }
807       qw(duration billsec rated_price rated_seconds rated_minutes)
808   );
809   # hack
810   $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
811   qsearchs ( $psearch->{query} );
812 }
813
814 =back
815
816 =head1 BUGS
817
818 =head1 SEE ALSO
819
820 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
821 L<FS::cust_pkg>, schema.html from the base documentation.
822
823 =cut
824
825 1;
826