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 );
7 use Scalar::Util qw( blessed );
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::PagedSearch qw( psearch );
11 use FS::Msgcat qw(gettext);
16 use FS::cust_location;
19 $me = '[' . __PACKAGE__ . ']';
23 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
25 #ask FS::UID to run this stuff for us later
26 FS::UID->install_callback( sub {
28 $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
34 FS::svc_phone - Object methods for svc_phone records
40 $record = new FS::svc_phone \%hash;
41 $record = new FS::svc_phone { 'column' => 'value' };
43 $error = $record->insert;
45 $error = $new_record->replace($old_record);
47 $error = $record->delete;
49 $error = $record->check;
51 $error = $record->suspend;
53 $error = $record->unsuspend;
55 $error = $record->cancel;
59 An FS::svc_phone object represents a phone number. FS::svc_phone inherits
60 from FS::Record. The following fields are currently supported:
74 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
86 Optional svcnum from svc_pbx
90 Forwarding destination
94 Email address for virtual fax (fax-to-email) services
98 LNP Status (can be null, native, portedin, portingin, portin-reject,
99 portingout, portout-reject)
105 =item lnp_desired_due_date
109 =item lnp_other_provider
111 If porting the number in or out, name of the losing or winning provider,
114 =item lnp_other_provider_account
116 Account number of other provider. See lnp_other_provider.
118 =item lnp_reject_reason
120 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
121 optional reject reason.
131 Creates a new phone number. To add the number to the database, see L<"insert">.
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.
138 # the new method can be inherited from FS::Record, if a table method is defined
141 my %dis2 = ( disable_inventory=>1, disable_select=>1 );
143 'name' => 'Phone number',
144 'sorts' => 'phonenum',
145 'display_weight' => 60,
146 'cancel_weight' => 80,
148 'svcnum' => 'Service',
149 'countrycode' => { label => 'Country code',
151 disable_inventory => 1,
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',
158 disable_inventory => 1,
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
171 select_table => 'svc_domain',
172 select_key => 'svcnum',
173 select_label => 'domain',
174 disable_inventory => 1,
176 'sms_carrierid' => { label => 'SMS Carrier',
178 select_table => 'cdr_carrier',
179 select_key => 'carrierid',
180 select_label => 'carriername',
181 disable_inventory => 1,
183 'sms_account' => { label => 'SMS Carrier Account', },
184 'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
186 label => 'E911 location',
187 disable_inventory => 1,
190 'forwarddst' => { label => 'Forward Destination',
193 'email' => { label => 'Email',
196 'lnp_status' => { label => 'LNP Status',
197 type => 'select-lnp_status.html',
200 'lnp_reject_reason' => {
201 label => 'LNP Reject Reason',
204 'portable' => { label => 'Portable?', %dis2, },
205 'lrn' => { label => 'LRN',
206 disable_inventory => 1,
208 'lnp_desired_due_date' =>
209 { label => 'LNP Desired Due Date', %dis2 },
211 { label => 'LNP Due Date', %dis2 },
212 'lnp_other_provider' =>
213 { label => 'LNP Other Provider',
214 disable_inventory => 1,
216 'lnp_other_provider_account' =>
217 { label => 'LNP Other Provider Account #',
224 sub table { 'svc_phone'; }
226 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
228 =item search_sql STRING
230 Class method which returns an SQL fragment to search for the given string.
235 my( $class, $string ) = @_;
237 my $conf = new FS::Conf;
239 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
245 my $ccode = ( $conf->exists('default_phone_countrycode')
246 && $conf->config('default_phone_countrycode')
248 ? $conf->config('default_phone_countrycode')
251 $string =~ s/^$ccode//;
253 $class->search_sql_field('phonenum', $string );
258 Returns the phone number.
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;
273 Adds this phone number to the database. If there is an error, returns the
274 error, otherwise returns false.
283 warn "[$me] insert called on $self: ". Dumper($self).
284 "\nwith options: ". Dumper(%options);
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';
294 my $oldAutoCommit = $FS::UID::AutoCommit;
295 local $FS::UID::AutoCommit = 0;
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;
303 $dbh->rollback if $oldAutoCommit;
304 return "inserting cust_location (transaction rolled back): $error";
306 $self->locationnum( $options{'cust_location'}->locationnum );
308 #what about on-the-fly edits? if the ui supports it?
310 my $error = $self->SUPER::insert(%options);
312 $dbh->rollback if $oldAutoCommit;
316 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
323 Delete this record from the database.
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';
337 my $oldAutoCommit = $FS::UID::AutoCommit;
338 local $FS::UID::AutoCommit = 0;
341 foreach my $phone_device ( $self->phone_device ) {
342 my $error = $phone_device->delete;
344 $dbh->rollback if $oldAutoCommit;
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;
354 $dbh->rollback if $oldAutoCommit;
359 my $error = $self->SUPER::delete;
361 $dbh->rollback if $oldAutoCommit;
365 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
370 # the delete method can be inherited from FS::Record
372 =item replace OLD_RECORD
374 Replaces the OLD_RECORD with this one in the database. If there is an error,
375 returns the error, otherwise returns false.
382 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
389 warn "[$me] replacing $old with $new\n".
390 "\nwith options: ". Dumper(%options);
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';
400 my $oldAutoCommit = $FS::UID::AutoCommit;
401 local $FS::UID::AutoCommit = 0;
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;
410 $dbh->rollback if $oldAutoCommit;
411 return "inserting cust_location (transaction rolled back): $error";
413 $new->locationnum( $options{'cust_location'}->locationnum );
415 #what about on-the-fly edits? if the ui supports it?
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')
428 my $error = $new->SUPER::replace($old, %options);
430 $dbh->rollback if $oldAutoCommit;
431 return $error if $error;
434 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
440 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
444 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
448 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
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
458 # the check method should currently be supplied - FS::Record contains some
459 # data checking routines
464 my $conf = new FS::Conf;
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';
472 $phonenum =~ s/\D//g;
473 $phonenum_check_method = 'ut_number';
475 $self->phonenum($phonenum);
477 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
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')
505 return $error if $error;
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 );
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');
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;
528 $self->countrycode(1) unless $self->countrycode;
530 unless ( length($self->pin) ) {
531 my $random_pin = $conf->config('svc_phone-random_pin');
532 if ( defined($random_pin) && $random_pin =~ /^\d+$/ ) {
534 join('', map int(rand(10)), 0..($random_pin-1))
539 unless ( length($self->sip_password) ) { # option for this?
542 join('', map $pw_set[ int(rand $#pw_set) ], (0..16) )
550 =item _check duplicate
552 Internal method to check for duplicate phone numers.
556 #false laziness w/svc_acct.pm's _check_duplicate.
557 sub _check_duplicate {
560 my $global_unique = $conf->config('global_unique-phonenum') || 'none';
561 return '' if $global_unique eq 'disabled';
566 grep { !$self->svcnum || $_->svcnum != $self->svcnum }
567 qsearch( 'svc_phone', {
568 'countrycode' => $self->countrycode,
569 'phonenum' => $self->phonenum,
572 return gettext('phonenum_in_use')
573 if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
575 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
576 unless ( $part_svc ) {
577 return 'unknown svcpart '. $self->svcpart;
580 if ( @dup_ccphonenum ) {
582 my $exports = FS::part_export::export_info('svc_phone');
583 my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
585 foreach my $part_export ( $part_svc->part_export ) {
587 #this will catch to the same exact export
588 my @svcparts = map { $_->svcpart } $part_export->export_svc;
590 $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
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};
613 Checks the supplied PIN against the PIN in the database. Returns true for a
614 sucessful authentication, false if no match.
619 my($self, $check_pin) = @_;
620 length($self->pin) && $check_pin eq $self->pin;
629 #XXX Session-Timeout! holy shit, need rlm_perl to ask for this in realtime
641 my $conf = new FS::Conf;
643 $check{'User-Password'} = $conf->config('svc_phone-radius-default_password');
652 =item sms_cdr_carrier
656 sub sms_cdr_carrier {
658 return '' unless $self->sms_carrierid;
659 qsearchs('cdr_carrier', { 'carrierid' => $self->sms_carrierid } );
662 =item sms_carriername
666 sub sms_carriername {
668 my $cdr_carrier = $self->sms_cdr_carrier or return '';
669 $cdr_carrier->carriername;
674 Returns any FS::phone_device records associated with this service.
680 qsearch('phone_device', { 'svcnum' => $self->svcnum } );
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
687 sub cust_location_or_main {
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 : '';
694 =item psearch_cdrs OPTIONS
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.
704 Accepts the following options:
706 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
708 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
710 =item inbound => 1: Return CDRs for inbound calls. With "status", will filter
711 on inbound processing status.
713 =item default_prefix => "XXX": Also accept the phone number of the service prepended
714 with the chosen prefix.
716 =item begin, end: Start and end of a date range, as unix timestamp.
718 =item cdrtypenum: Only return CDRs with this type.
720 =item calltypenum: Only return CDRs with this call type.
722 =item disable_src => 1: Only match on "charged_party", not "src".
724 =item nonzero: Only return CDRs where duration > 0.
726 =item by_svcnum: not supported for svc_phone
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.
738 my($self, %options) = @_;
743 if ( $options{'inbound'} ) {
746 if ( exists($options{'status'}) ) {
747 my $status = $options{'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 )';
754 push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
755 'WHERE cdr.acctid = cdr_termination.acctid '.
756 'AND cdr_termination.termpart = 1 )';
762 @fields = ( 'charged_party' );
763 push @fields, 'src' if !$options{'disable_src'};
764 $hash{'freesidestatus'} = $options{'status'}
765 if exists($options{'status'});
768 if ($options{'cdrtypenum'}) {
769 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
771 if ($options{'calltypenum'}) {
772 $hash{'calltypenum'} = $options{'calltypenum'};
775 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
777 my $number = $self->phonenum;
779 my $prefix = $options{'default_prefix'};
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
788 push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
790 if ( $options{'begin'} ) {
791 push @where, 'startdate >= '. $options{'begin'};
793 if ( $options{'end'} ) {
794 push @where, 'startdate < '. $options{'end'};
796 if ( $options{'nonzero'} ) {
797 push @where, 'duration > 0';
800 my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
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' : '*',
811 =item get_cdrs (DEPRECATED)
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.
821 my $psearch = $self->psearch_cdrs(@_);
822 qsearch ( $psearch->{query} )
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.
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.
839 my $psearch = $self->psearch_cdrs(@_);
840 $psearch->{query}->{'select'} = join(',',
842 map { "SUM($_) AS $_" }
843 qw(duration billsec rated_price rated_seconds rated_minutes)
846 $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
847 qsearchs ( $psearch->{query} );
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.