added basic LNP capability to svc_phone including SS, RT10948
[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 use Data::Dumper;
7 use Scalar::Util qw( blessed );
8 use FS::Conf;
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::Msgcat qw(gettext);
11 use FS::part_svc;
12 use FS::phone_device;
13 use FS::svc_pbx;
14 use FS::svc_domain;
15 use FS::cust_location;
16 use FS::phone_avail;
17
18 $me = '[' . __PACKAGE__ . ']';
19 $DEBUG = 0;
20
21 #avoid l 1 and o O 0
22 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
23
24 #ask FS::UID to run this stuff for us later
25 $FS::UID::callback{'FS::svc_acct'} = sub { 
26   $conf = new FS::Conf;
27   $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
28 };
29
30 =head1 NAME
31
32 FS::svc_phone - Object methods for svc_phone records
33
34 =head1 SYNOPSIS
35
36   use FS::svc_phone;
37
38   $record = new FS::svc_phone \%hash;
39   $record = new FS::svc_phone { 'column' => 'value' };
40
41   $error = $record->insert;
42
43   $error = $new_record->replace($old_record);
44
45   $error = $record->delete;
46
47   $error = $record->check;
48
49   $error = $record->suspend;
50
51   $error = $record->unsuspend;
52
53   $error = $record->cancel;
54
55 =head1 DESCRIPTION
56
57 An FS::svc_phone object represents a phone number.  FS::svc_phone inherits
58 from FS::Record.  The following fields are currently supported:
59
60 =over 4
61
62 =item svcnum
63
64 primary key
65
66 =item countrycode
67
68 =item phonenum
69
70 =item sip_password
71
72 =item pin
73
74 Voicemail PIN
75
76 =item phone_name
77
78 =item pbxsvc
79
80 Optional svcnum from svc_pbx
81
82 =back
83
84 =head1 METHODS
85
86 =over 4
87
88 =item new HASHREF
89
90 Creates a new phone number.  To add the number to the database, see L<"insert">.
91
92 Note that this stores the hash reference, not a distinct copy of the hash it
93 points to.  You can ask the object for a copy with the I<hash> method.
94
95 =cut
96
97 # the new method can be inherited from FS::Record, if a table method is defined
98 #
99 sub table_info {
100  my %dis2 = ( disable_inventory=>1, disable_select=>1 );
101   {
102     'name' => 'Phone number',
103     'sorts' => 'phonenum',
104     'display_weight' => 60,
105     'cancel_weight'  => 80,
106     'fields' => {
107         'countrycode'  => { label => 'Country code',
108                             type  => 'text',
109                             disable_inventory => 1,
110                             disable_select => 1,
111                           },
112         'phonenum'     => 'Phone number',
113         'pin'          => { label => 'Personal Identification Number',
114                             type  => 'text',
115                             disable_inventory => 1,
116                             disable_select => 1,
117                           },
118         'sip_password' => 'SIP password',
119         'phone_name'   => 'Name',
120         'pbxsvc'       => { label => 'PBX',
121                             type  => 'select-svc_pbx.html',
122                             disable_inventory => 1,
123                             disable_select => 1, #UI wonky, pry works otherwise
124                           },
125         'domsvc'    => {
126                          label     => 'Domain',
127                          type      => 'select',
128                          select_table => 'svc_domain',
129                          select_key   => 'svcnum',
130                          select_label => 'domain',
131                          disable_inventory => 1,
132                        },
133         'locationnum' => {
134                            label => 'E911 location',
135                            disable_inventory => 1,
136                            disable_select    => 1,
137                          },
138         'lnp_status' => {       label => 'LNP Status',
139                                 type => 'select-lnp_status.html',
140                                 %dis2,
141                         },
142         'portable' =>   {       label => 'Portable?', %dis2, },
143         'lrn'   =>      {       label => 'LRN', 
144                                 disable_inventory => 1, 
145                         },
146         'lnp_desired_due_date' =>
147                         { label => 'LNP Desired Due Date', %dis2 },
148         'lnp_due_date' =>
149                         { label => 'LNP Due Date', %dis2 },
150         'lnp_other_provider' =>
151                         {       label => 'LNP Other Provider', 
152                                 disable_inventory => 1, 
153                         },
154         'lnp_other_provider_account' =>
155                         {       label => 'LNP Other Provider Account #', 
156                                 %dis2 
157                         },
158     },
159   };
160 }
161
162 sub table { 'svc_phone'; }
163
164 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
165
166 =item search_sql STRING
167
168 Class method which returns an SQL fragment to search for the given string.
169
170 =cut
171
172 sub search_sql {
173   my( $class, $string ) = @_;
174
175   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
176     $string =~ s/\W//g;
177   } else {
178     $string =~ s/\D//g;
179   }
180
181   my $conf = new FS::Conf;
182   my $ccode = (    $conf->exists('default_phone_countrycode')
183                 && $conf->config('default_phone_countrycode')
184               )
185                 ? $conf->config('default_phone_countrycode') 
186                 : '1';
187
188   $string =~ s/^$ccode//;
189
190   $class->search_sql_field('phonenum', $string );
191 }
192
193 =item label
194
195 Returns the phone number.
196
197 =cut
198
199 sub label {
200   my $self = shift;
201   my $phonenum = $self->phonenum; #XXX format it better
202   my $label = $phonenum;
203   $label .= '@'.$self->domain if $self->domsvc;
204   $label .= ' ('.$self->phone_name.')' if $self->phone_name;
205   $label;
206 }
207
208 =item insert
209
210 Adds this phone number to the database.  If there is an error, returns the
211 error, otherwise returns false.
212
213 =cut
214
215 sub insert {
216   my $self = shift;
217   my %options = @_;
218
219   if ( $DEBUG ) {
220     warn "[$me] insert called on $self: ". Dumper($self).
221          "\nwith options: ". Dumper(%options);
222   }
223
224   local $SIG{HUP} = 'IGNORE';
225   local $SIG{INT} = 'IGNORE';
226   local $SIG{QUIT} = 'IGNORE';
227   local $SIG{TERM} = 'IGNORE';
228   local $SIG{TSTP} = 'IGNORE';
229   local $SIG{PIPE} = 'IGNORE';
230
231   my $oldAutoCommit = $FS::UID::AutoCommit;
232   local $FS::UID::AutoCommit = 0;
233   my $dbh = dbh;
234
235   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
236   #make it more of a base class than a mixin... :)
237   if ( $options{'cust_location'}
238          && ( ! $self->locationnum || $self->locationnum == -1 ) ) {
239     my $error = $options{'cust_location'}->insert;
240     if ( $error ) {
241       $dbh->rollback if $oldAutoCommit;
242       return "inserting cust_location (transaction rolled back): $error";
243     }
244     $self->locationnum( $options{'cust_location'}->locationnum );
245   }
246   #what about on-the-fly edits?  if the ui supports it?
247
248   my $error = $self->SUPER::insert(%options);
249   if ( $error ) {
250     $dbh->rollback if $oldAutoCommit;
251     return $error;
252   }
253
254   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
255   '';
256
257 }
258
259 =item delete
260
261 Delete this record from the database.
262
263 =cut
264
265 sub delete {
266   my $self = shift;
267
268   local $SIG{HUP} = 'IGNORE';
269   local $SIG{INT} = 'IGNORE';
270   local $SIG{QUIT} = 'IGNORE';
271   local $SIG{TERM} = 'IGNORE';
272   local $SIG{TSTP} = 'IGNORE';
273   local $SIG{PIPE} = 'IGNORE';
274
275   my $oldAutoCommit = $FS::UID::AutoCommit;
276   local $FS::UID::AutoCommit = 0;
277   my $dbh = dbh;
278
279   foreach my $phone_device ( $self->phone_device ) {
280     my $error = $phone_device->delete;
281     if ( $error ) {
282       $dbh->rollback if $oldAutoCommit;
283       return $error;
284     }
285   }
286
287   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
288   foreach my $phone_avail ( @phone_avail ) {
289     $phone_avail->svcnum('');
290     my $error = $phone_avail->replace;
291     if ( $error ) {
292       $dbh->rollback if $oldAutoCommit;
293       return $error;
294     }
295   }
296
297   my $error = $self->SUPER::delete;
298   if ( $error ) {
299     $dbh->rollback if $oldAutoCommit;
300     return $error;
301   }
302
303   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
304   '';
305
306 }
307
308 # the delete method can be inherited from FS::Record
309
310 =item replace OLD_RECORD
311
312 Replaces the OLD_RECORD with this one in the database.  If there is an error,
313 returns the error, otherwise returns false.
314
315 =cut
316
317 sub replace {
318   my $new = shift;
319
320   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
321               ? shift
322               : $new->replace_old;
323
324   my %options = @_;
325
326   if ( $DEBUG ) {
327     warn "[$me] replacing $old with $new\n".
328          "\nwith options: ". Dumper(%options);
329   }
330
331   local $SIG{HUP} = 'IGNORE';
332   local $SIG{INT} = 'IGNORE';
333   local $SIG{QUIT} = 'IGNORE';
334   local $SIG{TERM} = 'IGNORE';
335   local $SIG{TSTP} = 'IGNORE';
336   local $SIG{PIPE} = 'IGNORE';
337
338   my $oldAutoCommit = $FS::UID::AutoCommit;
339   local $FS::UID::AutoCommit = 0;
340   my $dbh = dbh;
341
342   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
343   #make it more of a base class than a mixin... :)
344   if ( $options{'cust_location'}
345          && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
346     my $error = $options{'cust_location'}->insert;
347     if ( $error ) {
348       $dbh->rollback if $oldAutoCommit;
349       return "inserting cust_location (transaction rolled back): $error";
350     }
351     $new->locationnum( $options{'cust_location'}->locationnum );
352   }
353   #what about on-the-fly edits?  if the ui supports it?
354
355   my $error = $new->SUPER::replace($old, %options);
356   if ( $error ) {
357     $dbh->rollback if $oldAutoCommit;
358     return $error if $error;
359   }
360
361   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
362   ''; #no error
363 }
364
365 =item suspend
366
367 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
368
369 =item unsuspend
370
371 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
372
373 =item cancel
374
375 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
376
377 =item check
378
379 Checks all fields to make sure this is a valid phone number.  If there is
380 an error, returns the error, otherwise returns false.  Called by the insert
381 and replace methods.
382
383 =cut
384
385 # the check method should currently be supplied - FS::Record contains some
386 # data checking routines
387
388 sub check {
389   my $self = shift;
390
391   my $conf = new FS::Conf;
392
393   my $phonenum = $self->phonenum;
394   my $phonenum_check_method;
395   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
396     $phonenum =~ s/\W//g;
397     $phonenum_check_method = 'ut_alpha';
398   } else {
399     $phonenum =~ s/\D//g;
400     $phonenum_check_method = 'ut_number';
401   }
402   $self->phonenum($phonenum);
403
404   $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
405
406   my $error = 
407     $self->ut_numbern('svcnum')
408     || $self->ut_numbern('countrycode')
409     || $self->$phonenum_check_method('phonenum')
410     || $self->ut_anything('sip_password')
411     || $self->ut_numbern('pin')
412     || $self->ut_textn('phone_name')
413     || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx',    'svcnum' )
414     || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
415     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
416     || $self->ut_numbern('lrn')
417     || $self->ut_numbern('lnp_desired_due_date')
418     || $self->ut_numbern('lnp_due_date')
419     || $self->ut_textn('lnp_other_provider')
420     || $self->ut_textn('lnp_other_provider_account')
421     || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin','native'])
422     || $self->ut_enumn('portable', ['','Y'])
423   ;
424   return $error if $error;
425
426   return 'Name ('. $self->phone_name.
427          ") is longer than $phone_name_max characters"
428     if $phone_name_max && length($self->phone_name) > $phone_name_max;
429
430   $self->countrycode(1) unless $self->countrycode;
431
432   unless ( length($self->sip_password) ) {
433
434     $self->sip_password(
435       join('', map $pw_set[ int(rand $#pw_set) ], (0..16) )
436     );
437
438   }
439
440   $self->SUPER::check;
441 }
442
443 =item _check duplicate
444
445 Internal method to check for duplicate phone numers.
446
447 =cut
448
449 #false laziness w/svc_acct.pm's _check_duplicate.
450 sub _check_duplicate {
451   my $self = shift;
452
453   my $global_unique = $conf->config('global_unique-phonenum') || 'none';
454   return '' if $global_unique eq 'disabled';
455
456   $self->lock_table;
457
458   my @dup_ccphonenum =
459     grep { !$self->svcnum || $_->svcnum != $self->svcnum }
460     qsearch( 'svc_phone', {
461       'countrycode' => $self->countrycode,
462       'phonenum'    => $self->phonenum,
463     });
464
465   return gettext('phonenum_in_use')
466     if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
467
468   my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
469   unless ( $part_svc ) {
470     return 'unknown svcpart '. $self->svcpart;
471   }
472
473   if ( @dup_ccphonenum ) {
474
475     my $exports = FS::part_export::export_info('svc_phone');
476     my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
477
478     foreach my $part_export ( $part_svc->part_export ) {
479
480       #this will catch to the same exact export
481       my @svcparts = map { $_->svcpart } $part_export->export_svc;
482
483       $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
484         foreach @svcparts;
485
486     }
487
488     foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
489       my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
490       if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
491         return "duplicate phone number ".
492                $self->countrycode. ' '. $self->phonenum.
493                ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
494                " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
495       }
496     }
497
498   }
499
500   return '';
501
502 }
503
504 =item check_pin
505
506 Checks the supplied PIN against the PIN in the database.  Returns true for a
507 sucessful authentication, false if no match.
508
509 =cut
510
511 sub check_pin {
512   my($self, $check_pin) = @_;
513   length($self->pin) && $check_pin eq $self->pin;
514 }
515
516 =item radius_reply
517
518 =cut
519
520 sub radius_reply {
521   my $self = shift;
522   #XXX Session-Timeout!  holy shit, need rlm_perl to ask for this in realtime
523   ();
524 }
525
526 =item radius_check
527
528 =cut
529
530 sub radius_check {
531   my $self = shift;
532   my %check = ();
533
534   my $conf = new FS::Conf;
535
536   $check{'User-Password'} = $conf->config('svc_phone-radius-default_password');
537
538   %check;
539 }
540
541 sub radius_groups {
542   ();
543 }
544
545 =item phone_device
546
547 Returns any FS::phone_device records associated with this service.
548
549 =cut
550
551 sub phone_device {
552   my $self = shift;
553   qsearch('phone_device', { 'svcnum' => $self->svcnum } );
554 }
555
556 #override location_Mixin version cause we want to try the cust_pkg location
557 #in between us and cust_main
558 # XXX what to do in the unlinked case???  return a pseudo-object that returns
559 # empty fields?
560 sub cust_location_or_main {
561   my $self = shift;
562   return $self->cust_location if $self->locationnum;
563   my $cust_pkg = $self->cust_svc->cust_pkg;
564   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
565 }
566
567 =item get_cdrs
568
569 Returns a set of Call Detail Records (see L<FS::cdr>) associated with this 
570 service.  By default, "associated with" means that either the "src" or the 
571 "charged_party" field of the CDR matches the "phonenum" field of the service.
572
573 =over 2
574
575 Accepts the following options:
576
577 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
578
579 =item status => "" (or "done"): Return only CDRs with that processing status.
580
581 =item inbound => 1: Return CDRs for inbound calls.  With "status", will filter 
582 on inbound processing status.
583
584 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
585 with the chosen prefix.
586
587 =item disable_src => 1: Only match on "charged_party", not "src".
588
589 =item by_svcnum: not supported for svc_phone
590
591 =back
592
593 =cut
594
595 sub get_cdrs {
596   my($self, %options) = @_;
597   my @fields;
598   my %hash;
599   my @where;
600
601   if ( $options{'inbound'} ) {
602     @fields = ( 'dst' );
603     if ( exists($options{'status'}) ) {
604       # must be 'done' or ''
605       my $sq = 'EXISTS ( SELECT 1 FROM cdr_termination '.
606         'WHERE cdr.acctid = cdr_termination.acctid '.
607         'AND cdr_termination.status = \'done\' '.
608         'AND cdr_termination.termpart = 1 )';
609       if ( $options{'status'} eq 'done' ) {
610         push @where, $sq;
611       }
612       elsif ($options{'status'} eq '' ) {
613         push @where, "NOT $sq";
614       }
615       else {
616         warn "invalid status: $options{'status'} (ignored)\n";
617       }
618     }
619   }
620   else {
621     @fields = ( 'charged_party' );
622     push @fields, 'src' if !$options{'disable_src'};
623     $hash{'freesidestatus'} = $options{'status'}
624       if exists($options{'status'});
625   }
626   
627   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
628
629   my $number = $self->phonenum;
630
631   my $prefix = $options{'default_prefix'};
632
633   my @orwhere =  map " $_ = '$number'        ", @fields;
634   push @orwhere, map " $_ = '$prefix$number' ", @fields
635     if length($prefix);
636   if ( $prefix =~ /^\+(\d+)$/ ) {
637     push @orwhere, map " $_ = '$1$number' ", @fields
638   }
639
640   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
641
642   if ( $options{'begin'} ) {
643     push @where, 'startdate >= '. $options{'begin'};
644   }
645   if ( $options{'end'} ) {
646     push @where, 'startdate < '.  $options{'end'};
647   }
648
649   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
650
651   my @cdrs =
652     qsearch( {
653       'table'      => 'cdr',
654       'hashref'    => \%hash,
655       'extra_sql'  => $extra_sql,
656       'order_by'   => "ORDER BY startdate $for_update",
657     } );
658
659   @cdrs;
660 }
661
662 =back
663
664 =head1 BUGS
665
666 =head1 SEE ALSO
667
668 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
669 L<FS::cust_pkg>, schema.html from the base documentation.
670
671 =cut
672
673 1;
674