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
9 use Scalar::Util qw( blessed );
10 use List::Util qw( min );
12 use FS::Record qw( qsearch qsearchs dbh );
13 use FS::PagedSearch qw( psearch );
14 use FS::Msgcat qw(gettext);
19 use FS::cust_location;
22 $me = '[' . __PACKAGE__ . ']';
26 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
28 #ask FS::UID to run this stuff for us later
29 FS::UID->install_callback( sub {
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;
39 FS::svc_phone - Object methods for svc_phone records
45 $record = new FS::svc_phone \%hash;
46 $record = new FS::svc_phone { 'column' => 'value' };
48 $error = $record->insert;
50 $error = $new_record->replace($old_record);
52 $error = $record->delete;
54 $error = $record->check;
56 $error = $record->suspend;
58 $error = $record->unsuspend;
60 $error = $record->cancel;
64 An FS::svc_phone object represents a phone number. FS::svc_phone inherits
65 from FS::Record. The following fields are currently supported:
79 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
91 Optional svcnum from svc_pbx
95 Forwarding destination
99 Email address for virtual fax (fax-to-email) services
103 LNP Status (can be null, native, portedin, portingin, portin-reject,
104 portingout, portout-reject)
110 =item lnp_desired_due_date
114 =item lnp_other_provider
116 If porting the number in or out, name of the losing or winning provider,
119 =item lnp_other_provider_account
121 Account number of other provider. See lnp_other_provider.
123 =item lnp_reject_reason
125 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
126 optional reject reason.
136 Creates a new phone number. To add the number to the database, see L<"insert">.
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.
143 # the new method can be inherited from FS::Record, if a table method is defined
146 my %dis2 = ( disable_inventory=>1, disable_select=>1 );
148 'name' => 'Phone number',
149 'sorts' => 'phonenum',
150 'display_weight' => 60,
151 'cancel_weight' => 80,
153 'svcnum' => 'Service',
154 'countrycode' => { label => 'Country code',
156 disable_inventory => 1,
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',
163 disable_inventory => 1,
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
176 select_table => 'svc_domain',
177 select_key => 'svcnum',
178 select_label => 'domain',
179 disable_inventory => 1,
181 'sms_carrierid' => { label => 'SMS Carrier',
183 select_table => 'cdr_carrier',
184 select_key => 'carrierid',
185 select_label => 'carriername',
186 disable_inventory => 1,
188 'sms_account' => { label => 'SMS Carrier Account', },
189 'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
191 label => 'E911 location',
192 disable_inventory => 1,
195 'forwarddst' => { label => 'Forward Destination',
198 'email' => { label => 'Email',
201 'lnp_status' => { label => 'LNP Status',
202 type => 'select-lnp_status.html',
205 'lnp_reject_reason' => {
206 label => 'LNP Reject Reason',
209 'portable' => { label => 'Portable?', %dis2, },
210 'lrn' => { label => 'LRN',
211 disable_inventory => 1,
213 'lnp_desired_due_date' =>
214 { label => 'LNP Desired Due Date', %dis2 },
216 { label => 'LNP Due Date', %dis2 },
217 'lnp_other_provider' =>
218 { label => 'LNP Other Provider',
219 disable_inventory => 1,
221 'lnp_other_provider_account' =>
222 { label => 'LNP Other Provider Account #',
229 sub table { 'svc_phone'; }
231 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
233 =item search_sql STRING
235 Class method which returns an SQL fragment to search for the given string.
240 my( $class, $string ) = @_;
242 my $conf = new FS::Conf;
244 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
250 my $ccode = ( $conf->exists('default_phone_countrycode')
251 && $conf->config('default_phone_countrycode')
253 ? $conf->config('default_phone_countrycode')
256 $string =~ s/^$ccode//;
258 $class->search_sql_field('phonenum', $string );
263 Returns the phone number.
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;
278 Adds this phone number to the database. If there is an error, returns the
279 error, otherwise returns false.
288 warn "[$me] insert called on $self: ". Dumper($self).
289 "\nwith options: ". Dumper(%options);
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';
299 my $oldAutoCommit = $FS::UID::AutoCommit;
300 local $FS::UID::AutoCommit = 0;
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;
308 $dbh->rollback if $oldAutoCommit;
309 return "inserting cust_location (transaction rolled back): $error";
311 $self->locationnum( $options{'cust_location'}->locationnum );
313 #what about on-the-fly edits? if the ui supports it?
315 my $error = $self->SUPER::insert(%options);
317 $dbh->rollback if $oldAutoCommit;
321 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
328 Delete this record from the database.
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';
342 my $oldAutoCommit = $FS::UID::AutoCommit;
343 local $FS::UID::AutoCommit = 0;
346 foreach my $phone_device ( $self->phone_device ) {
347 my $error = $phone_device->delete;
349 $dbh->rollback if $oldAutoCommit;
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;
359 $dbh->rollback if $oldAutoCommit;
364 my $error = $self->SUPER::delete;
366 $dbh->rollback if $oldAutoCommit;
370 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
375 =item replace OLD_RECORD
377 Replaces the OLD_RECORD with this one in the database. If there is an error,
378 returns the error, otherwise returns false.
385 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
392 warn "[$me] replacing $old with $new\n".
393 "\nwith options: ". Dumper(%options);
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';
403 my $oldAutoCommit = $FS::UID::AutoCommit;
404 local $FS::UID::AutoCommit = 0;
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;
413 $dbh->rollback if $oldAutoCommit;
414 return "inserting cust_location (transaction rolled back): $error";
416 $new->locationnum( $options{'cust_location'}->locationnum );
418 #what about on-the-fly edits? if the ui supports it?
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')
431 my $error = $new->SUPER::replace($old, %options);
433 $dbh->rollback if $oldAutoCommit;
434 return $error if $error;
437 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
443 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
447 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
451 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
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
461 # the check method should currently be supplied - FS::Record contains some
462 # data checking routines
467 my $conf = new FS::Conf;
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';
475 $phonenum =~ s/\D//g;
476 $phonenum_check_method = 'ut_number';
478 $self->phonenum($phonenum);
480 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
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')
508 return $error if $error;
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 );
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');
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;
531 $self->countrycode(1) unless $self->countrycode;
533 unless ( length($self->pin) ) {
534 my $random_pin = $conf->config('svc_phone-random_pin');
535 if ( defined($random_pin) && $random_pin =~ /^\d+$/ ) {
537 join('', map int(rand(10)), 0..($random_pin-1))
542 if ( length($self->sip_password) ) {
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;
549 } else { # option for this?
552 join('', map $pw_set[ int(rand $#pw_set) ], (1..min($passwordmax,16)) )
560 =item _check duplicate
562 Internal method to check for duplicate phone numers.
566 #false laziness w/svc_acct.pm's _check_duplicate.
567 sub _check_duplicate {
570 my $global_unique = $conf->config('global_unique-phonenum') || 'none';
571 return '' if $global_unique eq 'disabled';
576 grep { !$self->svcnum || $_->svcnum != $self->svcnum }
577 qsearch( 'svc_phone', {
578 'countrycode' => $self->countrycode,
579 'phonenum' => $self->phonenum,
582 return gettext('phonenum_in_use')
583 if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
585 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
586 unless ( $part_svc ) {
587 return 'unknown svcpart '. $self->svcpart;
590 if ( @dup_ccphonenum ) {
592 my $exports = FS::part_export::export_info('svc_phone');
593 my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
595 foreach my $part_export ( $part_svc->part_export ) {
597 #this will catch to the same exact export
598 my @svcparts = map { $_->svcpart } $part_export->export_svc;
600 $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
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};
623 Checks the supplied PIN against the PIN in the database. Returns true for a
624 sucessful authentication, false if no match.
629 my($self, $check_pin) = @_;
630 length($self->pin) && $check_pin eq $self->pin;
639 #XXX Session-Timeout! holy shit, need rlm_perl to ask for this in realtime
651 my $conf = new FS::Conf;
654 if ( $conf->config('svc_phone-radius-password') eq 'countrycode_phonenum' ) {
655 $password = $self->countrycode. $self->phonenum;
657 $password = $conf->config('svc_phone-radius-default_password');
659 $check{'User-Password'} = $password;
668 =item sms_cdr_carrier
672 sub sms_cdr_carrier {
674 return '' unless $self->sms_carrierid;
675 qsearchs('cdr_carrier', { 'carrierid' => $self->sms_carrierid } );
678 =item sms_carriername
682 sub sms_carriername {
684 my $cdr_carrier = $self->sms_cdr_carrier or return '';
685 $cdr_carrier->carriername;
690 Returns any FS::phone_device records associated with this service.
696 qsearch('phone_device', { 'svcnum' => $self->svcnum } );
699 #override location_Mixin version cause we want to try the cust_pkg location
700 #in between us and cust_main
701 # XXX what to do in the unlinked case??? return a pseudo-object that returns
703 sub cust_location_or_main {
705 return $self->cust_location if $self->locationnum;
706 my $cust_pkg = $self->cust_svc->cust_pkg;
707 $cust_pkg ? $cust_pkg->cust_location_or_main : '';
710 =item psearch_cdrs OPTIONS
712 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records
713 associated with this service. By default, "associated with" means that
714 either the "src" or the "charged_party" field of the CDR matches the
715 "phonenum" field of the service. To access the CDRs themselves, call
716 "->fetch" on the resulting object.
720 Accepts the following options:
722 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
724 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
726 =item inbound => 1: Return CDRs for inbound calls. With "status", will filter
727 on inbound processing status.
729 =item default_prefix => "XXX": Also accept the phone number of the service prepended
730 with the chosen prefix.
732 =item begin, end: Start and end of a date range, as unix timestamp.
734 =item cdrtypenum: Only return CDRs with this type.
736 =item calltypenum: Only return CDRs with this call type.
738 =item disable_src => 1: Only match on "charged_party", not "src".
740 =item nonzero: Only return CDRs where duration > 0.
742 =item by_svcnum: not supported for svc_phone
744 =item billsec_sum: Instead of returning all of the CDRs, return a single
745 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over
746 the entire result set.
754 my($self, %options) = @_;
759 if ( $options{'inbound'} ) {
762 if ( exists($options{'status'}) ) {
763 my $status = $options{'status'};
765 push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
766 'WHERE cdr.acctid = cdr_termination.acctid '.
767 "AND cdr_termination.status = '$status' ". #quoting kludge
768 'AND cdr_termination.termpart = 1 )';
770 push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
771 'WHERE cdr.acctid = cdr_termination.acctid '.
772 'AND cdr_termination.termpart = 1 )';
778 @fields = ( 'charged_party' );
779 push @fields, 'src' if !$options{'disable_src'};
780 $hash{'freesidestatus'} = $options{'status'}
781 if exists($options{'status'});
784 if ($options{'cdrtypenum'}) {
785 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
787 if ($options{'calltypenum'}) {
788 $hash{'calltypenum'} = $options{'calltypenum'};
791 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
793 my $number = $self->phonenum;
795 my $prefix = $options{'default_prefix'};
797 my @orwhere = map " $_ = '$number' ", @fields;
798 push @orwhere, map " $_ = '$prefix$number' ", @fields
799 if defined($prefix) && length($prefix);
800 if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
801 push @orwhere, map " $_ = '$1$number' ", @fields
804 push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
806 if ( $options{'begin'} ) {
807 push @where, 'startdate >= '. $options{'begin'};
809 if ( $options{'end'} ) {
810 push @where, 'startdate < '. $options{'end'};
812 if ( $options{'nonzero'} ) {
813 push @where, 'duration > 0';
816 my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
821 'extra_sql' => $extra_sql,
822 'order_by' => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
823 'select' => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
827 =item get_cdrs (DEPRECATED)
829 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a
830 single list. Arguments are the same as for psearch_cdrs. This can take
831 an unreasonably large amount of memory and is best avoided.
837 my $psearch = $self->psearch_cdrs(@_);
838 qsearch ( $psearch->{query} )
843 Takes the same options as psearch_cdrs, but returns a single row containing
844 "count" (the number of CDRs) and the sums of the following fields: duration,
845 billsec, rated_price, rated_seconds, rated_minutes.
847 Note that if any calls are not rated, their rated_* fields will be null.
848 If you want to use those fields, pass the 'status' option to limit to
849 calls that have been rated. This is intentional; please don't "fix" it.
855 my $psearch = $self->psearch_cdrs(@_);
856 $psearch->{query}->{'select'} = join(',',
858 map { "SUM($_) AS $_" }
859 qw(duration billsec rated_price rated_seconds rated_minutes)
862 $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
863 qsearchs ( $psearch->{query} );
872 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
873 L<FS::cust_pkg>, schema.html from the base documentation.