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