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