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