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