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