voip.ms export, #31834
[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              $passwordmin $passwordmax
7            );
8 use Data::Dumper;
9 use Scalar::Util qw( blessed );
10 use List::Util qw( min );
11 use Tie::IxHash;
12 use FS::Conf;
13 use FS::Record qw( qsearch qsearchs dbh );
14 use FS::PagedSearch qw( psearch );
15 use FS::Msgcat qw(gettext);
16 use FS::part_svc;
17 use FS::phone_device;
18 use FS::svc_pbx;
19 use FS::svc_domain;
20 use FS::cust_location;
21 use FS::phone_avail;
22
23 $me = '[' . __PACKAGE__ . ']';
24 $DEBUG = 0;
25
26 #avoid l 1 and o O 0
27 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
28
29 #ask FS::UID to run this stuff for us later
30 FS::UID->install_callback( sub { 
31   $conf = new FS::Conf;
32   $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
33   $passwordmin = $conf->config('sip_passwordmin') || 0;
34   $passwordmax = $conf->config('sip_passwordmax') || 80;
35 }
36 );
37
38 =head1 NAME
39
40 FS::svc_phone - Object methods for svc_phone records
41
42 =head1 SYNOPSIS
43
44   use FS::svc_phone;
45
46   $record = new FS::svc_phone \%hash;
47   $record = new FS::svc_phone { 'column' => 'value' };
48
49   $error = $record->insert;
50
51   $error = $new_record->replace($old_record);
52
53   $error = $record->delete;
54
55   $error = $record->check;
56
57   $error = $record->suspend;
58
59   $error = $record->unsuspend;
60
61   $error = $record->cancel;
62
63 =head1 DESCRIPTION
64
65 An FS::svc_phone object represents a phone number.  FS::svc_phone inherits
66 from FS::Record.  The following fields are currently supported:
67
68 =over 4
69
70 =item svcnum
71
72 primary key
73
74 =item countrycode
75
76 =item phonenum
77
78 =item sim_imsi
79
80 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
81
82 =item sip_password
83
84 =item pin
85
86 Voicemail PIN
87
88 =item phone_name
89
90 =item pbxsvc
91
92 Optional svcnum from svc_pbx
93
94 =item forwarddst
95
96 Forwarding destination
97
98 =item email
99
100 Email address for virtual fax (fax-to-email) services
101
102 =item lnp_status
103
104 LNP Status (can be null, native, portedin, portingin, portin-reject,
105 portingout, portout-reject)
106
107 =item portable
108
109 =item lrn
110
111 =item lnp_desired_due_date
112
113 =item lnp_due_date
114
115 =item lnp_other_provider
116
117 If porting the number in or out, name of the losing or winning provider, 
118 respectively.
119
120 =item lnp_other_provider_account
121
122 Account number of other provider. See lnp_other_provider.
123
124 =item lnp_reject_reason
125
126 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
127 optional reject reason.
128
129 =item e911_class
130
131 Class of Service for E911 service (per the NENA 2.1 standard).
132
133 =item e911_type
134
135 Type of Service for E911 service.
136
137 =item circuit_svcnum
138
139 The L<FS::svc_circuit> record for the physical circuit that transports this
140 phone line.
141
142 =item sip_server
143
144 The hostname of the SIP server that this phone number is routed to.
145
146 =back
147
148 =head1 METHODS
149
150 =over 4
151
152 =item new HASHREF
153
154 Creates a new phone number.  To add the number to the database, see L<"insert">.
155
156 Note that this stores the hash reference, not a distinct copy of the hash it
157 points to.  You can ask the object for a copy with the I<hash> method.
158
159 =cut
160
161 # the new method can be inherited from FS::Record, if a table method is defined
162 #
163 sub table_info {
164  my %dis2 = ( disable_inventory=>1, disable_select=>1 );
165   {
166     'name' => 'Phone number',
167     'sorts' => 'phonenum',
168     'display_weight' => 60,
169     'cancel_weight'  => 80,
170     'fields' => {
171         'svcnum'       => 'Service',
172         'countrycode'  => { label => 'Country code',
173                             type  => 'text',
174                             disable_inventory => 1,
175                             disable_select => 1,
176                           },
177         'phonenum'     => 'Phone number',
178         'sim_imsi'     => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
179         'pin'          => { label => 'Voicemail PIN', #'Personal Identification Number',
180                             type  => 'text',
181                             disable_inventory => 1,
182                             disable_select => 1,
183                           },
184         'sip_password' => 'SIP password',
185         'phone_name'   => 'Name',
186         'pbxsvc'       => { label => 'PBX',
187                             type  => 'select-svc_pbx.html',
188                             disable_inventory => 1,
189                             disable_select => 1, #UI wonky, pry works otherwise
190                           },
191         'domsvc'    => {
192                          label     => 'Domain',
193                          type      => 'select',
194                          select_table => 'svc_domain',
195                          select_key   => 'svcnum',
196                          select_label => 'domain',
197                          disable_inventory => 1,
198                        },
199         'circuit_svcnum'   => { label             => 'Circuit',
200                                 type              => 'select',
201                                 select_table      => 'svc_domain',
202                                 select_key        => 'svcnum',
203                                 select_label      => 'circuit_label',
204                                 disable_inventory => 1,
205                               },
206
207         'sms_carrierid'    => { label             => 'SMS Carrier',
208                                 type              => 'select',
209                                 select_table      => 'cdr_carrier',
210                                 select_key        => 'carrierid',
211                                 select_label      => 'carriername',
212                                 disable_inventory => 1,
213                               },
214         'sms_account'      => { label => 'SMS Carrier Account', },
215         'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
216         'locationnum' => {
217                            label => 'E911 location',
218                            disable_inventory => 1,
219                            disable_select    => 1,
220                          },
221         'forwarddst' => {       label => 'Forward Destination', 
222                                 %dis2,
223                         },
224         'email' => {            label => 'Email',
225                                 %dis2,
226                     },
227         'lnp_status' => {       label => 'LNP Status',
228                                 type => 'select-lnp_status.html',
229                                 %dis2,
230                         },
231         'lnp_reject_reason' => { 
232                                 label => 'LNP Reject Reason',
233                                 %dis2,
234                         },
235         'portable' =>   {       label => 'Portable?', %dis2, },
236         'lrn'   =>      {       label => 'LRN', 
237                                 disable_inventory => 1, 
238                         },
239         'lnp_desired_due_date' =>
240                         { label => 'LNP Desired Due Date', %dis2 },
241         'lnp_due_date' =>
242                         { label => 'LNP Due Date', %dis2 },
243         'lnp_other_provider' =>
244                         {       label => 'LNP Other Provider', 
245                                 disable_inventory => 1, 
246                         },
247         'lnp_other_provider_account' =>
248                         {       label => 'LNP Other Provider Account #', 
249                                 %dis2 
250                         },
251         'e911_class' => {
252                                 label => 'E911 Service Class',
253                                 type  => 'select-e911_class',
254                                 disable_inventory => 1,
255                                 multiple => 1,
256                         },
257         'e911_type' => {
258                                 label => 'E911 Service Type',
259                                 type  => 'select-e911_type',
260                                 disable_inventory => 1,
261                                 multiple => 1,
262                         },
263         'sip_server'  => {
264                                 label => 'SIP Host',
265                                 %dis2,
266                          },
267     },
268   };
269 }
270
271 sub table { 'svc_phone'; }
272
273 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
274
275 =item search_sql STRING
276
277 Class method which returns an SQL fragment to search for the given string.
278
279 =cut
280
281 sub search_sql {
282   my( $class, $string ) = @_;
283
284   #my $conf = new FS::Conf;
285
286   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
287     $string =~ s/\W//g;
288   } else {
289     $string =~ s/\D//g;
290   }
291
292   my $ccode = (    $conf->exists('default_phone_countrycode')
293                 && $conf->config('default_phone_countrycode')
294               )
295                 ? $conf->config('default_phone_countrycode') 
296                 : '1';
297
298   $string =~ s/^$ccode//;
299
300   $class->search_sql_field('phonenum', $string );
301 }
302
303 =item label
304
305 Returns the phone number.
306
307 =cut
308
309 sub label {
310   my $self = shift;
311   my $phonenum = $self->phonenum; #XXX format it better
312   my $label = $phonenum;
313   $label .= '@'.$self->domain if $self->domsvc;
314   $label .= ' ('.$self->phone_name.')' if $self->phone_name;
315   $label;
316 }
317
318 =item insert
319
320 Adds this phone number to the database.  If there is an error, returns the
321 error, otherwise returns false.
322
323 =cut
324
325 sub insert {
326   my $self = shift;
327   my %options = @_;
328
329   if ( $DEBUG ) {
330     warn "[$me] insert called on $self: ". Dumper($self).
331          "\nwith options: ". Dumper(%options);
332   }
333
334   local $SIG{HUP} = 'IGNORE';
335   local $SIG{INT} = 'IGNORE';
336   local $SIG{QUIT} = 'IGNORE';
337   local $SIG{TERM} = 'IGNORE';
338   local $SIG{TSTP} = 'IGNORE';
339   local $SIG{PIPE} = 'IGNORE';
340
341   my $oldAutoCommit = $FS::UID::AutoCommit;
342   local $FS::UID::AutoCommit = 0;
343   my $dbh = dbh;
344
345   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
346   #make it more of a base class than a mixin... :)
347   if ( $options{'cust_location'} ) {
348     my $error = $options{'cust_location'}->find_or_insert;
349     if ( $error ) {
350       $dbh->rollback if $oldAutoCommit;
351       return "inserting cust_location (transaction rolled back): $error";
352     }
353     $self->locationnum( $options{'cust_location'}->locationnum );
354   }
355   #what about on-the-fly edits?  if the ui supports it?
356
357   my $error = $self->SUPER::insert(%options);
358   if ( $error ) {
359     $dbh->rollback if $oldAutoCommit;
360     return $error;
361   }
362
363   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
364   '';
365
366 }
367
368 =item delete
369
370 Delete this record from the database.
371
372 =cut
373
374 sub delete {
375   my $self = shift;
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   foreach my $phone_device ( $self->phone_device ) {
389     my $error = $phone_device->delete;
390     if ( $error ) {
391       $dbh->rollback if $oldAutoCommit;
392       return $error;
393     }
394   }
395
396   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
397   foreach my $phone_avail ( @phone_avail ) {
398     $phone_avail->svcnum('');
399     my $error = $phone_avail->replace;
400     if ( $error ) {
401       $dbh->rollback if $oldAutoCommit;
402       return $error;
403     }
404   }
405
406   my $error = $self->SUPER::delete;
407   if ( $error ) {
408     $dbh->rollback if $oldAutoCommit;
409     return $error;
410   }
411
412   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
413   '';
414
415 }
416
417 # the delete method can be inherited from FS::Record
418
419 =item replace OLD_RECORD
420
421 Replaces the OLD_RECORD with this one in the database.  If there is an error,
422 returns the error, otherwise returns false.
423
424 =cut
425
426 sub replace {
427   my $new = shift;
428
429   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
430               ? shift
431               : $new->replace_old;
432
433   my %options = @_;
434
435   if ( $DEBUG ) {
436     warn "[$me] replacing $old with $new\n".
437          "\nwith options: ". Dumper(%options);
438   }
439
440   local $SIG{HUP} = 'IGNORE';
441   local $SIG{INT} = 'IGNORE';
442   local $SIG{QUIT} = 'IGNORE';
443   local $SIG{TERM} = 'IGNORE';
444   local $SIG{TSTP} = 'IGNORE';
445   local $SIG{PIPE} = 'IGNORE';
446
447   my $oldAutoCommit = $FS::UID::AutoCommit;
448   local $FS::UID::AutoCommit = 0;
449   my $dbh = dbh;
450
451   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
452   #make it more of a base class than a mixin... :)
453   if ( $options{'cust_location'}
454          && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
455     my $error = $options{'cust_location'}->insert;
456     if ( $error ) {
457       $dbh->rollback if $oldAutoCommit;
458       return "inserting cust_location (transaction rolled back): $error";
459     }
460     $new->locationnum( $options{'cust_location'}->locationnum );
461   }
462   #what about on-the-fly edits?  if the ui supports it?
463
464   # LNP data validation
465  return 'Invalid LNP status' # if someone does really stupid stuff
466     if (  ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
467         || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
468         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
469         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
470         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
471         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
472         || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
473         );
474
475   my $error = $new->SUPER::replace($old, %options);
476
477   # if this changed the e911 location, notify exports
478   if ($new->locationnum ne $old->locationnum) {
479     my $new_location = $new->cust_location_or_main;
480     my $old_location = $new->cust_location_or_main;
481     $error ||= $new->export('relocate', $new_location, $old_location);
482   }
483
484   if ( $error ) {
485     $dbh->rollback if $oldAutoCommit;
486     return $error if $error;
487   }
488
489
490   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
491   ''; #no error
492 }
493
494 =item suspend
495
496 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
497
498 =item unsuspend
499
500 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
501
502 =item cancel
503
504 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
505
506 =item check
507
508 Checks all fields to make sure this is a valid phone number.  If there is
509 an error, returns the error, otherwise returns false.  Called by the insert
510 and replace methods.
511
512 =cut
513
514 # the check method should currently be supplied - FS::Record contains some
515 # data checking routines
516
517 sub check {
518   my $self = shift;
519
520   #my $conf = new FS::Conf;
521
522   my $x = $self->setfixed;
523   return $x unless ref($x);
524   my $part_svc = $x;
525
526   my $phonenum = $self->phonenum;
527   my $phonenum_check_method;
528   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
529     $phonenum =~ s/\W//g;
530     $phonenum_check_method = 'ut_alpha';
531   } else {
532     $phonenum =~ s/\D//g;
533     $phonenum_check_method = 'ut_number';
534   }
535   $self->phonenum($phonenum);
536
537   $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
538
539   my $error = 
540     $self->ut_numbern('svcnum')
541     || $self->ut_numbern('countrycode')
542     || $self->$phonenum_check_method('phonenum')
543     || $self->ut_numbern('sim_imsi')
544     || $self->ut_anything('sip_password')
545     || $self->ut_numbern('pin')
546     || $self->ut_textn('phone_name')
547     || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx',    'svcnum' )
548     || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
549     || $self->ut_foreign_keyn('sms_carrierid', 'cdr_carrier', 'carrierid' )
550     || $self->ut_alphan('sms_account')
551     || $self->ut_numbern('max_simultaneous')
552     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
553     || $self->ut_numbern('forwarddst')
554     || $self->ut_textn('email')
555     || $self->ut_numbern('lrn')
556     || $self->ut_numbern('lnp_desired_due_date')
557     || $self->ut_numbern('lnp_due_date')
558     || $self->ut_textn('lnp_other_provider')
559     || $self->ut_textn('lnp_other_provider_account')
560     || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
561                                 'native', 'portin-reject', 'portout-reject'])
562     || $self->ut_enumn('portable', ['','Y'])
563     || $self->ut_textn('lnp_reject_reason')
564     || $self->ut_domainn('sip_server')
565   ;
566   return $error if $error;
567
568   return 'Illegal IMSI (not 14-15 digits)' #shorter?
569     if length($self->sim_imsi)
570     && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
571
572     # LNP data validation
573     return 'Cannot set LNP fields: no LNP in progress'
574         if ( ($self->lnp_desired_due_date || $self->lnp_due_date 
575             || $self->lnp_other_provider || $self->lnp_other_provider_account
576             || $self->lnp_reject_reason) 
577             && (!$self->lnp_status || $self->lnp_status eq 'native') );
578     return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
579         if ($self->lnp_reject_reason && (!$self->lnp_status 
580                             || $self->lnp_status !~ /^port(in|out)-reject$/) );
581     return 'Cannot port-out a non-portable number' 
582         if (!$self->portable && $self->lnp_status eq 'portingout');
583
584
585   return 'Name ('. $self->phone_name.
586          ") is longer than $phone_name_max characters"
587     if $phone_name_max && length($self->phone_name) > $phone_name_max;
588
589   $self->countrycode(1) unless $self->countrycode;
590
591   unless ( length($self->pin) ) {
592     my $random_pin = $conf->config('svc_phone-random_pin');
593     if ( defined($random_pin) && $random_pin =~ /^\d+$/ ) {
594       $self->pin(
595         join('', map int(rand(10)), 0..($random_pin-1))
596       );
597     }
598   }
599
600   if ( length($self->sip_password) ) {
601
602     return "SIP password must be longer than $passwordmin characters"
603       if length($self->sip_password) < $passwordmin;
604     return "SIP password must be shorter than $passwordmax characters"
605       if length($self->sip_password) > $passwordmax;
606
607   } elsif ( $part_svc->part_svc_column('sip_password')->columnflag ne 'F' ) {
608
609     # option for this?
610     $self->sip_password(
611       join('', map $pw_set[ int(rand $#pw_set) ], (1..min($passwordmax,16)) )
612     );
613
614   }
615
616   if ($self->e911_class and !exists(e911_classes()->{$self->e911_class})) {
617     return "undefined e911 class '".$self->e911_class."'";
618   }
619   if ($self->e911_type and !exists(e911_types()->{$self->e911_type})) {
620     return "undefined e911 type '".$self->e911_type."'";
621   }
622
623   $self->SUPER::check;
624 }
625
626 =item _check duplicate
627
628 Internal method to check for duplicate phone numers.
629
630 =cut
631
632 #false laziness w/svc_acct.pm's _check_duplicate.
633 sub _check_duplicate {
634   my $self = shift;
635
636   my $global_unique = $conf->config('global_unique-phonenum') || 'none';
637   return '' if $global_unique eq 'disabled';
638
639   $self->lock_table;
640
641   my @dup_ccphonenum =
642     grep { !$self->svcnum || $_->svcnum != $self->svcnum }
643     qsearch( 'svc_phone', {
644       'countrycode' => $self->countrycode,
645       'phonenum'    => $self->phonenum,
646     });
647
648   return gettext('phonenum_in_use')
649     if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
650
651   my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
652   unless ( $part_svc ) {
653     return 'unknown svcpart '. $self->svcpart;
654   }
655
656   if ( @dup_ccphonenum ) {
657
658     my $exports = FS::part_export::export_info('svc_phone');
659     my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
660
661     foreach my $part_export ( $part_svc->part_export ) {
662
663       #this will catch to the same exact export
664       my @svcparts = map { $_->svcpart } $part_export->export_svc;
665
666       $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
667         foreach @svcparts;
668
669     }
670
671     foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
672       my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
673       if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
674         return "duplicate phone number ".
675                $self->countrycode. ' '. $self->phonenum.
676                ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
677                " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
678       }
679     }
680
681   }
682
683   return '';
684
685 }
686
687 =item check_pin
688
689 Checks the supplied PIN against the PIN in the database.  Returns true for a
690 sucessful authentication, false if no match.
691
692 =cut
693
694 sub check_pin {
695   my($self, $check_pin) = @_;
696   length($self->pin) && $check_pin eq $self->pin;
697 }
698
699 =item radius_reply
700
701 =cut
702
703 sub radius_reply {
704   my $self = shift;
705   #XXX Session-Timeout!  holy shit, need rlm_perl to ask for this in realtime
706   ();
707 }
708
709 =item radius_check
710
711 =cut
712
713 sub radius_check {
714   my $self = shift;
715   my %check = ();
716
717   #my $conf = new FS::Conf;
718
719   my $password;
720   if ( $conf->config('svc_phone-radius-password') eq 'countrycode_phonenum' ) {
721     $password = $self->countrycode. $self->phonenum;
722   } else {
723     $password = $conf->config('svc_phone-radius-default_password');
724   }
725   $check{'User-Password'} = $password;
726
727   %check;
728 }
729
730 sub radius_groups {
731   ();
732 }
733
734 =item sms_cdr_carrier
735
736 Returns the L<FS::cdr_carrier> assigned as the SMS carrier for this phone.
737
738 =cut
739
740 sub sms_cdr_carrier {
741   my $self = shift;
742   return '' unless $self->sms_carrierid;
743   qsearchs('cdr_carrier',  { 'carrierid' => $self->sms_carrierid } );
744 }
745
746 =item sms_carriername
747
748 Returns the name of the SMS carrier, or an empty string if there isn't one.
749
750 =cut
751
752 sub sms_carriername {
753   my $self = shift;
754   my $cdr_carrier = $self->sms_cdr_carrier or return '';
755   $cdr_carrier->carriername;
756 }
757
758 =item svc_circuit
759
760 Returns the L<FS::svc_circuit> assigned as the trunk for this phone line.
761
762 =item circuit_label
763
764 Returns the label of the circuit (the part_svc label followed by the 
765 circuit ID), or an empty string if there isn't one.
766
767 =cut
768
769 sub svc_circuit {
770   my $self = shift;
771   my $svcnum = $self->get('circuit_svcnum') or return '';
772   return FS::svc_circuit->by_key($svcnum);
773 }
774
775 sub circuit_label {
776   my $self = shift;
777   my $svc_circuit = $self->svc_circuit or return '';
778   return join(' ', $svc_circuit->part_svc->svc, $svc_circuit->circuit_id);
779 }
780
781 =item phone_device
782
783 Returns any FS::phone_device records associated with this service.
784
785 =cut
786
787 sub phone_device {
788   my $self = shift;
789   qsearch('phone_device', { 'svcnum' => $self->svcnum } );
790 }
791
792 #override location_Mixin version cause we want to try the cust_pkg location
793 #in between us and cust_main
794 # XXX what to do in the unlinked case???  return a pseudo-object that returns
795 # empty fields?
796 sub cust_location_or_main {
797   my $self = shift;
798   return $self->cust_location if $self->locationnum;
799   my $cust_pkg = $self->cust_svc->cust_pkg;
800   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
801 }
802
803 =item phone_name_or_cust
804
805 Returns the C<phone_name> field if it has a value, or the package contact
806 name if there is one, or the customer contact name.
807
808 =cut
809
810 sub phone_name_or_cust {
811   my $self = shift;
812   if ( $self->phone_name ) {
813     return $self->phone_name;
814   }
815   my $cust_pkg = $self->cust_svc->cust_pkg or return '';
816   if ( $cust_pkg->contactnum ) {
817     return $cust_pkg->contact->firstlast;
818   } else {
819     return $cust_pkg->cust_main->name_short;
820   }
821 }
822
823 =item psearch_cdrs OPTIONS
824
825 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records 
826 associated with this service.  By default, "associated with" means that 
827 either the "src" or the "charged_party" field of the CDR matches the 
828 "phonenum" field of the service.  To access the CDRs themselves, call
829 "->fetch" on the resulting object.
830
831 =over 2
832
833 Accepts the following options:
834
835 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
836
837 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
838
839 =item inbound => 1: Return CDRs for inbound calls (that is, those that match
840 on 'dst').  With "status", will filter on inbound processing status.
841
842 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
843 with the chosen prefix.
844
845 =item begin, end: Start and end of a date range, as unix timestamp.
846
847 =item cdrtypenum: Only return CDRs with this type.
848
849 =item calltypenum: Only return CDRs with this call type.
850
851 =item disable_src => 1: Only match on 'charged_party', not 'src'.
852
853 =item disable_charged_party => 1: Only match on 'src', not 'charged_party'.
854
855 =item nonzero: Only return CDRs where duration > 0.
856
857 =item by_svcnum: not supported for svc_phone
858
859 =item billsec_sum: Instead of returning all of the CDRs, return a single
860 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over 
861 the entire result set.
862
863 =back
864
865 =cut
866
867 sub psearch_cdrs {
868
869   my($self, %options) = @_;
870   my @fields;
871   my %hash;
872   my @where;
873
874   if ( $options{'inbound'} ) {
875
876     @fields = ( 'dst' );
877     if ( exists($options{'status'}) ) {
878       my $status = $options{'status'};
879       if ( $status ) {
880         push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
881           'WHERE cdr.acctid = cdr_termination.acctid '.
882           "AND cdr_termination.status = '$status' ". #quoting kludge
883           'AND cdr_termination.termpart = 1 )';
884       } else {
885         push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
886           'WHERE cdr.acctid = cdr_termination.acctid '.
887           'AND cdr_termination.termpart = 1 )';
888       }
889     }
890
891   } else {
892
893     push @fields, 'charged_party' unless $options{'disable_charged_party'};
894     push @fields, 'src' unless $options{'disable_src'};
895     $hash{'freesidestatus'} = $options{'status'}
896       if exists($options{'status'});
897   }
898
899   if ($options{'cdrtypenum'}) {
900     $hash{'cdrtypenum'} = $options{'cdrtypenum'};
901   }
902   if ($options{'calltypenum'}) {
903     $hash{'calltypenum'} = $options{'calltypenum'};
904   }
905   
906   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
907
908   my $number = $self->phonenum;
909
910   my $prefix = $options{'default_prefix'};
911
912   my @orwhere =  map " $_ = '$number'        ", @fields;
913   push @orwhere, map " $_ = '$prefix$number' ", @fields
914     if defined($prefix) && length($prefix);
915   if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
916     push @orwhere, map " $_ = '$1$number' ", @fields
917   }
918
919   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
920
921   if ( $options{'begin'} ) {
922     push @where, 'startdate >= '. $options{'begin'};
923   }
924   if ( $options{'end'} ) {
925     push @where, 'startdate < '.  $options{'end'};
926   }
927   if ( $options{'nonzero'} ) {
928     push @where, 'duration > 0';
929   }
930
931   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
932
933   psearch( {
934       'table'      => 'cdr',
935       'hashref'    => \%hash,
936       'extra_sql'  => $extra_sql,
937       'order_by'   => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
938       'select'     => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
939   } );
940 }
941
942 =item get_cdrs (DEPRECATED)
943
944 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a 
945 single list.  Arguments are the same as for psearch_cdrs.  This can take 
946 an unreasonably large amount of memory and is best avoided.
947
948 =cut
949
950 sub get_cdrs {
951   my $self = shift;
952   my $psearch = $self->psearch_cdrs(@_);
953   qsearch ( $psearch->{query} )
954 }
955
956 =item sum_cdrs
957
958 Takes the same options as psearch_cdrs, but returns a single row containing
959 "count" (the number of CDRs) and the sums of the following fields: duration,
960 billsec, rated_price, rated_seconds, rated_minutes.
961
962 Note that if any calls are not rated, their rated_* fields will be null.
963 If you want to use those fields, pass the 'status' option to limit to 
964 calls that have been rated.  This is intentional; please don't "fix" it.
965
966 =cut
967
968 sub sum_cdrs {
969   my $self = shift;
970   my $psearch = $self->psearch_cdrs(@_);
971   $psearch->{query}->{'select'} = join(',',
972     'COUNT(*) AS count',
973     map { "SUM($_) AS $_" }
974       qw(duration billsec rated_price rated_seconds rated_minutes)
975   );
976   # hack
977   $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
978   qsearchs ( $psearch->{query} );
979 }
980
981 =back
982
983 =head1 CLASS METHODS
984
985 =over 4
986
987 =item e911_classes
988
989 Returns a hashref of allowed values and descriptions for the C<e911_class>
990 field.
991
992 =item e911_types
993
994 Returns a hashref of allowed values and descriptions for the C<e911_type>
995 field.
996
997 =cut
998
999 sub e911_classes {
1000   tie my %x, 'Tie::IxHash', (
1001     1 => 'Residence',
1002     2 => 'Business',
1003     3 => 'Residence PBX',
1004     4 => 'Business PBX',
1005     5 => 'Centrex',
1006     6 => 'Coin 1 Way out',
1007     7 => 'Coin 2 Way',
1008     8 => 'Mobile',
1009     9 => 'Residence OPX',
1010     0 => 'Business OPX',
1011     A => 'Customer Operated Coin Telephone',
1012     #B => not available
1013     G => 'Wireless Phase I',
1014     H => 'Wireless Phase II',
1015     I => 'Wireless Phase II with Phase I information',
1016     V => 'VoIP Services Default',
1017     C => 'VoIP Residence',
1018     D => 'VoIP Business',
1019     E => 'VoIP Coin/Pay Phone',
1020     F => 'VoIP Wireless',
1021     J => 'VoIP Nomadic',
1022     K => 'VoIP Enterprise Services',
1023     T => 'Telematics',
1024   );
1025   \%x;
1026 }
1027
1028 sub e911_types {
1029   tie my %x, 'Tie::IxHash', (
1030     0 => 'Not FX nor Non-Published',
1031     1 => 'FX in 911 serving area',
1032     2 => 'FX outside 911 serving area',
1033     3 => 'Non-Published',
1034     4 => 'Non-Published FX in serving area',
1035     5 => 'Non-Published FX outside serving area',
1036     6 => 'Local Ported Number',
1037     7 => 'Interim Ported Number',
1038   );
1039   \%x;
1040 }
1041
1042 =back
1043
1044 =head1 BUGS
1045
1046 =head1 SEE ALSO
1047
1048 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
1049 L<FS::cust_pkg>, schema.html from the base documentation.
1050
1051 =cut
1052
1053 1;
1054