NENA2 E911 export and batch-oriented exports in general, #14049
[freeside.git] / FS / FS / svc_phone.pm
1 package FS::svc_phone;
2
3 use strict;
4 use base qw( FS::svc_Domain_Mixin FS::location_Mixin FS::svc_Common );
5 use vars qw( $DEBUG $me @pw_set $conf $phone_name_max
6              $passwordmin $passwordmax
7            );
8 use Data::Dumper;
9 use Scalar::Util qw( blessed );
10 use List::Util qw( min );
11 use Tie::IxHash;
12 use FS::Conf;
13 use FS::Record qw( qsearch qsearchs dbh );
14 use FS::PagedSearch qw( psearch );
15 use FS::Msgcat qw(gettext);
16 use FS::part_svc;
17 use FS::phone_device;
18 use FS::svc_pbx;
19 use FS::svc_domain;
20 use FS::cust_location;
21 use FS::phone_avail;
22
23 $me = '[' . __PACKAGE__ . ']';
24 $DEBUG = 0;
25
26 #avoid l 1 and o O 0
27 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
28
29 #ask FS::UID to run this stuff for us later
30 FS::UID->install_callback( sub { 
31   $conf = new FS::Conf;
32   $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
33   $passwordmin = $conf->config('sip_passwordmin') || 0;
34   $passwordmax = $conf->config('sip_passwordmax') || 80;
35 }
36 );
37
38 =head1 NAME
39
40 FS::svc_phone - Object methods for svc_phone records
41
42 =head1 SYNOPSIS
43
44   use FS::svc_phone;
45
46   $record = new FS::svc_phone \%hash;
47   $record = new FS::svc_phone { 'column' => 'value' };
48
49   $error = $record->insert;
50
51   $error = $new_record->replace($old_record);
52
53   $error = $record->delete;
54
55   $error = $record->check;
56
57   $error = $record->suspend;
58
59   $error = $record->unsuspend;
60
61   $error = $record->cancel;
62
63 =head1 DESCRIPTION
64
65 An FS::svc_phone object represents a phone number.  FS::svc_phone inherits
66 from FS::Record.  The following fields are currently supported:
67
68 =over 4
69
70 =item svcnum
71
72 primary key
73
74 =item countrycode
75
76 =item phonenum
77
78 =item sim_imsi
79
80 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
81
82 =item sip_password
83
84 =item pin
85
86 Voicemail PIN
87
88 =item phone_name
89
90 =item pbxsvc
91
92 Optional svcnum from svc_pbx
93
94 =item forwarddst
95
96 Forwarding destination
97
98 =item email
99
100 Email address for virtual fax (fax-to-email) services
101
102 =item lnp_status
103
104 LNP Status (can be null, native, portedin, portingin, portin-reject,
105 portingout, portout-reject)
106
107 =item portable
108
109 =item lrn
110
111 =item lnp_desired_due_date
112
113 =item lnp_due_date
114
115 =item lnp_other_provider
116
117 If porting the number in or out, name of the losing or winning provider, 
118 respectively.
119
120 =item lnp_other_provider_account
121
122 Account number of other provider. See lnp_other_provider.
123
124 =item lnp_reject_reason
125
126 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
127 optional reject reason.
128
129 =item e911_class
130
131 Class of Service for E911 service (per the NENA 2.1 standard).
132
133 =item e911_type
134
135 Type of Service for E911 service.
136
137 =back
138
139 =head1 METHODS
140
141 =over 4
142
143 =item new HASHREF
144
145 Creates a new phone number.  To add the number to the database, see L<"insert">.
146
147 Note that this stores the hash reference, not a distinct copy of the hash it
148 points to.  You can ask the object for a copy with the I<hash> method.
149
150 =cut
151
152 # the new method can be inherited from FS::Record, if a table method is defined
153 #
154 sub table_info {
155  my %dis2 = ( disable_inventory=>1, disable_select=>1 );
156   {
157     'name' => 'Phone number',
158     'sorts' => 'phonenum',
159     'display_weight' => 60,
160     'cancel_weight'  => 80,
161     'fields' => {
162         'svcnum'       => 'Service',
163         'countrycode'  => { label => 'Country code',
164                             type  => 'text',
165                             disable_inventory => 1,
166                             disable_select => 1,
167                           },
168         'phonenum'     => 'Phone number',
169         'sim_imsi'     => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
170         'pin'          => { label => 'Voicemail PIN', #'Personal Identification Number',
171                             type  => 'text',
172                             disable_inventory => 1,
173                             disable_select => 1,
174                           },
175         'sip_password' => 'SIP password',
176         'phone_name'   => 'Name',
177         'pbxsvc'       => { label => 'PBX',
178                             type  => 'select-svc_pbx.html',
179                             disable_inventory => 1,
180                             disable_select => 1, #UI wonky, pry works otherwise
181                           },
182         'domsvc'    => {
183                          label     => 'Domain',
184                          type      => 'select',
185                          select_table => 'svc_domain',
186                          select_key   => 'svcnum',
187                          select_label => 'domain',
188                          disable_inventory => 1,
189                        },
190         'sms_carrierid'    => { label             => 'SMS Carrier',
191                                 type              => 'select',
192                                 select_table      => 'cdr_carrier',
193                                 select_key        => 'carrierid',
194                                 select_label      => 'carriername',
195                                 disable_inventory => 1,
196                               },
197         'sms_account'      => { label => 'SMS Carrier Account', },
198         'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
199         'locationnum' => {
200                            label => 'E911 location',
201                            disable_inventory => 1,
202                            disable_select    => 1,
203                          },
204         'forwarddst' => {       label => 'Forward Destination', 
205                                 %dis2,
206                         },
207         'email' => {            label => 'Email',
208                                 %dis2,
209                     },
210         'lnp_status' => {       label => 'LNP Status',
211                                 type => 'select-lnp_status.html',
212                                 %dis2,
213                         },
214         'lnp_reject_reason' => { 
215                                 label => 'LNP Reject Reason',
216                                 %dis2,
217                         },
218         'portable' =>   {       label => 'Portable?', %dis2, },
219         'lrn'   =>      {       label => 'LRN', 
220                                 disable_inventory => 1, 
221                         },
222         'lnp_desired_due_date' =>
223                         { label => 'LNP Desired Due Date', %dis2 },
224         'lnp_due_date' =>
225                         { label => 'LNP Due Date', %dis2 },
226         'lnp_other_provider' =>
227                         {       label => 'LNP Other Provider', 
228                                 disable_inventory => 1, 
229                         },
230         'lnp_other_provider_account' =>
231                         {       label => 'LNP Other Provider Account #', 
232                                 %dis2 
233                         },
234         'e911_class' => {
235                                 label => 'E911 Service Class',
236                                 type  => 'select-e911_class',
237                                 disable_inventory => 1,
238                                 multiple => 1,
239                         },
240         'e911_type' => {
241                                 label => 'E911 Service Type',
242                                 type  => 'select-e911_type',
243                                 disable_inventory => 1,
244                                 multiple => 1,
245                         },
246     },
247   };
248 }
249
250 sub table { 'svc_phone'; }
251
252 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
253
254 =item search_sql STRING
255
256 Class method which returns an SQL fragment to search for the given string.
257
258 =cut
259
260 sub search_sql {
261   my( $class, $string ) = @_;
262
263   #my $conf = new FS::Conf;
264
265   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
266     $string =~ s/\W//g;
267   } else {
268     $string =~ s/\D//g;
269   }
270
271   my $ccode = (    $conf->exists('default_phone_countrycode')
272                 && $conf->config('default_phone_countrycode')
273               )
274                 ? $conf->config('default_phone_countrycode') 
275                 : '1';
276
277   $string =~ s/^$ccode//;
278
279   $class->search_sql_field('phonenum', $string );
280 }
281
282 =item label
283
284 Returns the phone number.
285
286 =cut
287
288 sub label {
289   my $self = shift;
290   my $phonenum = $self->phonenum; #XXX format it better
291   my $label = $phonenum;
292   $label .= '@'.$self->domain if $self->domsvc;
293   $label .= ' ('.$self->phone_name.')' if $self->phone_name;
294   $label;
295 }
296
297 =item insert
298
299 Adds this phone number to the database.  If there is an error, returns the
300 error, otherwise returns false.
301
302 =cut
303
304 sub insert {
305   my $self = shift;
306   my %options = @_;
307
308   if ( $DEBUG ) {
309     warn "[$me] insert called on $self: ". Dumper($self).
310          "\nwith options: ". Dumper(%options);
311   }
312
313   local $SIG{HUP} = 'IGNORE';
314   local $SIG{INT} = 'IGNORE';
315   local $SIG{QUIT} = 'IGNORE';
316   local $SIG{TERM} = 'IGNORE';
317   local $SIG{TSTP} = 'IGNORE';
318   local $SIG{PIPE} = 'IGNORE';
319
320   my $oldAutoCommit = $FS::UID::AutoCommit;
321   local $FS::UID::AutoCommit = 0;
322   my $dbh = dbh;
323
324   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
325   #make it more of a base class than a mixin... :)
326   if ( $options{'cust_location'} ) {
327     my $error = $options{'cust_location'}->find_or_insert;
328     if ( $error ) {
329       $dbh->rollback if $oldAutoCommit;
330       return "inserting cust_location (transaction rolled back): $error";
331     }
332     $self->locationnum( $options{'cust_location'}->locationnum );
333   }
334   #what about on-the-fly edits?  if the ui supports it?
335
336   my $error = $self->SUPER::insert(%options);
337   if ( $error ) {
338     $dbh->rollback if $oldAutoCommit;
339     return $error;
340   }
341
342   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
343   '';
344
345 }
346
347 =item delete
348
349 Delete this record from the database.
350
351 =cut
352
353 sub delete {
354   my $self = shift;
355
356   local $SIG{HUP} = 'IGNORE';
357   local $SIG{INT} = 'IGNORE';
358   local $SIG{QUIT} = 'IGNORE';
359   local $SIG{TERM} = 'IGNORE';
360   local $SIG{TSTP} = 'IGNORE';
361   local $SIG{PIPE} = 'IGNORE';
362
363   my $oldAutoCommit = $FS::UID::AutoCommit;
364   local $FS::UID::AutoCommit = 0;
365   my $dbh = dbh;
366
367   foreach my $phone_device ( $self->phone_device ) {
368     my $error = $phone_device->delete;
369     if ( $error ) {
370       $dbh->rollback if $oldAutoCommit;
371       return $error;
372     }
373   }
374
375   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
376   foreach my $phone_avail ( @phone_avail ) {
377     $phone_avail->svcnum('');
378     my $error = $phone_avail->replace;
379     if ( $error ) {
380       $dbh->rollback if $oldAutoCommit;
381       return $error;
382     }
383   }
384
385   my $error = $self->SUPER::delete;
386   if ( $error ) {
387     $dbh->rollback if $oldAutoCommit;
388     return $error;
389   }
390
391   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
392   '';
393
394 }
395
396 # the delete method can be inherited from FS::Record
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 sub phone_device {
739   my $self = shift;
740   qsearch('phone_device', { 'svcnum' => $self->svcnum } );
741 }
742
743 #override location_Mixin version cause we want to try the cust_pkg location
744 #in between us and cust_main
745 # XXX what to do in the unlinked case???  return a pseudo-object that returns
746 # empty fields?
747 sub cust_location_or_main {
748   my $self = shift;
749   return $self->cust_location if $self->locationnum;
750   my $cust_pkg = $self->cust_svc->cust_pkg;
751   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
752 }
753
754 =item phone_name_or_cust
755
756 Returns the C<phone_name> field if it has a value, or the package contact
757 name if there is one, or the customer contact name.
758
759 =cut
760
761 sub phone_name_or_cust {
762   my $self = shift;
763   if ( $self->phone_name ) {
764     return $self->phone_name;
765   }
766   my $cust_pkg = $self->cust_svc->cust_pkg or return '';
767   if ( $cust_pkg->contactnum ) {
768     return $cust_pkg->contact->firstlast;
769   } else {
770     return $cust_pkg->cust_main->name_short;
771   }
772 }
773
774 =item psearch_cdrs OPTIONS
775
776 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records 
777 associated with this service.  By default, "associated with" means that 
778 either the "src" or the "charged_party" field of the CDR matches the 
779 "phonenum" field of the service.  To access the CDRs themselves, call
780 "->fetch" on the resulting object.
781
782 =over 2
783
784 Accepts the following options:
785
786 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
787
788 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
789
790 =item inbound => 1: Return CDRs for inbound calls (that is, those that match
791 on 'dst').  With "status", will filter on inbound processing status.
792
793 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
794 with the chosen prefix.
795
796 =item begin, end: Start and end of a date range, as unix timestamp.
797
798 =item cdrtypenum: Only return CDRs with this type.
799
800 =item calltypenum: Only return CDRs with this call type.
801
802 =item disable_src => 1: Only match on 'charged_party', not 'src'.
803
804 =item disable_charged_party => 1: Only match on 'src', not 'charged_party'.
805
806 =item nonzero: Only return CDRs where duration > 0.
807
808 =item by_svcnum: not supported for svc_phone
809
810 =item billsec_sum: Instead of returning all of the CDRs, return a single
811 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over 
812 the entire result set.
813
814 =back
815
816 =cut
817
818 sub psearch_cdrs {
819
820   my($self, %options) = @_;
821   my @fields;
822   my %hash;
823   my @where;
824
825   if ( $options{'inbound'} ) {
826
827     @fields = ( 'dst' );
828     if ( exists($options{'status'}) ) {
829       my $status = $options{'status'};
830       if ( $status ) {
831         push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
832           'WHERE cdr.acctid = cdr_termination.acctid '.
833           "AND cdr_termination.status = '$status' ". #quoting kludge
834           'AND cdr_termination.termpart = 1 )';
835       } else {
836         push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
837           'WHERE cdr.acctid = cdr_termination.acctid '.
838           'AND cdr_termination.termpart = 1 )';
839       }
840     }
841
842   } else {
843
844     push @fields, 'charged_party' unless $options{'disable_charged_party'};
845     push @fields, 'src' unless $options{'disable_src'};
846     $hash{'freesidestatus'} = $options{'status'}
847       if exists($options{'status'});
848   }
849
850   if ($options{'cdrtypenum'}) {
851     $hash{'cdrtypenum'} = $options{'cdrtypenum'};
852   }
853   if ($options{'calltypenum'}) {
854     $hash{'calltypenum'} = $options{'calltypenum'};
855   }
856   
857   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
858
859   my $number = $self->phonenum;
860
861   my $prefix = $options{'default_prefix'};
862
863   my @orwhere =  map " $_ = '$number'        ", @fields;
864   push @orwhere, map " $_ = '$prefix$number' ", @fields
865     if defined($prefix) && length($prefix);
866   if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
867     push @orwhere, map " $_ = '$1$number' ", @fields
868   }
869
870   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
871
872   if ( $options{'begin'} ) {
873     push @where, 'startdate >= '. $options{'begin'};
874   }
875   if ( $options{'end'} ) {
876     push @where, 'startdate < '.  $options{'end'};
877   }
878   if ( $options{'nonzero'} ) {
879     push @where, 'duration > 0';
880   }
881
882   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
883
884   psearch( {
885       'table'      => 'cdr',
886       'hashref'    => \%hash,
887       'extra_sql'  => $extra_sql,
888       'order_by'   => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
889       'select'     => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
890   } );
891 }
892
893 =item get_cdrs (DEPRECATED)
894
895 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a 
896 single list.  Arguments are the same as for psearch_cdrs.  This can take 
897 an unreasonably large amount of memory and is best avoided.
898
899 =cut
900
901 sub get_cdrs {
902   my $self = shift;
903   my $psearch = $self->psearch_cdrs(@_);
904   qsearch ( $psearch->{query} )
905 }
906
907 =item sum_cdrs
908
909 Takes the same options as psearch_cdrs, but returns a single row containing
910 "count" (the number of CDRs) and the sums of the following fields: duration,
911 billsec, rated_price, rated_seconds, rated_minutes.
912
913 Note that if any calls are not rated, their rated_* fields will be null.
914 If you want to use those fields, pass the 'status' option to limit to 
915 calls that have been rated.  This is intentional; please don't "fix" it.
916
917 =cut
918
919 sub sum_cdrs {
920   my $self = shift;
921   my $psearch = $self->psearch_cdrs(@_);
922   $psearch->{query}->{'select'} = join(',',
923     'COUNT(*) AS count',
924     map { "SUM($_) AS $_" }
925       qw(duration billsec rated_price rated_seconds rated_minutes)
926   );
927   # hack
928   $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
929   qsearchs ( $psearch->{query} );
930 }
931
932 =back
933
934 =head1 CLASS METHODS
935
936 =over 4
937
938 =item e911_classes
939
940 Returns a hashref of allowed values and descriptions for the C<e911_class>
941 field.
942
943 =item e911_types
944
945 Returns a hashref of allowed values and descriptions for the C<e911_type>
946 field.
947
948 =cut
949
950 sub e911_classes {
951   tie my %x, 'Tie::IxHash', (
952     1 => 'Residence',
953     2 => 'Business',
954     3 => 'Residence PBX',
955     4 => 'Business PBX',
956     5 => 'Centrex',
957     6 => 'Coin 1 Way out',
958     7 => 'Coin 2 Way',
959     8 => 'Mobile',
960     9 => 'Residence OPX',
961     0 => 'Business OPX',
962     A => 'Customer Operated Coin Telephone',
963     #B => not available
964     G => 'Wireless Phase I',
965     H => 'Wireless Phase II',
966     I => 'Wireless Phase II with Phase I information',
967     V => 'VoIP Services Default',
968     C => 'VoIP Residence',
969     D => 'VoIP Business',
970     E => 'VoIP Coin/Pay Phone',
971     F => 'VoIP Wireless',
972     J => 'VoIP Nomadic',
973     K => 'VoIP Enterprise Services',
974     T => 'Telematics',
975   );
976   \%x;
977 }
978
979 sub e911_types {
980   tie my %x, 'Tie::IxHash', (
981     0 => 'Not FX nor Non-Published',
982     1 => 'FX in 911 serving area',
983     2 => 'FX outside 911 serving area',
984     3 => 'Non-Published',
985     4 => 'Non-Published FX in serving area',
986     5 => 'Non-Published FX outside serving area',
987     6 => 'Local Ported Number',
988     7 => 'Interim Ported Number',
989   );
990   \%x;
991 }
992
993 =back
994
995 =head1 BUGS
996
997 =head1 SEE ALSO
998
999 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
1000 L<FS::cust_pkg>, schema.html from the base documentation.
1001
1002 =cut
1003
1004 1;
1005