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