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