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