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