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