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