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