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