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