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