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