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