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