fix svc_phone provisioning with new location, RT#34069
[freeside.git] / FS / FS / svc_phone.pm
1 package FS::svc_phone;
2 use base qw( FS::svc_Domain_Mixin FS::svc_PBX_Mixin 
3              FS::location_Mixin
4              FS::svc_Common
5            );
6
7 use strict;
8 use vars qw( $DEBUG $me @pw_set $conf $phone_name_max
9              $passwordmin $passwordmax
10            );
11 use Data::Dumper;
12 use Scalar::Util qw( blessed );
13 use List::Util qw( min );
14 use Tie::IxHash;
15 use FS::Conf;
16 use FS::Record qw( qsearch qsearchs dbh );
17 use FS::PagedSearch qw( psearch );
18 use FS::Msgcat qw(gettext);
19 use FS::part_svc;
20 use FS::svc_pbx;
21 use FS::svc_domain;
22 use FS::cust_location;
23 use FS::phone_avail;
24
25 $me = '[' . __PACKAGE__ . ']';
26 $DEBUG = 0;
27
28 #avoid l 1 and o O 0
29 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
30
31 #ask FS::UID to run this stuff for us later
32 FS::UID->install_callback( sub { 
33   $conf = new FS::Conf;
34   $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
35   $passwordmin = $conf->config('sip_passwordmin') || 0;
36   $passwordmax = $conf->config('sip_passwordmax') || 80;
37 }
38 );
39
40 =head1 NAME
41
42 FS::svc_phone - Object methods for svc_phone records
43
44 =head1 SYNOPSIS
45
46   use FS::svc_phone;
47
48   $record = new FS::svc_phone \%hash;
49   $record = new FS::svc_phone { 'column' => 'value' };
50
51   $error = $record->insert;
52
53   $error = $new_record->replace($old_record);
54
55   $error = $record->delete;
56
57   $error = $record->check;
58
59   $error = $record->suspend;
60
61   $error = $record->unsuspend;
62
63   $error = $record->cancel;
64
65 =head1 DESCRIPTION
66
67 An FS::svc_phone object represents a phone number.  FS::svc_phone inherits
68 from FS::Record.  The following fields are currently supported:
69
70 =over 4
71
72 =item svcnum
73
74 primary key
75
76 =item countrycode
77
78 =item phonenum
79
80 =item sim_imsi
81
82 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
83
84 =item sip_password
85
86 =item pin
87
88 Voicemail PIN
89
90 =item phone_name
91
92 =item pbxsvc
93
94 Optional svcnum from svc_pbx
95
96 =item forwarddst
97
98 Forwarding destination
99
100 =item email
101
102 Email address for virtual fax (fax-to-email) services
103
104 =item lnp_status
105
106 LNP Status (can be null, native, portedin, portingin, portin-reject,
107 portingout, portout-reject)
108
109 =item portable
110
111 =item lrn
112
113 =item lnp_desired_due_date
114
115 =item lnp_due_date
116
117 =item lnp_other_provider
118
119 If porting the number in or out, name of the losing or winning provider, 
120 respectively.
121
122 =item lnp_other_provider_account
123
124 Account number of other provider. See lnp_other_provider.
125
126 =item lnp_reject_reason
127
128 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
129 optional reject reason.
130
131 =item e911_class
132
133 Class of Service for E911 service (per the NENA 2.1 standard).
134
135 =item e911_type
136
137 Type of Service for E911 service.
138
139 =item circuit_svcnum
140
141 The L<FS::svc_circuit> record for the physical circuit that transports this
142 phone line.
143
144 =item sip_server
145
146 The hostname of the SIP server that this phone number is routed to.
147
148 =back
149
150 =head1 METHODS
151
152 =over 4
153
154 =item new HASHREF
155
156 Creates a new phone number.  To add the number to the database, see L<"insert">.
157
158 Note that this stores the hash reference, not a distinct copy of the hash it
159 points to.  You can ask the object for a copy with the I<hash> method.
160
161 =cut
162
163 # the new method can be inherited from FS::Record, if a table method is defined
164 #
165 sub table_info {
166  my %dis2 = ( disable_inventory=>1, disable_select=>1 );
167   {
168     'name' => 'Phone number',
169     'sorts' => 'phonenum',
170     'display_weight' => 60,
171     'cancel_weight'  => 80,
172     'fields' => {
173         'svcnum'       => 'Service',
174         'countrycode'  => { label => 'Country code',
175                             type  => 'text',
176                             disable_inventory => 1,
177                             disable_select => 1,
178                           },
179         'phonenum'     => 'Phone number',
180         'sim_imsi'     => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
181         'pin'          => { label => 'Voicemail PIN', #'Personal Identification Number',
182                             type  => 'text',
183                             disable_inventory => 1,
184                             disable_select => 1,
185                           },
186         'sip_password' => 'SIP password',
187         'phone_name'   => 'Name',
188         'pbxsvc'       => { label => 'PBX',
189                             type  => 'select-svc_pbx.html',
190                             disable_inventory => 1,
191                             disable_select => 1, #UI wonky, pry works otherwise
192                           },
193         'domsvc'    => {
194                          label     => 'Domain',
195                          type      => 'select',
196                          select_table => 'svc_domain',
197                          select_key   => 'svcnum',
198                          select_label => 'domain',
199                          select_allow_empty => 1,
200                          disable_inventory => 1,
201                        },
202         'circuit_svcnum'   => { label             => 'Circuit',
203                                 type              => 'select',
204                                 select_table      => 'svc_domain',
205                                 select_key        => 'svcnum',
206                                 select_label      => 'circuit_label',
207                                 disable_inventory => 1,
208                               },
209
210         'sms_carrierid'    => { label             => 'SMS Carrier',
211                                 type              => 'select',
212                                 select_table      => 'cdr_carrier',
213                                 select_key        => 'carrierid',
214                                 select_label      => 'carriername',
215                                 disable_inventory => 1,
216                               },
217         'sms_account'      => { label => 'SMS Carrier Account', },
218         'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
219         'locationnum' => {
220                            label => 'E911 location',
221                            disable_inventory => 1,
222                            disable_select    => 1,
223                          },
224         'forwarddst' => {       label => 'Forward Destination', 
225                                 %dis2,
226                         },
227         'email' => {            label => 'Email',
228                                 %dis2,
229                     },
230         'lnp_status' => {       label => 'LNP Status',
231                                 type => 'select-lnp_status.html',
232                                 %dis2,
233                         },
234         'lnp_reject_reason' => { 
235                                 label => 'LNP Reject Reason',
236                                 %dis2,
237                         },
238         'portable' =>   {       label => 'Portable?', %dis2, },
239         'lrn'   =>      {       label => 'LRN', 
240                                 disable_inventory => 1, 
241                         },
242         'lnp_desired_due_date' =>
243                         { label => 'LNP Desired Due Date', %dis2 },
244         'lnp_due_date' =>
245                         { label => 'LNP Due Date', %dis2 },
246         'lnp_other_provider' =>
247                         {       label => 'LNP Other Provider', 
248                                 disable_inventory => 1, 
249                         },
250         'lnp_other_provider_account' =>
251                         {       label => 'LNP Other Provider Account #', 
252                                 %dis2 
253                         },
254         'e911_class' => {
255                                 label => 'E911 Service Class',
256                                 type  => 'select-e911_class',
257                                 disable_inventory => 1,
258                                 multiple => 1,
259                         },
260         'e911_type' => {
261                                 label => 'E911 Service Type',
262                                 type  => 'select-e911_type',
263                                 disable_inventory => 1,
264                                 multiple => 1,
265                         },
266         'sip_server'  => {
267                                 label => 'SIP Host',
268                                 %dis2,
269                          },
270     },
271   };
272 }
273
274 sub table { 'svc_phone'; }
275
276 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
277
278 =item search_sql STRING
279
280 Class method which returns an SQL fragment to search for the given string.
281
282 =cut
283
284 sub search_sql {
285   my( $class, $string ) = @_;
286
287   #my $conf = new FS::Conf;
288
289   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
290     $string =~ s/\W//g;
291   } else {
292     $string =~ s/\D//g;
293   }
294
295   my $ccode = (    $conf->exists('default_phone_countrycode')
296                 && $conf->config('default_phone_countrycode')
297               )
298                 ? $conf->config('default_phone_countrycode') 
299                 : '1';
300
301   $string =~ s/^$ccode//;
302
303   $class->search_sql_field('phonenum', $string );
304 }
305
306 =item label
307
308 Returns the phone number.
309
310 =cut
311
312 sub label {
313   my $self = shift;
314   my $phonenum = $self->phonenum; #XXX format it better
315   my $label = $phonenum;
316   $label .= '@'.$self->domain if $self->domsvc;
317   $label .= ' ('.$self->phone_name.')' if $self->phone_name;
318   $label;
319 }
320
321 =item insert
322
323 Adds this phone number to the database.  If there is an error, returns the
324 error, otherwise returns false.
325
326 =cut
327
328 sub insert {
329   my $self = shift;
330   my %options = @_;
331
332   if ( $DEBUG ) {
333     warn "[$me] insert called on $self: ". Dumper($self).
334          "\nwith options: ". Dumper(%options);
335   }
336
337   local $SIG{HUP} = 'IGNORE';
338   local $SIG{INT} = 'IGNORE';
339   local $SIG{QUIT} = 'IGNORE';
340   local $SIG{TERM} = 'IGNORE';
341   local $SIG{TSTP} = 'IGNORE';
342   local $SIG{PIPE} = 'IGNORE';
343
344   my $oldAutoCommit = $FS::UID::AutoCommit;
345   local $FS::UID::AutoCommit = 0;
346   my $dbh = dbh;
347
348   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
349   #make it more of a base class than a mixin... :)
350   if ( $options{'cust_location'} ) {
351     $options{'cust_location'}->custnum( $self->cust_svc->cust_pkg->custnum );
352     my $error = $options{'cust_location'}->find_or_insert;
353     if ( $error ) {
354       $dbh->rollback if $oldAutoCommit;
355       return "inserting cust_location (transaction rolled back): $error";
356     }
357     $self->locationnum( $options{'cust_location'}->locationnum );
358   }
359   #what about on-the-fly edits?  if the ui supports it?
360
361   my $error = $self->SUPER::insert(%options);
362   if ( $error ) {
363     $dbh->rollback if $oldAutoCommit;
364     return $error;
365   }
366
367   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
368   '';
369
370 }
371
372 =item delete
373
374 Delete this record from the database.
375
376 =cut
377
378 sub delete {
379   my $self = shift;
380
381   local $SIG{HUP} = 'IGNORE';
382   local $SIG{INT} = 'IGNORE';
383   local $SIG{QUIT} = 'IGNORE';
384   local $SIG{TERM} = 'IGNORE';
385   local $SIG{TSTP} = 'IGNORE';
386   local $SIG{PIPE} = 'IGNORE';
387
388   my $oldAutoCommit = $FS::UID::AutoCommit;
389   local $FS::UID::AutoCommit = 0;
390   my $dbh = dbh;
391
392   foreach my $phone_device ( $self->phone_device ) {
393     my $error = $phone_device->delete;
394     if ( $error ) {
395       $dbh->rollback if $oldAutoCommit;
396       return $error;
397     }
398   }
399
400   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
401   foreach my $phone_avail ( @phone_avail ) {
402     $phone_avail->svcnum('');
403     my $error = $phone_avail->replace;
404     if ( $error ) {
405       $dbh->rollback if $oldAutoCommit;
406       return $error;
407     }
408   }
409
410   my $error = $self->SUPER::delete;
411   if ( $error ) {
412     $dbh->rollback if $oldAutoCommit;
413     return $error;
414   }
415
416   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
417   '';
418
419 }
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 #override location_Mixin version cause we want to try the cust_pkg location
790 #in between us and cust_main
791 # XXX what to do in the unlinked case???  return a pseudo-object that returns
792 # empty fields?
793 sub cust_location_or_main {
794   my $self = shift;
795   return $self->cust_location if $self->locationnum;
796   my $cust_pkg = $self->cust_svc->cust_pkg;
797   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
798 }
799
800 =item phone_name_or_cust
801
802 Returns the C<phone_name> field if it has a value, or the package contact
803 name if there is one, or the customer contact name.
804
805 =cut
806
807 sub phone_name_or_cust {
808   my $self = shift;
809   if ( $self->phone_name ) {
810     return $self->phone_name;
811   }
812   my $cust_pkg = $self->cust_svc->cust_pkg or return '';
813   if ( $cust_pkg->contactnum ) {
814     return $cust_pkg->contact->firstlast;
815   } else {
816     return $cust_pkg->cust_main->name_short;
817   }
818 }
819
820 =item psearch_cdrs OPTIONS
821
822 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records 
823 associated with this service.  By default, "associated with" means that 
824 either the "src" or the "charged_party" field of the CDR matches the 
825 "phonenum" field of the service.  To access the CDRs themselves, call
826 "->fetch" on the resulting object.
827
828 =over 2
829
830 Accepts the following options:
831
832 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
833
834 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
835
836 =item inbound => 1: Return CDRs for inbound calls (that is, those that match
837 on 'dst').  With "status", will filter on inbound processing status.
838
839 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
840 with the chosen prefix.
841
842 =item begin, end: Start and end of a date range, as unix timestamp.
843
844 =item cdrtypenum: Only return CDRs with this type.
845
846 =item calltypenum: Only return CDRs with this call type.
847
848 =item disable_src => 1: Only match on 'charged_party', not 'src'.
849
850 =item disable_charged_party => 1: Only match on 'src', not 'charged_party'.
851
852 =item nonzero: Only return CDRs where duration > 0.
853
854 =item by_svcnum: not supported for svc_phone
855
856 =item billsec_sum: Instead of returning all of the CDRs, return a single
857 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over 
858 the entire result set.
859
860 =back
861
862 =cut
863
864 sub psearch_cdrs {
865
866   my($self, %options) = @_;
867   my @fields;
868   my %hash;
869   my @where;
870
871   if ( $options{'inbound'} ) {
872
873     @fields = ( 'dst' );
874     if ( exists($options{'status'}) ) {
875       my $status = $options{'status'};
876       if ( $status ) {
877         push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
878           'WHERE cdr.acctid = cdr_termination.acctid '.
879           "AND cdr_termination.status = '$status' ". #quoting kludge
880           'AND cdr_termination.termpart = 1 )';
881       } else {
882         push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
883           'WHERE cdr.acctid = cdr_termination.acctid '.
884           'AND cdr_termination.termpart = 1 )';
885       }
886     }
887
888   } else {
889
890     push @fields, 'charged_party' unless $options{'disable_charged_party'};
891     push @fields, 'src' unless $options{'disable_src'};
892     $hash{'freesidestatus'} = $options{'status'}
893       if exists($options{'status'});
894   }
895
896   if ($options{'cdrtypenum'}) {
897     $hash{'cdrtypenum'} = $options{'cdrtypenum'};
898   }
899   if ($options{'calltypenum'}) {
900     $hash{'calltypenum'} = $options{'calltypenum'};
901   }
902   
903   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
904
905   my $number = $self->phonenum;
906
907   my $prefix = $options{'default_prefix'};
908
909   my @orwhere =  map " $_ = '$number'        ", @fields;
910   push @orwhere, map " $_ = '$prefix$number' ", @fields
911     if defined($prefix) && length($prefix);
912   if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
913     push @orwhere, map " $_ = '$1$number' ", @fields
914   }
915
916   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
917
918   if ( $options{'begin'} ) {
919     push @where, 'startdate >= '. $options{'begin'};
920   }
921   if ( $options{'end'} ) {
922     push @where, 'startdate < '.  $options{'end'};
923   }
924   if ( $options{'nonzero'} ) {
925     push @where, 'duration > 0';
926   }
927
928   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
929
930   psearch( {
931       'table'      => 'cdr',
932       'hashref'    => \%hash,
933       'extra_sql'  => $extra_sql,
934       'order_by'   => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
935       'select'     => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
936   } );
937 }
938
939 =item get_cdrs (DEPRECATED)
940
941 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a 
942 single list.  Arguments are the same as for psearch_cdrs.  This can take 
943 an unreasonably large amount of memory and is best avoided.
944
945 =cut
946
947 sub get_cdrs {
948   my $self = shift;
949   my $psearch = $self->psearch_cdrs(@_);
950   qsearch ( $psearch->{query} )
951 }
952
953 =item sum_cdrs
954
955 Takes the same options as psearch_cdrs, but returns a single row containing
956 "count" (the number of CDRs) and the sums of the following fields: duration,
957 billsec, rated_price, rated_seconds, rated_minutes.
958
959 Note that if any calls are not rated, their rated_* fields will be null.
960 If you want to use those fields, pass the 'status' option to limit to 
961 calls that have been rated.  This is intentional; please don't "fix" it.
962
963 =cut
964
965 sub sum_cdrs {
966   my $self = shift;
967   my $psearch = $self->psearch_cdrs(@_);
968   $psearch->{query}->{'select'} = join(',',
969     'COUNT(*) AS count',
970     map { "SUM($_) AS $_" }
971       qw(duration billsec rated_price rated_seconds rated_minutes)
972   );
973   # hack
974   $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
975   qsearchs ( $psearch->{query} );
976 }
977
978 =back
979
980 =head1 CLASS METHODS
981
982 =over 4
983
984 =item e911_classes
985
986 Returns a hashref of allowed values and descriptions for the C<e911_class>
987 field.
988
989 =item e911_types
990
991 Returns a hashref of allowed values and descriptions for the C<e911_type>
992 field.
993
994 =cut
995
996 sub e911_classes {
997   tie my %x, 'Tie::IxHash', (
998     1 => 'Residence',
999     2 => 'Business',
1000     3 => 'Residence PBX',
1001     4 => 'Business PBX',
1002     5 => 'Centrex',
1003     6 => 'Coin 1 Way out',
1004     7 => 'Coin 2 Way',
1005     8 => 'Mobile',
1006     9 => 'Residence OPX',
1007     0 => 'Business OPX',
1008     A => 'Customer Operated Coin Telephone',
1009     #B => not available
1010     G => 'Wireless Phase I',
1011     H => 'Wireless Phase II',
1012     I => 'Wireless Phase II with Phase I information',
1013     V => 'VoIP Services Default',
1014     C => 'VoIP Residence',
1015     D => 'VoIP Business',
1016     E => 'VoIP Coin/Pay Phone',
1017     F => 'VoIP Wireless',
1018     J => 'VoIP Nomadic',
1019     K => 'VoIP Enterprise Services',
1020     T => 'Telematics',
1021   );
1022   \%x;
1023 }
1024
1025 sub e911_types {
1026   tie my %x, 'Tie::IxHash', (
1027     0 => 'Not FX nor Non-Published',
1028     1 => 'FX in 911 serving area',
1029     2 => 'FX outside 911 serving area',
1030     3 => 'Non-Published',
1031     4 => 'Non-Published FX in serving area',
1032     5 => 'Non-Published FX outside serving area',
1033     6 => 'Local Ported Number',
1034     7 => 'Interim Ported Number',
1035   );
1036   \%x;
1037 }
1038
1039 =back
1040
1041 =head1 BUGS
1042
1043 =head1 SEE ALSO
1044
1045 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
1046 L<FS::cust_pkg>, schema.html from the base documentation.
1047
1048 =cut
1049
1050 1;
1051