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