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