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,
177 label => 'E911 location',
178 disable_inventory => 1,
181 'forwarddst' => { label => 'Forward Destination',
184 'email' => { label => 'Email',
187 'lnp_status' => { label => 'LNP Status',
188 type => 'select-lnp_status.html',
191 'lnp_reject_reason' => {
192 label => 'LNP Reject Reason',
195 'portable' => { label => 'Portable?', %dis2, },
196 'lrn' => { label => 'LRN',
197 disable_inventory => 1,
199 'lnp_desired_due_date' =>
200 { label => 'LNP Desired Due Date', %dis2 },
202 { label => 'LNP Due Date', %dis2 },
203 'lnp_other_provider' =>
204 { label => 'LNP Other Provider',
205 disable_inventory => 1,
207 'lnp_other_provider_account' =>
208 { label => 'LNP Other Provider Account #',
215 sub table { 'svc_phone'; }
217 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
219 =item search_sql STRING
221 Class method which returns an SQL fragment to search for the given string.
226 my( $class, $string ) = @_;
228 my $conf = new FS::Conf;
230 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
236 my $ccode = ( $conf->exists('default_phone_countrycode')
237 && $conf->config('default_phone_countrycode')
239 ? $conf->config('default_phone_countrycode')
242 $string =~ s/^$ccode//;
244 $class->search_sql_field('phonenum', $string );
249 Returns the phone number.
255 my $phonenum = $self->phonenum; #XXX format it better
256 my $label = $phonenum;
257 $label .= '@'.$self->domain if $self->domsvc;
258 $label .= ' ('.$self->phone_name.')' if $self->phone_name;
264 Adds this phone number to the database. If there is an error, returns the
265 error, otherwise returns false.
274 warn "[$me] insert called on $self: ". Dumper($self).
275 "\nwith options: ". Dumper(%options);
278 local $SIG{HUP} = 'IGNORE';
279 local $SIG{INT} = 'IGNORE';
280 local $SIG{QUIT} = 'IGNORE';
281 local $SIG{TERM} = 'IGNORE';
282 local $SIG{TSTP} = 'IGNORE';
283 local $SIG{PIPE} = 'IGNORE';
285 my $oldAutoCommit = $FS::UID::AutoCommit;
286 local $FS::UID::AutoCommit = 0;
289 #false laziness w/cust_pkg.pm... move this to location_Mixin? that would
290 #make it more of a base class than a mixin... :)
291 if ( $options{'cust_location'} ) {
292 my $error = $options{'cust_location'}->find_or_insert;
294 $dbh->rollback if $oldAutoCommit;
295 return "inserting cust_location (transaction rolled back): $error";
297 $self->locationnum( $options{'cust_location'}->locationnum );
299 #what about on-the-fly edits? if the ui supports it?
301 my $error = $self->SUPER::insert(%options);
303 $dbh->rollback if $oldAutoCommit;
307 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
314 Delete this record from the database.
321 local $SIG{HUP} = 'IGNORE';
322 local $SIG{INT} = 'IGNORE';
323 local $SIG{QUIT} = 'IGNORE';
324 local $SIG{TERM} = 'IGNORE';
325 local $SIG{TSTP} = 'IGNORE';
326 local $SIG{PIPE} = 'IGNORE';
328 my $oldAutoCommit = $FS::UID::AutoCommit;
329 local $FS::UID::AutoCommit = 0;
332 foreach my $phone_device ( $self->phone_device ) {
333 my $error = $phone_device->delete;
335 $dbh->rollback if $oldAutoCommit;
340 my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
341 foreach my $phone_avail ( @phone_avail ) {
342 $phone_avail->svcnum('');
343 my $error = $phone_avail->replace;
345 $dbh->rollback if $oldAutoCommit;
350 my $error = $self->SUPER::delete;
352 $dbh->rollback if $oldAutoCommit;
356 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
361 # the delete method can be inherited from FS::Record
363 =item replace OLD_RECORD
365 Replaces the OLD_RECORD with this one in the database. If there is an error,
366 returns the error, otherwise returns false.
373 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
380 warn "[$me] replacing $old with $new\n".
381 "\nwith options: ". Dumper(%options);
384 local $SIG{HUP} = 'IGNORE';
385 local $SIG{INT} = 'IGNORE';
386 local $SIG{QUIT} = 'IGNORE';
387 local $SIG{TERM} = 'IGNORE';
388 local $SIG{TSTP} = 'IGNORE';
389 local $SIG{PIPE} = 'IGNORE';
391 my $oldAutoCommit = $FS::UID::AutoCommit;
392 local $FS::UID::AutoCommit = 0;
395 #false laziness w/cust_pkg.pm... move this to location_Mixin? that would
396 #make it more of a base class than a mixin... :)
397 if ( $options{'cust_location'}
398 && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
399 my $error = $options{'cust_location'}->insert;
401 $dbh->rollback if $oldAutoCommit;
402 return "inserting cust_location (transaction rolled back): $error";
404 $new->locationnum( $options{'cust_location'}->locationnum );
406 #what about on-the-fly edits? if the ui supports it?
408 # LNP data validation
409 return 'Invalid LNP status' # if someone does really stupid stuff
410 if ( ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
411 || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
412 || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
413 || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
414 || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
415 || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
416 || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
419 my $error = $new->SUPER::replace($old, %options);
421 $dbh->rollback if $oldAutoCommit;
422 return $error if $error;
425 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
431 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
435 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
439 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
443 Checks all fields to make sure this is a valid phone number. If there is
444 an error, returns the error, otherwise returns false. Called by the insert
449 # the check method should currently be supplied - FS::Record contains some
450 # data checking routines
455 my $conf = new FS::Conf;
457 my $phonenum = $self->phonenum;
458 my $phonenum_check_method;
459 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
460 $phonenum =~ s/\W//g;
461 $phonenum_check_method = 'ut_alpha';
463 $phonenum =~ s/\D//g;
464 $phonenum_check_method = 'ut_number';
466 $self->phonenum($phonenum);
468 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
471 $self->ut_numbern('svcnum')
472 || $self->ut_numbern('countrycode')
473 || $self->$phonenum_check_method('phonenum')
474 || $self->ut_numbern('sim_imsi')
475 || $self->ut_anything('sip_password')
476 || $self->ut_numbern('pin')
477 || $self->ut_textn('phone_name')
478 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
479 || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
480 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
481 || $self->ut_numbern('forwarddst')
482 || $self->ut_textn('email')
483 || $self->ut_numbern('lrn')
484 || $self->ut_numbern('lnp_desired_due_date')
485 || $self->ut_numbern('lnp_due_date')
486 || $self->ut_textn('lnp_other_provider')
487 || $self->ut_textn('lnp_other_provider_account')
488 || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
489 'native', 'portin-reject', 'portout-reject'])
490 || $self->ut_enumn('portable', ['','Y'])
491 || $self->ut_textn('lnp_reject_reason')
493 return $error if $error;
495 return 'Illegal IMSI (not 14-15 digits)' #shorter?
496 if length($self->sim_imsi)
497 && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
499 # LNP data validation
500 return 'Cannot set LNP fields: no LNP in progress'
501 if ( ($self->lnp_desired_due_date || $self->lnp_due_date
502 || $self->lnp_other_provider || $self->lnp_other_provider_account
503 || $self->lnp_reject_reason)
504 && (!$self->lnp_status || $self->lnp_status eq 'native') );
505 return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
506 if ($self->lnp_reject_reason && (!$self->lnp_status
507 || $self->lnp_status !~ /^port(in|out)-reject$/) );
508 return 'Cannot port-out a non-portable number'
509 if (!$self->portable && $self->lnp_status eq 'portingout');
512 return 'Name ('. $self->phone_name.
513 ") is longer than $phone_name_max characters"
514 if $phone_name_max && length($self->phone_name) > $phone_name_max;
516 $self->countrycode(1) unless $self->countrycode;
518 unless ( length($self->pin) ) {
519 my $random_pin = $conf->config('svc_phone-random_pin');
520 if ( $random_pin =~ /^\d+$/ ) {
522 join('', map int(rand(10)), 0..($random_pin-1))
527 unless ( length($self->sip_password) ) { # option for this?
530 join('', map $pw_set[ int(rand $#pw_set) ], (0..16) )
538 =item _check duplicate
540 Internal method to check for duplicate phone numers.
544 #false laziness w/svc_acct.pm's _check_duplicate.
545 sub _check_duplicate {
548 my $global_unique = $conf->config('global_unique-phonenum') || 'none';
549 return '' if $global_unique eq 'disabled';
554 grep { !$self->svcnum || $_->svcnum != $self->svcnum }
555 qsearch( 'svc_phone', {
556 'countrycode' => $self->countrycode,
557 'phonenum' => $self->phonenum,
560 return gettext('phonenum_in_use')
561 if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
563 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
564 unless ( $part_svc ) {
565 return 'unknown svcpart '. $self->svcpart;
568 if ( @dup_ccphonenum ) {
570 my $exports = FS::part_export::export_info('svc_phone');
571 my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
573 foreach my $part_export ( $part_svc->part_export ) {
575 #this will catch to the same exact export
576 my @svcparts = map { $_->svcpart } $part_export->export_svc;
578 $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
583 foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
584 my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
585 if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
586 return "duplicate phone number ".
587 $self->countrycode. ' '. $self->phonenum.
588 ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
589 " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
601 Checks the supplied PIN against the PIN in the database. Returns true for a
602 sucessful authentication, false if no match.
607 my($self, $check_pin) = @_;
608 length($self->pin) && $check_pin eq $self->pin;
617 #XXX Session-Timeout! holy shit, need rlm_perl to ask for this in realtime
629 my $conf = new FS::Conf;
631 $check{'User-Password'} = $conf->config('svc_phone-radius-default_password');
642 Returns any FS::phone_device records associated with this service.
648 qsearch('phone_device', { 'svcnum' => $self->svcnum } );
651 #override location_Mixin version cause we want to try the cust_pkg location
652 #in between us and cust_main
653 # XXX what to do in the unlinked case??? return a pseudo-object that returns
655 sub cust_location_or_main {
657 return $self->cust_location if $self->locationnum;
658 my $cust_pkg = $self->cust_svc->cust_pkg;
659 $cust_pkg ? $cust_pkg->cust_location_or_main : '';
662 =item psearch_cdrs OPTIONS
664 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records
665 associated with this service. By default, "associated with" means that
666 either the "src" or the "charged_party" field of the CDR matches the
667 "phonenum" field of the service. To access the CDRs themselves, call
668 "->fetch" on the resulting object.
672 Accepts the following options:
674 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
676 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
678 =item inbound => 1: Return CDRs for inbound calls. With "status", will filter
679 on inbound processing status.
681 =item default_prefix => "XXX": Also accept the phone number of the service prepended
682 with the chosen prefix.
684 =item begin, end: Start and end of a date range, as unix timestamp.
686 =item cdrtypenum: Only return CDRs with this type.
688 =item calltypenum: Only return CDRs with this call type.
690 =item disable_src => 1: Only match on "charged_party", not "src".
692 =item nonzero: Only return CDRs where duration > 0.
694 =item by_svcnum: not supported for svc_phone
696 =item billsec_sum: Instead of returning all of the CDRs, return a single
697 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over
698 the entire result set.
706 my($self, %options) = @_;
711 if ( $options{'inbound'} ) {
714 if ( exists($options{'status'}) ) {
715 my $status = $options{'status'};
717 push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
718 'WHERE cdr.acctid = cdr_termination.acctid '.
719 "AND cdr_termination.status = '$status' ". #quoting kludge
720 'AND cdr_termination.termpart = 1 )';
722 push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
723 'WHERE cdr.acctid = cdr_termination.acctid '.
724 'AND cdr_termination.termpart = 1 )';
730 @fields = ( 'charged_party' );
731 push @fields, 'src' if !$options{'disable_src'};
732 $hash{'freesidestatus'} = $options{'status'}
733 if exists($options{'status'});
736 if ($options{'cdrtypenum'}) {
737 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
739 if ($options{'calltypenum'}) {
740 $hash{'calltypenum'} = $options{'calltypenum'};
743 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
745 my $number = $self->phonenum;
747 my $prefix = $options{'default_prefix'};
749 my @orwhere = map " $_ = '$number' ", @fields;
750 push @orwhere, map " $_ = '$prefix$number' ", @fields
751 if defined($prefix) && length($prefix);
752 if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
753 push @orwhere, map " $_ = '$1$number' ", @fields
756 push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
758 if ( $options{'begin'} ) {
759 push @where, 'startdate >= '. $options{'begin'};
761 if ( $options{'end'} ) {
762 push @where, 'startdate < '. $options{'end'};
764 if ( $options{'nonzero'} ) {
765 push @where, 'duration > 0';
768 my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
773 'extra_sql' => $extra_sql,
774 'order_by' => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
775 'select' => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
779 =item get_cdrs (DEPRECATED)
781 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a
782 single list. Arguments are the same as for psearch_cdrs. This can take
783 an unreasonably large amount of memory and is best avoided.
789 my $psearch = $self->psearch_cdrs(@_);
790 qsearch ( $psearch->{query} )
795 Takes the same options as psearch_cdrs, but returns a single row containing
796 "count" (the number of CDRs) and the sums of the following fields: duration,
797 billsec, rated_price, rated_seconds, rated_minutes.
799 Note that if any calls are not rated, their rated_* fields will be null.
800 If you want to use those fields, pass the 'status' option to limit to
801 calls that have been rated. This is intentional; please don't "fix" it.
807 my $psearch = $self->psearch_cdrs(@_);
808 $psearch->{query}->{'select'} = join(',',
810 map { "SUM($_) AS $_" }
811 qw(duration billsec rated_price rated_seconds rated_minutes)
814 $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
815 qsearchs ( $psearch->{query} );
824 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
825 L<FS::cust_pkg>, schema.html from the base documentation.