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