2 use base qw( FS::svc_Domain_Mixin FS::svc_PBX_Mixin
8 use vars qw( $DEBUG $me @pw_set $conf $phone_name_max
9 $passwordmin $passwordmax
12 use Scalar::Util qw( blessed );
13 use List::Util qw( min );
15 use FS::Record qw( qsearch qsearchs dbh );
16 use FS::PagedSearch qw( psearch );
17 use FS::Msgcat qw(gettext);
21 use FS::cust_location;
24 $me = '[' . __PACKAGE__ . ']';
28 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
30 #ask FS::UID to run this stuff for us later
31 FS::UID->install_callback( sub {
33 $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
34 $passwordmin = $conf->config('sip_passwordmin') || 0;
35 $passwordmax = $conf->config('sip_passwordmax') || 80;
41 FS::svc_phone - Object methods for svc_phone records
47 $record = new FS::svc_phone \%hash;
48 $record = new FS::svc_phone { 'column' => 'value' };
50 $error = $record->insert;
52 $error = $new_record->replace($old_record);
54 $error = $record->delete;
56 $error = $record->check;
58 $error = $record->suspend;
60 $error = $record->unsuspend;
62 $error = $record->cancel;
66 An FS::svc_phone object represents a phone number. FS::svc_phone inherits
67 from FS::Record. The following fields are currently supported:
81 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
93 Optional svcnum from svc_pbx
97 Forwarding destination
101 Email address for virtual fax (fax-to-email) services
105 LNP Status (can be null, native, portedin, portingin, portin-reject,
106 portingout, portout-reject)
112 =item lnp_desired_due_date
116 =item lnp_other_provider
118 If porting the number in or out, name of the losing or winning provider,
121 =item lnp_other_provider_account
123 Account number of other provider. See lnp_other_provider.
125 =item lnp_reject_reason
127 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
128 optional reject reason.
138 Creates a new phone number. To add the number to the database, see L<"insert">.
140 Note that this stores the hash reference, not a distinct copy of the hash it
141 points to. You can ask the object for a copy with the I<hash> method.
145 # the new method can be inherited from FS::Record, if a table method is defined
148 my %dis2 = ( disable_inventory=>1, disable_select=>1 );
150 'name' => 'Phone number',
151 'sorts' => 'phonenum',
152 'display_weight' => 60,
153 'cancel_weight' => 80,
155 'svcnum' => 'Service',
156 'countrycode' => { label => 'Country code',
158 disable_inventory => 1,
161 'phonenum' => 'Phone number',
162 'sim_imsi' => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
163 'pin' => { label => 'Voicemail PIN', #'Personal Identification Number',
165 disable_inventory => 1,
168 'sip_password' => 'SIP password',
169 'phone_name' => 'Name',
170 'pbxsvc' => { label => 'PBX',
171 type => 'select-svc_pbx.html',
172 disable_inventory => 1,
173 disable_select => 1, #UI wonky, pry works otherwise
178 select_table => 'svc_domain',
179 select_key => 'svcnum',
180 select_label => 'domain',
181 disable_inventory => 1,
183 'sms_carrierid' => { label => 'SMS Carrier',
185 select_table => 'cdr_carrier',
186 select_key => 'carrierid',
187 select_label => 'carriername',
188 disable_inventory => 1,
190 'sms_account' => { label => 'SMS Carrier Account', },
191 'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
193 label => 'E911 location',
194 disable_inventory => 1,
197 'forwarddst' => { label => 'Forward Destination',
200 'email' => { label => 'Email',
203 'lnp_status' => { label => 'LNP Status',
204 type => 'select-lnp_status.html',
207 'lnp_reject_reason' => {
208 label => 'LNP Reject Reason',
211 'portable' => { label => 'Portable?', %dis2, },
212 'lrn' => { label => 'LRN',
213 disable_inventory => 1,
215 'lnp_desired_due_date' =>
216 { label => 'LNP Desired Due Date', %dis2 },
218 { label => 'LNP Due Date', %dis2 },
219 'lnp_other_provider' =>
220 { label => 'LNP Other Provider',
221 disable_inventory => 1,
223 'lnp_other_provider_account' =>
224 { label => 'LNP Other Provider Account #',
231 sub table { 'svc_phone'; }
233 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
235 =item search_sql STRING
237 Class method which returns an SQL fragment to search for the given string.
242 my( $class, $string ) = @_;
244 #my $conf = new FS::Conf;
246 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
252 my $ccode = ( $conf->exists('default_phone_countrycode')
253 && $conf->config('default_phone_countrycode')
255 ? $conf->config('default_phone_countrycode')
258 $string =~ s/^$ccode//;
260 $class->search_sql_field('phonenum', $string );
265 Returns the phone number.
271 my $phonenum = $self->phonenum; #XXX format it better
272 my $label = $phonenum;
273 $label .= '@'.$self->domain if $self->domsvc;
274 $label .= ' ('.$self->phone_name.')' if $self->phone_name;
280 Adds this phone number to the database. If there is an error, returns the
281 error, otherwise returns false.
290 warn "[$me] insert called on $self: ". Dumper($self).
291 "\nwith options: ". Dumper(%options);
294 local $SIG{HUP} = 'IGNORE';
295 local $SIG{INT} = 'IGNORE';
296 local $SIG{QUIT} = 'IGNORE';
297 local $SIG{TERM} = 'IGNORE';
298 local $SIG{TSTP} = 'IGNORE';
299 local $SIG{PIPE} = 'IGNORE';
301 my $oldAutoCommit = $FS::UID::AutoCommit;
302 local $FS::UID::AutoCommit = 0;
305 #false laziness w/cust_pkg.pm... move this to location_Mixin? that would
306 #make it more of a base class than a mixin... :)
307 if ( $options{'cust_location'} ) {
308 my $error = $options{'cust_location'}->find_or_insert;
310 $dbh->rollback if $oldAutoCommit;
311 return "inserting cust_location (transaction rolled back): $error";
313 $self->locationnum( $options{'cust_location'}->locationnum );
315 #what about on-the-fly edits? if the ui supports it?
317 my $error = $self->SUPER::insert(%options);
319 $dbh->rollback if $oldAutoCommit;
323 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
330 Delete this record from the database.
337 local $SIG{HUP} = 'IGNORE';
338 local $SIG{INT} = 'IGNORE';
339 local $SIG{QUIT} = 'IGNORE';
340 local $SIG{TERM} = 'IGNORE';
341 local $SIG{TSTP} = 'IGNORE';
342 local $SIG{PIPE} = 'IGNORE';
344 my $oldAutoCommit = $FS::UID::AutoCommit;
345 local $FS::UID::AutoCommit = 0;
348 foreach my $phone_device ( $self->phone_device ) {
349 my $error = $phone_device->delete;
351 $dbh->rollback if $oldAutoCommit;
356 my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
357 foreach my $phone_avail ( @phone_avail ) {
358 $phone_avail->svcnum('');
359 my $error = $phone_avail->replace;
361 $dbh->rollback if $oldAutoCommit;
366 my $error = $self->SUPER::delete;
368 $dbh->rollback if $oldAutoCommit;
372 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
377 =item replace OLD_RECORD
379 Replaces the OLD_RECORD with this one in the database. If there is an error,
380 returns the error, otherwise returns false.
387 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
394 warn "[$me] replacing $old with $new\n".
395 "\nwith options: ". Dumper(%options);
398 local $SIG{HUP} = 'IGNORE';
399 local $SIG{INT} = 'IGNORE';
400 local $SIG{QUIT} = 'IGNORE';
401 local $SIG{TERM} = 'IGNORE';
402 local $SIG{TSTP} = 'IGNORE';
403 local $SIG{PIPE} = 'IGNORE';
405 my $oldAutoCommit = $FS::UID::AutoCommit;
406 local $FS::UID::AutoCommit = 0;
409 #false laziness w/cust_pkg.pm... move this to location_Mixin? that would
410 #make it more of a base class than a mixin... :)
411 if ( $options{'cust_location'}
412 && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
413 my $error = $options{'cust_location'}->insert;
415 $dbh->rollback if $oldAutoCommit;
416 return "inserting cust_location (transaction rolled back): $error";
418 $new->locationnum( $options{'cust_location'}->locationnum );
420 #what about on-the-fly edits? if the ui supports it?
422 # LNP data validation
423 return 'Invalid LNP status' # if someone does really stupid stuff
424 if ( ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
425 || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
426 || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
427 || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
428 || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
429 || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
430 || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
433 my $error = $new->SUPER::replace($old, %options);
435 $dbh->rollback if $oldAutoCommit;
436 return $error if $error;
439 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
445 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
449 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
453 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
457 Checks all fields to make sure this is a valid phone number. If there is
458 an error, returns the error, otherwise returns false. Called by the insert
463 # the check method should currently be supplied - FS::Record contains some
464 # data checking routines
469 #my $conf = new FS::Conf;
471 my $x = $self->setfixed;
472 return $x unless ref($x);
475 my $phonenum = $self->phonenum;
476 my $phonenum_check_method;
477 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
478 $phonenum =~ s/\W//g;
479 $phonenum_check_method = 'ut_alpha';
481 $phonenum =~ s/\D//g;
482 $phonenum_check_method = 'ut_number';
484 $self->phonenum($phonenum);
486 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
489 $self->ut_numbern('svcnum')
490 || $self->ut_numbern('countrycode')
491 || $self->$phonenum_check_method('phonenum')
492 || $self->ut_numbern('sim_imsi')
493 || $self->ut_anything('sip_password')
494 || $self->ut_numbern('pin')
495 || $self->ut_textn('phone_name')
496 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
497 || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
498 || $self->ut_foreign_keyn('sms_carrierid', 'cdr_carrier', 'carrierid' )
499 || $self->ut_alphan('sms_account')
500 || $self->ut_numbern('max_simultaneous')
501 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
502 || $self->ut_numbern('forwarddst')
503 || $self->ut_textn('email')
504 || $self->ut_numbern('lrn')
505 || $self->ut_numbern('lnp_desired_due_date')
506 || $self->ut_numbern('lnp_due_date')
507 || $self->ut_textn('lnp_other_provider')
508 || $self->ut_textn('lnp_other_provider_account')
509 || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
510 'native', 'portin-reject', 'portout-reject'])
511 || $self->ut_enumn('portable', ['','Y'])
512 || $self->ut_textn('lnp_reject_reason')
514 return $error if $error;
516 return 'Illegal IMSI (not 14-15 digits)' #shorter?
517 if length($self->sim_imsi)
518 && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
520 # LNP data validation
521 return 'Cannot set LNP fields: no LNP in progress'
522 if ( ($self->lnp_desired_due_date || $self->lnp_due_date
523 || $self->lnp_other_provider || $self->lnp_other_provider_account
524 || $self->lnp_reject_reason)
525 && (!$self->lnp_status || $self->lnp_status eq 'native') );
526 return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
527 if ($self->lnp_reject_reason && (!$self->lnp_status
528 || $self->lnp_status !~ /^port(in|out)-reject$/) );
529 return 'Cannot port-out a non-portable number'
530 if (!$self->portable && $self->lnp_status eq 'portingout');
533 return 'Name ('. $self->phone_name.
534 ") is longer than $phone_name_max characters"
535 if $phone_name_max && length($self->phone_name) > $phone_name_max;
537 $self->countrycode(1) unless $self->countrycode;
539 unless ( length($self->pin) ) {
540 my $random_pin = $conf->config('svc_phone-random_pin');
541 if ( defined($random_pin) && $random_pin =~ /^\d+$/ ) {
543 join('', map int(rand(10)), 0..($random_pin-1))
548 if ( length($self->sip_password) ) {
550 return "SIP password must be longer than $passwordmin characters"
551 if length($self->sip_password) < $passwordmin;
552 return "SIP password must be shorter than $passwordmax characters"
553 if length($self->sip_password) > $passwordmax;
555 } elsif ( $part_svc->part_svc_column('sip_password')->columnflag ne 'F' ) {
559 join('', map $pw_set[ int(rand $#pw_set) ], (1..min($passwordmax,16)) )
567 =item _check duplicate
569 Internal method to check for duplicate phone numers.
573 #false laziness w/svc_acct.pm's _check_duplicate.
574 sub _check_duplicate {
577 my $global_unique = $conf->config('global_unique-phonenum') || 'none';
578 return '' if $global_unique eq 'disabled';
583 grep { !$self->svcnum || $_->svcnum != $self->svcnum }
584 qsearch( 'svc_phone', {
585 'countrycode' => $self->countrycode,
586 'phonenum' => $self->phonenum,
589 return gettext('phonenum_in_use')
590 if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
592 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
593 unless ( $part_svc ) {
594 return 'unknown svcpart '. $self->svcpart;
597 if ( @dup_ccphonenum ) {
599 my $exports = FS::part_export::export_info('svc_phone');
600 my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
602 foreach my $part_export ( $part_svc->part_export ) {
604 #this will catch to the same exact export
605 my @svcparts = map { $_->svcpart } $part_export->export_svc;
607 $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
612 foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
613 my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
614 if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
615 return "duplicate phone number ".
616 $self->countrycode. ' '. $self->phonenum.
617 ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
618 " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
630 Checks the supplied PIN against the PIN in the database. Returns true for a
631 sucessful authentication, false if no match.
636 my($self, $check_pin) = @_;
637 length($self->pin) && $check_pin eq $self->pin;
646 #XXX Session-Timeout! holy shit, need rlm_perl to ask for this in realtime
658 #my $conf = new FS::Conf;
661 if ( $conf->config('svc_phone-radius-password') eq 'countrycode_phonenum' ) {
662 $password = $self->countrycode. $self->phonenum;
664 $password = $conf->config('svc_phone-radius-default_password');
666 $check{'User-Password'} = $password;
675 =item sms_cdr_carrier
679 sub sms_cdr_carrier {
681 return '' unless $self->sms_carrierid;
682 qsearchs('cdr_carrier', { 'carrierid' => $self->sms_carrierid } );
685 =item sms_carriername
689 sub sms_carriername {
691 my $cdr_carrier = $self->sms_cdr_carrier or return '';
692 $cdr_carrier->carriername;
697 Returns any FS::phone_device records associated with this service.
701 #override location_Mixin version cause we want to try the cust_pkg location
702 #in between us and cust_main
703 # XXX what to do in the unlinked case??? return a pseudo-object that returns
705 sub cust_location_or_main {
707 return $self->cust_location if $self->locationnum;
708 my $cust_pkg = $self->cust_svc->cust_pkg;
709 $cust_pkg ? $cust_pkg->cust_location_or_main : '';
712 =item psearch_cdrs OPTIONS
714 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records
715 associated with this service. By default, "associated with" means that
716 either the "src" or the "charged_party" field of the CDR matches the
717 "phonenum" field of the service. To access the CDRs themselves, call
718 "->fetch" on the resulting object.
722 Accepts the following options:
724 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
726 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
728 =item inbound => 1: Return CDRs for inbound calls. With "status", will filter
729 on inbound processing status.
731 =item default_prefix => "XXX": Also accept the phone number of the service prepended
732 with the chosen prefix.
734 =item begin, end: Start and end of a date range, as unix timestamp.
736 =item cdrtypenum: Only return CDRs with this type.
738 =item calltypenum: Only return CDRs with this call type.
740 =item disable_src => 1: Only match on "charged_party", not "src".
742 =item nonzero: Only return CDRs where duration > 0.
744 =item by_svcnum: not supported for svc_phone
746 =item billsec_sum: Instead of returning all of the CDRs, return a single
747 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over
748 the entire result set.
756 my($self, %options) = @_;
761 if ( $options{'inbound'} ) {
764 if ( exists($options{'status'}) ) {
765 my $status = $options{'status'};
767 push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
768 'WHERE cdr.acctid = cdr_termination.acctid '.
769 "AND cdr_termination.status = '$status' ". #quoting kludge
770 'AND cdr_termination.termpart = 1 )';
772 push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
773 'WHERE cdr.acctid = cdr_termination.acctid '.
774 'AND cdr_termination.termpart = 1 )';
780 @fields = ( 'charged_party' );
781 push @fields, 'src' if !$options{'disable_src'};
782 $hash{'freesidestatus'} = $options{'status'}
783 if exists($options{'status'});
786 if ($options{'cdrtypenum'}) {
787 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
789 if ($options{'calltypenum'}) {
790 $hash{'calltypenum'} = $options{'calltypenum'};
793 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
795 my $number = $self->phonenum;
797 my $prefix = $options{'default_prefix'};
799 my @orwhere = map " $_ = '$number' ", @fields;
800 push @orwhere, map " $_ = '$prefix$number' ", @fields
801 if defined($prefix) && length($prefix);
802 if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
803 push @orwhere, map " $_ = '$1$number' ", @fields
806 push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
808 if ( $options{'begin'} ) {
809 push @where, 'startdate >= '. $options{'begin'};
811 if ( $options{'end'} ) {
812 push @where, 'startdate < '. $options{'end'};
814 if ( $options{'nonzero'} ) {
815 push @where, 'duration > 0';
818 my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
823 'extra_sql' => $extra_sql,
824 'order_by' => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
825 'select' => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
829 =item get_cdrs (DEPRECATED)
831 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a
832 single list. Arguments are the same as for psearch_cdrs. This can take
833 an unreasonably large amount of memory and is best avoided.
839 my $psearch = $self->psearch_cdrs(@_);
840 qsearch ( $psearch->{query} )
845 Takes the same options as psearch_cdrs, but returns a single row containing
846 "count" (the number of CDRs) and the sums of the following fields: duration,
847 billsec, rated_price, rated_seconds, rated_minutes.
849 Note that if any calls are not rated, their rated_* fields will be null.
850 If you want to use those fields, pass the 'status' option to limit to
851 calls that have been rated. This is intentional; please don't "fix" it.
857 my $psearch = $self->psearch_cdrs(@_);
858 $psearch->{query}->{'select'} = join(',',
860 map { "SUM($_) AS $_" }
861 qw(duration billsec rated_price rated_seconds rated_minutes)
864 $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
865 qsearchs ( $psearch->{query} );
874 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
875 L<FS::cust_pkg>, schema.html from the base documentation.