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