update cust_svc::seconds_since_sqlradacct to deal with any usage-capable export
[freeside.git] / FS / FS / cust_svc.pm
1 package FS::cust_svc;
2
3 use strict;
4 use vars qw( @ISA $DEBUG $ignore_quantity );
5 use Carp qw( carp cluck );
6 use FS::Conf;
7 use FS::Record qw( qsearch qsearchs dbh );
8 use FS::cust_pkg;
9 use FS::part_pkg;
10 use FS::part_svc;
11 use FS::pkg_svc;
12 use FS::svc_acct;
13 use FS::svc_domain;
14 use FS::svc_forward;
15 use FS::svc_broadband;
16 use FS::svc_external;
17 use FS::domain_record;
18 use FS::part_export;
19
20 @ISA = qw( FS::Record );
21
22 $DEBUG = 0;
23
24 $ignore_quantity = 0;
25
26 sub _cache {
27   my $self = shift;
28   my ( $hashref, $cache ) = @_;
29   if ( $hashref->{'username'} ) {
30     $self->{'_svc_acct'} = FS::svc_acct->new($hashref, '');
31   }
32   if ( $hashref->{'svc'} ) {
33     $self->{'_svcpart'} = FS::part_svc->new($hashref);
34   }
35 }
36
37 =head1 NAME
38
39 FS::cust_svc - Object method for cust_svc objects
40
41 =head1 SYNOPSIS
42
43   use FS::cust_svc;
44
45   $record = new FS::cust_svc \%hash
46   $record = new FS::cust_svc { 'column' => 'value' };
47
48   $error = $record->insert;
49
50   $error = $new_record->replace($old_record);
51
52   $error = $record->delete;
53
54   $error = $record->check;
55
56   ($label, $value) = $record->label;
57
58 =head1 DESCRIPTION
59
60 An FS::cust_svc represents a service.  FS::cust_svc inherits from FS::Record.
61 The following fields are currently supported:
62
63 =over 4
64
65 =item svcnum - primary key (assigned automatically for new services)
66
67 =item pkgnum - Package (see L<FS::cust_pkg>)
68
69 =item svcpart - Service definition (see L<FS::part_svc>)
70
71 =back
72
73 =head1 METHODS
74
75 =over 4
76
77 =item new HASHREF
78
79 Creates a new service.  To add the refund to the database, see L<"insert">.
80 Services are normally created by creating FS::svc_ objects (see
81 L<FS::svc_acct>, L<FS::svc_domain>, and L<FS::svc_forward>, among others).
82
83 =cut
84
85 sub table { 'cust_svc'; }
86
87 =item insert
88
89 Adds this service to the database.  If there is an error, returns the error,
90 otherwise returns false.
91
92 =item delete
93
94 Deletes this service from the database.  If there is an error, returns the
95 error, otherwise returns false.  Note that this only removes the cust_svc
96 record - you should probably use the B<cancel> method instead.
97
98 =item cancel
99
100 Cancels the relevant service by calling the B<cancel> method of the associated
101 FS::svc_XXX object (i.e. an FS::svc_acct object or FS::svc_domain object),
102 deleting the FS::svc_XXX record and then deleting this record.
103
104 If there is an error, returns the error, otherwise returns false.
105
106 =cut
107
108 sub cancel {
109   my $self = shift;
110
111   local $SIG{HUP} = 'IGNORE';
112   local $SIG{INT} = 'IGNORE';
113   local $SIG{QUIT} = 'IGNORE'; 
114   local $SIG{TERM} = 'IGNORE';
115   local $SIG{TSTP} = 'IGNORE';
116   local $SIG{PIPE} = 'IGNORE';
117
118   my $oldAutoCommit = $FS::UID::AutoCommit;
119   local $FS::UID::AutoCommit = 0;
120   my $dbh = dbh;
121
122   my $part_svc = $self->part_svc;
123
124   $part_svc->svcdb =~ /^([\w\-]+)$/ or do {
125     $dbh->rollback if $oldAutoCommit;
126     return "Illegal svcdb value in part_svc!";
127   };
128   my $svcdb = $1;
129   require "FS/$svcdb.pm";
130
131   my $svc = $self->svc_x;
132   if ($svc) {
133     my $error = $svc->cancel;
134     if ( $error ) {
135       $dbh->rollback if $oldAutoCommit;
136       return "Error canceling service: $error";
137     }
138     $error = $svc->delete;
139     if ( $error ) {
140       $dbh->rollback if $oldAutoCommit;
141       return "Error deleting service: $error";
142     }
143   }
144
145   my $error = $self->delete;
146   if ( $error ) {
147     $dbh->rollback if $oldAutoCommit;
148     return "Error deleting cust_svc: $error";
149   }
150
151   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
152
153   ''; #no errors
154
155 }
156
157 =item replace OLD_RECORD
158
159 Replaces the OLD_RECORD with this one in the database.  If there is an error,
160 returns the error, otherwise returns false.
161
162 =cut
163
164 sub replace {
165   my ( $new, $old ) = ( shift, shift );
166
167   local $SIG{HUP} = 'IGNORE';
168   local $SIG{INT} = 'IGNORE';
169   local $SIG{QUIT} = 'IGNORE';
170   local $SIG{TERM} = 'IGNORE';
171   local $SIG{TSTP} = 'IGNORE';
172   local $SIG{PIPE} = 'IGNORE';
173
174   my $oldAutoCommit = $FS::UID::AutoCommit;
175   local $FS::UID::AutoCommit = 0;
176   my $dbh = dbh;
177
178   if ( $new->svcpart != $old->svcpart ) {
179     my $svc_x = $new->svc_x;
180     my $new_svc_x = ref($svc_x)->new({$svc_x->hash, svcpart=>$new->svcpart });
181     local($FS::Record::nowarn_identical) = 1;
182     my $error = $new_svc_x->replace($svc_x);
183     if ( $error ) {
184       $dbh->rollback if $oldAutoCommit;
185       return $error if $error;
186     }
187   }
188
189   my $error = $new->SUPER::replace($old);
190   if ( $error ) {
191     $dbh->rollback if $oldAutoCommit;
192     return $error if $error;
193   }
194
195   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
196   ''; #no error
197
198 }
199
200 =item check
201
202 Checks all fields to make sure this is a valid service.  If there is an error,
203 returns the error, otehrwise returns false.  Called by the insert and
204 replace methods.
205
206 =cut
207
208 sub check {
209   my $self = shift;
210
211   my $error =
212     $self->ut_numbern('svcnum')
213     || $self->ut_numbern('pkgnum')
214     || $self->ut_number('svcpart')
215   ;
216   return $error if $error;
217
218   my $part_svc = qsearchs( 'part_svc', { 'svcpart' => $self->svcpart } );
219   return "Unknown svcpart" unless $part_svc;
220
221   if ( $self->pkgnum ) {
222     my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
223     return "Unknown pkgnum" unless $cust_pkg;
224     my $pkg_svc = qsearchs( 'pkg_svc', {
225       'pkgpart' => $cust_pkg->pkgpart,
226       'svcpart' => $self->svcpart,
227     });
228     # or new FS::pkg_svc ( { 'pkgpart'  => $cust_pkg->pkgpart,
229     #                        'svcpart'  => $self->svcpart,
230     #                        'quantity' => 0                   } );
231     my $quantity = $pkg_svc ? $pkg_svc->quantity : 0;
232
233     my @cust_svc = qsearch('cust_svc', {
234       'pkgnum'  => $self->pkgnum,
235       'svcpart' => $self->svcpart,
236     });
237     return "Already ". scalar(@cust_svc). " ". $part_svc->svc.
238            " services for pkgnum ". $self->pkgnum
239       if scalar(@cust_svc) >= $quantity && !$ignore_quantity;
240   }
241
242   $self->SUPER::check;
243 }
244
245 =item part_svc
246
247 Returns the definition for this service, as a FS::part_svc object (see
248 L<FS::part_svc>).
249
250 =cut
251
252 sub part_svc {
253   my $self = shift;
254   $self->{'_svcpart'}
255     ? $self->{'_svcpart'}
256     : qsearchs( 'part_svc', { 'svcpart' => $self->svcpart } );
257 }
258
259 =item cust_pkg
260
261 Returns the package this service belongs to, as a FS::cust_pkg object (see
262 L<FS::cust_pkg>).
263
264 =cut
265
266 sub cust_pkg {
267   my $self = shift;
268   qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
269 }
270
271 =item label
272
273 Returns a list consisting of:
274 - The name of this service (from part_svc)
275 - A meaningful identifier (username, domain, or mail alias)
276 - The table name (i.e. svc_domain) for this service
277 - svcnum
278
279 =cut
280
281 sub label {
282   my $self = shift;
283   carp "FS::cust_svc::label called on $self" if $DEBUG;
284   my $svc_x = $self->svc_x
285     or die "can't find ". $self->part_svc->svcdb. '.svcnum '. $self->svcnum;
286   $self->_svc_label($svc_x);
287 }
288
289 sub _svc_label {
290   my( $self, $svc_x ) = ( shift, shift );
291   my $svcdb = $self->part_svc->svcdb;
292
293   my $tag;
294   if ( $svcdb eq 'svc_acct' ) {
295     $tag = $svc_x->email(@_);
296   } elsif ( $svcdb eq 'svc_forward' ) {
297     if ( $svc_x->srcsvc ) {
298       my $svc_acct = $svc_x->srcsvc_acct(@_);
299       $tag = $svc_acct->email(@_);
300     } else {
301       $tag = $svc_x->src;
302     }
303     $tag .= '->';
304     if ( $svc_x->dstsvc ) {
305       my $svc_acct = $svc_x->dstsvc_acct(@_);
306       $tag .= $svc_acct->email(@_);
307     } else {
308       $tag .= $svc_x->dst;
309     }
310   } elsif ( $svcdb eq 'svc_domain' ) {
311     $tag = $svc_x->getfield('domain');
312   } elsif ( $svcdb eq 'svc_www' ) {
313     my $domain_record = $svc_x->domain_record(@_);
314     $tag = $domain_record->zone;
315   } elsif ( $svcdb eq 'svc_broadband' ) {
316     $tag = $svc_x->ip_addr;
317   } elsif ( $svcdb eq 'svc_external' ) {
318     my $conf = new FS::Conf;
319     if ( $conf->config('svc_external-display_type') eq 'artera_turbo' ) {
320       $tag = sprintf('%010d', $svc_x->id). '-'.
321              substr('0000000000'.uc($svc_x->title), -10);
322     } else {
323       $tag = $svc_x->id. ': '. $svc_x->title;
324     }
325   } else {
326     cluck "warning: asked for label of unsupported svcdb; using svcnum";
327     $tag = $svc_x->getfield('svcnum');
328   }
329
330   $self->part_svc->svc, $tag, $svcdb, $self->svcnum;
331
332 }
333
334 =item svc_x
335
336 Returns the FS::svc_XXX object for this service (i.e. an FS::svc_acct object or
337 FS::svc_domain object, etc.)
338
339 =cut
340
341 sub svc_x {
342   my $self = shift;
343   my $svcdb = $self->part_svc->svcdb;
344   if ( $svcdb eq 'svc_acct' && $self->{'_svc_acct'} ) {
345     $self->{'_svc_acct'};
346   } else {
347     #require "FS/$svcdb.pm";
348     qsearchs( $svcdb, { 'svcnum' => $self->svcnum } );
349   }
350 }
351
352 =item seconds_since TIMESTAMP
353
354 See L<FS::svc_acct/seconds_since>.  Equivalent to
355 $cust_svc->svc_x->seconds_since, but more efficient.  Meaningless for records
356 where B<svcdb> is not "svc_acct".
357
358 =cut
359
360 #note: implementation here, POD in FS::svc_acct
361 sub seconds_since {
362   my($self, $since) = @_;
363   my $dbh = dbh;
364   my $sth = $dbh->prepare(' SELECT SUM(logout-login) FROM session
365                               WHERE svcnum = ?
366                                 AND login >= ?
367                                 AND logout IS NOT NULL'
368   ) or die $dbh->errstr;
369   $sth->execute($self->svcnum, $since) or die $sth->errstr;
370   $sth->fetchrow_arrayref->[0];
371 }
372
373 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
374
375 See L<FS::svc_acct/seconds_since_sqlradacct>.  Equivalent to
376 $cust_svc->svc_x->seconds_since_sqlradacct, but more efficient.  Meaningless
377 for records where B<svcdb> is not "svc_acct".
378
379 =cut
380
381 #note: implementation here, POD in FS::svc_acct
382 sub seconds_since_sqlradacct {
383   my($self, $start, $end) = @_;
384
385   my $svc_x = $self->svc_x;
386
387   my @part_export = $self->part_svc->part_export_usage;
388   die "no usage-capable export configured for this service type"
389     unless @part_export;
390     #or return undef;
391
392   my $seconds = 0;
393   foreach my $part_export ( @part_export ) {
394
395     next if $part_export->option('ignore_accounting');
396
397     my $dbh = DBI->connect( map { $part_export->option($_) }
398                             qw(datasrc username password)    )
399       or die "can't connect to sqlradius database: ". $DBI::errstr;
400
401     #select a unix time conversion function based on database type
402     my $str2time;
403     if ( $dbh->{Driver}->{Name} =~ /^mysql(PP)?$/ ) {
404       $str2time = 'UNIX_TIMESTAMP(';
405     } elsif ( $dbh->{Driver}->{Name} eq 'Pg' ) {
406       $str2time = 'EXTRACT( EPOCH FROM ';
407     } else {
408       warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
409            "; guessing how to convert to UNIX timestamps";
410       $str2time = 'extract(epoch from ';
411     }
412
413     my $username = $part_export->export_username($svc_x);
414
415     my $query;
416   
417     #find closed sessions completely within the given range
418     my $sth = $dbh->prepare("SELECT SUM(acctsessiontime)
419                                FROM radacct
420                                WHERE UserName = ?
421                                  AND $str2time AcctStartTime) >= ?
422                                  AND $str2time AcctStopTime ) <  ?
423                                  AND $str2time AcctStopTime ) > 0
424                                  AND AcctStopTime IS NOT NULL"
425     ) or die $dbh->errstr;
426     $sth->execute($username, $start, $end) or die $sth->errstr;
427     my $regular = $sth->fetchrow_arrayref->[0];
428   
429     #find open sessions which start in the range, count session start->range end
430     $query = "SELECT SUM( ? - $str2time AcctStartTime ) )
431                 FROM radacct
432                 WHERE UserName = ?
433                   AND $str2time AcctStartTime ) >= ?
434                   AND $str2time AcctStartTime ) <  ?
435                   AND ( ? - $str2time AcctStartTime ) ) < 86400
436                   AND (    $str2time AcctStopTime ) = 0
437                                     OR AcctStopTime IS NULL )";
438     $sth = $dbh->prepare($query) or die $dbh->errstr;
439     $sth->execute($end, $username, $start, $end, $end)
440       or die $sth->errstr. " executing query $query";
441     my $start_during = $sth->fetchrow_arrayref->[0];
442   
443     #find closed sessions which start before the range but stop during,
444     #count range start->session end
445     $sth = $dbh->prepare("SELECT SUM( $str2time AcctStopTime ) - ? ) 
446                             FROM radacct
447                             WHERE UserName = ?
448                               AND $str2time AcctStartTime ) < ?
449                               AND $str2time AcctStopTime  ) >= ?
450                               AND $str2time AcctStopTime  ) <  ?
451                               AND $str2time AcctStopTime ) > 0
452                               AND AcctStopTime IS NOT NULL"
453     ) or die $dbh->errstr;
454     $sth->execute($start, $username, $start, $start, $end ) or die $sth->errstr;
455     my $end_during = $sth->fetchrow_arrayref->[0];
456   
457     #find closed (not anymore - or open) sessions which start before the range
458     # but stop after, or are still open, count range start->range end
459     # don't count open sessions (probably missing stop record)
460     $sth = $dbh->prepare("SELECT COUNT(*)
461                             FROM radacct
462                             WHERE UserName = ?
463                               AND $str2time AcctStartTime ) < ?
464                               AND ( $str2time AcctStopTime ) >= ?
465                                                                   )"
466                               #      OR AcctStopTime =  0
467                               #      OR AcctStopTime IS NULL       )"
468     ) or die $dbh->errstr;
469     $sth->execute($username, $start, $end ) or die $sth->errstr;
470     my $entire_range = ($end-$start) * $sth->fetchrow_arrayref->[0];
471
472     $seconds += $regular + $end_during + $start_during + $entire_range;
473
474   }
475
476   $seconds;
477
478 }
479
480 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
481
482 See L<FS::svc_acct/attribute_since_sqlradacct>.  Equivalent to
483 $cust_svc->svc_x->attribute_since_sqlradacct, but more efficient.  Meaningless
484 for records where B<svcdb> is not "svc_acct".
485
486 =cut
487
488 #note: implementation here, POD in FS::svc_acct
489 #(false laziness w/seconds_since_sqlradacct above)
490 sub attribute_since_sqlradacct {
491   my($self, $start, $end, $attrib) = @_;
492
493   my $svc_x = $self->svc_x;
494
495   my @part_export = $self->part_svc->part_export('sqlradius');
496   push @part_export, $self->part_svc->part_export('sqlradius_withdomain');
497   die "no sqlradius or sqlradius_withdomain export configured for this".
498       "service type"
499     unless @part_export;
500     #or return undef;
501
502   my $sum = 0;
503
504   foreach my $part_export ( @part_export ) {
505
506     next if $part_export->option('ignore_accounting');
507
508     my $dbh = DBI->connect( map { $part_export->option($_) }
509                             qw(datasrc username password)    )
510       or die "can't connect to sqlradius database: ". $DBI::errstr;
511
512     #select a unix time conversion function based on database type
513     my $str2time;
514     if ( $dbh->{Driver}->{Name} =~ /^mysql(PP)?$/ ) {
515       $str2time = 'UNIX_TIMESTAMP(';
516     } elsif ( $dbh->{Driver}->{Name} eq 'Pg' ) {
517       $str2time = 'EXTRACT( EPOCH FROM ';
518     } else {
519       warn "warning: unknown database type ". $dbh->{Driver}->{Name}.
520            "; guessing how to convert to UNIX timestamps";
521       $str2time = 'extract(epoch from ';
522     }
523
524     my $username;
525     if ( $part_export->exporttype eq 'sqlradius' ) {
526       $username = $svc_x->username;
527     } elsif ( $part_export->exporttype eq 'sqlradius_withdomain' ) {
528       $username = $svc_x->email;
529     } else {
530       die 'unknown exporttype '. $part_export->exporttype;
531     }
532
533     my $sth = $dbh->prepare("SELECT SUM($attrib)
534                                FROM radacct
535                                WHERE UserName = ?
536                                  AND $str2time AcctStopTime ) >= ?
537                                  AND $str2time AcctStopTime ) <  ?
538                                  AND AcctStopTime IS NOT NULL"
539     ) or die $dbh->errstr;
540     $sth->execute($username, $start, $end) or die $sth->errstr;
541
542     $sum += $sth->fetchrow_arrayref->[0];
543
544   }
545
546   $sum;
547
548 }
549
550 =item get_session_history TIMESTAMP_START TIMESTAMP_END
551
552 See L<FS::svc_acct/get_session_history>.  Equivalent to
553 $cust_svc->svc_x->get_session_history, but more efficient.  Meaningless for
554 records where B<svcdb> is not "svc_acct".
555
556 =cut
557
558 sub get_session_history {
559   my($self, $start, $end, $attrib) = @_;
560
561   #$attrib ???
562
563   my @part_export = $self->part_svc->part_export_usage;
564   die "no accounting-capable exports are enabled for this service definition"
565     unless @part_export;
566     #or return undef;
567                      
568   my @sessions = ();
569
570   foreach my $part_export ( @part_export ) {
571     push @sessions,
572       @{ $part_export->usage_sessions( $start, $end, $self->svc_x ) };
573   }
574
575   @sessions;
576
577 }
578
579 =item pkg_svc
580
581 Returns the pkg_svc record for for this service, if applicable.
582
583 =cut
584
585 sub pkg_svc {
586   my $self = shift;
587   my $cust_pkg = $self->cust_pkg;
588   return undef unless $cust_pkg;
589
590   qsearchs( 'pkg_svc', { 'svcpart' => $self->svcpart,
591                          'pkgpart' => $cust_pkg->pkgpart,
592                        }
593           );
594 }
595
596 =back
597
598 =head1 BUGS
599
600 Behaviour of changing the svcpart of cust_svc records is undefined and should
601 possibly be prohibited, and pkg_svc records are not checked.
602
603 pkg_svc records are not checked in general (here).
604
605 Deleting this record doesn't check or delete the svc_* record associated
606 with this record.
607
608 In seconds_since_sqlradacct, specifying a DATASRC/USERNAME/PASSWORD instead of
609 a DBI database handle is not yet implemented.
610
611 =head1 SEE ALSO
612
613 L<FS::Record>, L<FS::cust_pkg>, L<FS::part_svc>, L<FS::pkg_svc>, 
614 schema.html from the base documentation
615
616 =cut
617
618 1;
619