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