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