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