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