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