fc5258fff033abbcdc2836c0a8a91cce03652ac8
[freeside.git] / FS / FS / part_svc.pm
1 package FS::part_svc;
2
3 use strict;
4 use vars qw( @ISA $DEBUG );
5 use FS::Record qw( qsearch qsearchs fields dbh );
6 use FS::Schema qw( dbdef );
7 use FS::part_svc_column;
8 use FS::part_export;
9 use FS::export_svc;
10 use FS::cust_svc;
11
12 @ISA = qw(FS::Record);
13
14 $DEBUG = 1;
15
16 =head1 NAME
17
18 FS::part_svc - Object methods for part_svc objects
19
20 =head1 SYNOPSIS
21
22   use FS::part_svc;
23
24   $record = new FS::part_svc \%hash
25   $record = new FS::part_svc { 'column' => 'value' };
26
27   $error = $record->insert;
28   $error = $record->insert( [ 'pseudofield' ] );
29   $error = $record->insert( [ 'pseudofield' ], \%exportnums );
30
31   $error = $new_record->replace($old_record);
32   $error = $new_record->replace($old_record, '1.3-COMPAT', [ 'pseudofield' ] );
33   $error = $new_record->replace($old_record, '1.3-COMPAT', [ 'pseudofield' ], \%exportnums );
34
35   $error = $record->delete;
36
37   $error = $record->check;
38
39 =head1 DESCRIPTION
40
41 An FS::part_svc represents a service definition.  FS::part_svc inherits from
42 FS::Record.  The following fields are currently supported:
43
44 =over 4
45
46 =item svcpart - primary key (assigned automatically for new service definitions)
47
48 =item svc - text name of this service definition
49
50 =item svcdb - table used for this service.  See L<FS::svc_acct>,
51 L<FS::svc_domain>, and L<FS::svc_forward>, among others.
52
53 =item disabled - Disabled flag, empty or `Y'
54
55 =back
56
57 =head1 METHODS
58
59 =over 4
60
61 =item new HASHREF
62
63 Creates a new service definition.  To add the service definition to the
64 database, see L<"insert">.
65
66 =cut
67
68 sub table { 'part_svc'; }
69
70 =item insert [ EXTRA_FIELDS_ARRAYREF [ , EXPORTNUMS_HASHREF [ , JOB ] ] ] 
71
72 Adds this service definition to the database.  If there is an error, returns
73 the error, otherwise returns false.
74
75 The following pseudo-fields may be defined, and will be maintained in
76 the part_svc_column table appropriately (see L<FS::part_svc_column>).
77
78 =over 4
79
80 =item I<svcdb>__I<field> - Default or fixed value for I<field> in I<svcdb>.
81
82 =item I<svcdb>__I<field>_flag - defines I<svcdb>__I<field> action: null or empty (no default), `D' for default, `F' for fixed (unchangeable), `M' for manual selection from inventory, or `A' for automatic selection from inventory.  For virtual fields, can also be 'X' for excluded.
83
84 =back
85
86 If you want to add part_svc_column records for fields that do not exist as
87 (real or virtual) fields in the I<svcdb> table, make sure to list then in 
88 EXTRA_FIELDS_ARRAYREF also.
89
90 If EXPORTNUMS_HASHREF is specified (keys are exportnums and values are
91 boolean), the appopriate export_svc records will be inserted.
92
93 TODOC: JOB
94
95 =cut
96
97 sub insert {
98   my $self = shift;
99   my @fields = ();
100   my @exportnums = ();
101   @fields = @{shift(@_)} if @_;
102   if ( @_ ) {
103     my $exportnums = shift;
104     @exportnums = grep $exportnums->{$_}, keys %$exportnums;
105   }
106   my $job = '';
107   $job = shift if @_;
108
109   local $SIG{HUP} = 'IGNORE';
110   local $SIG{INT} = 'IGNORE';
111   local $SIG{QUIT} = 'IGNORE';
112   local $SIG{TERM} = 'IGNORE';
113   local $SIG{TSTP} = 'IGNORE';
114   local $SIG{PIPE} = 'IGNORE';
115
116   my $oldAutoCommit = $FS::UID::AutoCommit;
117   local $FS::UID::AutoCommit = 0;
118   my $dbh = dbh;
119
120   my $error = $self->SUPER::insert;
121   if ( $error ) {
122     $dbh->rollback if $oldAutoCommit;
123     return $error;
124   }
125
126   # add part_svc_column records
127
128   my $svcdb = $self->svcdb;
129 #  my @rows = map { /^${svcdb}__(.*)$/; $1 }
130 #    grep ! /_flag$/,
131 #      grep /^${svcdb}__/,
132 #        fields('part_svc');
133   foreach my $field (
134     grep { $_ ne 'svcnum'
135            && defined( $self->getfield($svcdb.'__'.$_.'_flag') )
136          } (fields($svcdb), @fields)
137   ) {
138     my $part_svc_column = $self->part_svc_column($field);
139     my $previous = qsearchs('part_svc_column', {
140       'svcpart'    => $self->svcpart,
141       'columnname' => $field,
142     } );
143
144     my $flag = $self->getfield($svcdb.'__'.$field.'_flag');
145     #if ( uc($flag) =~ /^([DFMAX])$/ ) {
146     if ( uc($flag) =~ /^([A-Z])$/ ) { #part_svc_column will test it
147       $part_svc_column->setfield('columnflag', $1);
148       $part_svc_column->setfield('columnvalue',
149         $self->getfield($svcdb.'__'.$field)
150       );
151       if ( $previous ) {
152         $error = $part_svc_column->replace($previous);
153       } else {
154         $error = $part_svc_column->insert;
155       }
156     } else {
157       $error = $previous ? $previous->delete : '';
158     }
159     if ( $error ) {
160       $dbh->rollback if $oldAutoCommit;
161       return $error;
162     }
163
164   }
165
166   # add export_svc records
167   my $slice = 100/scalar(@exportnums) if @exportnums;
168   my $done = 0;
169   foreach my $exportnum ( @exportnums ) {
170     my $export_svc = new FS::export_svc ( {
171       'exportnum' => $exportnum,
172       'svcpart'   => $self->svcpart,
173     } );
174     $error = $export_svc->insert($job, $slice*$done++, $slice);
175     if ( $error ) {
176       $dbh->rollback if $oldAutoCommit;
177       return $error;
178     }
179   }
180
181   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
182
183   '';
184 }
185
186 =item delete
187
188 Currently unimplemented.  Set the "disabled" field instead.
189
190 =cut
191
192 sub delete {
193   return "Can't (yet?) delete service definitions.";
194 # check & make sure the svcpart isn't in cust_svc or pkg_svc (in any packages)?
195 }
196
197 =item replace OLD_RECORD [ '1.3-COMPAT' [ , EXTRA_FIELDS_ARRAYREF [ , EXPORTNUMS_HASHREF [ , JOB ] ] ] ]
198
199 Replaces OLD_RECORD with this one in the database.  If there is an error,
200 returns the error, otherwise returns false.
201
202 TODOC: 1.3-COMPAT
203
204 TODOC: EXTRA_FIELDS_ARRAYREF (same as insert method)
205
206 TODOC: JOB
207
208 =cut
209
210 sub replace {
211   my ( $new, $old ) = ( shift, shift );
212   my $compat = '';
213   my @fields = ();
214   my $exportnums;
215   my $job = '';
216   if ( @_ && $_[0] eq '1.3-COMPAT' ) {
217     shift;
218     $compat = '1.3';
219     @fields = @{shift(@_)} if @_;
220     $exportnums = @_ ? shift : '';
221     $job = shift if @_;
222   } else {
223     return 'non-1.3-COMPAT interface not yet written';
224     #not yet implemented
225   }
226
227   return "Can't change svcdb for an existing service definition!"
228     unless $old->svcdb eq $new->svcdb;
229
230   local $SIG{HUP} = 'IGNORE';
231   local $SIG{INT} = 'IGNORE';
232   local $SIG{QUIT} = 'IGNORE';
233   local $SIG{TERM} = 'IGNORE';
234   local $SIG{TSTP} = 'IGNORE';
235   local $SIG{PIPE} = 'IGNORE';
236
237   my $oldAutoCommit = $FS::UID::AutoCommit;
238   local $FS::UID::AutoCommit = 0;
239   my $dbh = dbh;
240
241   my $error = $new->SUPER::replace( $old );
242   if ( $error ) {
243     $dbh->rollback if $oldAutoCommit;
244     return $error;
245   }
246
247   if ( $compat eq '1.3' ) {
248
249    # maintain part_svc_column records
250
251     my $svcdb = $new->svcdb;
252     foreach my $field (
253       grep { $_ ne 'svcnum'
254              && defined( $new->getfield($svcdb.'__'.$_.'_flag') )
255            } (fields($svcdb),@fields)
256     ) {
257       my $part_svc_column = $new->part_svc_column($field);
258       my $previous = qsearchs('part_svc_column', {
259         'svcpart'    => $new->svcpart,
260         'columnname' => $field,
261       } );
262
263       my $flag = $new->getfield($svcdb.'__'.$field.'_flag');
264       #if ( uc($flag) =~ /^([DFMAX])$/ ) {
265       if ( uc($flag) =~ /^([A-Z])$/ ) { #part_svc_column will test it
266         $part_svc_column->setfield('columnflag', $1);
267         $part_svc_column->setfield('columnvalue',
268           $new->getfield($svcdb.'__'.$field)
269         );
270         if ( $previous ) {
271           $error = $part_svc_column->replace($previous);
272         } else {
273           $error = $part_svc_column->insert;
274         }
275       } else {
276         $error = $previous ? $previous->delete : '';
277       }
278       if ( $error ) {
279         $dbh->rollback if $oldAutoCommit;
280         return $error;
281       }
282     }
283
284     # maintain export_svc records
285
286     if ( $exportnums ) {
287
288       #false laziness w/ edit/process/agent_type.cgi
289       my @new_export_svc = ();
290       foreach my $part_export ( qsearch('part_export', {}) ) {
291         my $exportnum = $part_export->exportnum;
292         my $hashref = {
293           'exportnum' => $exportnum,
294           'svcpart'   => $new->svcpart,
295         };
296         my $export_svc = qsearchs('export_svc', $hashref);
297
298         if ( $export_svc && ! $exportnums->{$exportnum} ) {
299           $error = $export_svc->delete;
300           if ( $error ) {
301             $dbh->rollback if $oldAutoCommit;
302             return $error;
303           }
304         } elsif ( ! $export_svc && $exportnums->{$exportnum} ) {
305           push @new_export_svc, new FS::export_svc ( $hashref );
306         }
307
308       }
309
310       my $slice = 100/scalar(@new_export_svc) if @new_export_svc;
311       my $done = 0;
312       foreach my $export_svc (@new_export_svc) {
313         $error = $export_svc->insert($job, $slice*$done++, $slice);
314         if ( $error ) {
315           $dbh->rollback if $oldAutoCommit;
316           return $error;
317         }
318         if ( $job ) {
319           $error = $job->update_statustext( int( $slice * $done ) );
320           if ( $error ) {
321             $dbh->rollback if $oldAutoCommit;
322             return $error;
323           }
324         }
325       }
326
327     }
328
329   } else {
330     $dbh->rollback if $oldAutoCommit;
331     return 'non-1.3-COMPAT interface not yet written';
332     #not yet implemented
333   }
334
335   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
336
337   '';
338 }
339
340 =item check
341
342 Checks all fields to make sure this is a valid service definition.  If there is
343 an error, returns the error, otherwise returns false.  Called by the insert
344 and replace methods.
345
346 =cut
347
348 sub check {
349   my $self = shift;
350
351   my $error;
352   $error=
353     $self->ut_numbern('svcpart')
354     || $self->ut_text('svc')
355     || $self->ut_alpha('svcdb')
356     || $self->ut_enum('disabled', [ '', 'Y' ] )
357   ;
358   return $error if $error;
359
360   my @fields = eval { fields( $self->svcdb ) }; #might die
361   return "Unknown svcdb: ". $self->svcdb. " (Error: $@)"
362     unless @fields;
363
364   $self->SUPER::check;
365 }
366
367 =item part_svc_column COLUMNNAME
368
369 Returns the part_svc_column object (see L<FS::part_svc_column>) for the given
370 COLUMNNAME, or a new part_svc_column object if none exists.
371
372 =cut
373
374 sub part_svc_column {
375   my( $self, $columnname) = @_;
376   $self->svcpart &&
377     qsearchs('part_svc_column',  {
378                                    'svcpart'    => $self->svcpart,
379                                    'columnname' => $columnname,
380                                  }
381   ) or new FS::part_svc_column {
382                                  'svcpart'    => $self->svcpart,
383                                  'columnname' => $columnname,
384                                };
385 }
386
387 =item all_part_svc_column
388
389 =cut
390
391 sub all_part_svc_column {
392   my $self = shift;
393   qsearch('part_svc_column', { 'svcpart' => $self->svcpart } );
394 }
395
396 =item part_export [ EXPORTTYPE ]
397
398 Returns a list of all exports (see L<FS::part_export>) for this service, or,
399 if an export type is specified, only returns exports of the given type.
400
401 =cut
402
403 sub part_export {
404   my $self = shift;
405   my %search;
406   $search{'exporttype'} = shift if @_;
407   map { qsearchs('part_export', { 'exportnum' => $_->exportnum, %search } ) }
408     qsearch('export_svc', { 'svcpart' => $self->svcpart } );
409 }
410
411 =item part_export_usage
412
413 Returns a list of any exports (see L<FS::part_export>) for this service that
414 are capable of reporting usage information.
415
416 =cut
417
418 sub part_export_usage {
419   my $self = shift;
420   grep $_->can('usage_sessions'), $self->part_export;
421 }
422
423 =item cust_svc [ PKGPART ] 
424
425 Returns a list of associated customer services (FS::cust_svc records).
426
427 If a PKGPART is specified, returns the customer services which are contained
428 within packages of that type (see L<FS::part_pkg>).  If PKGPARTis specified as
429 B<0>, returns unlinked customer services.
430
431 =cut
432
433 sub cust_svc {
434   my $self = shift;
435
436   my $hashref = { 'svcpart' => $self->svcpart };
437
438   my( $addl_from, $extra_sql ) = ( '', '' );
439   if ( @_ ) {
440     my $pkgpart = shift;
441     if ( $pkgpart =~ /^(\d+)$/ ) {
442       $addl_from = 'LEFT JOIN cust_pkg USING ( pkgnum )';
443       $extra_sql = "AND pkgpart = $1";
444     } elsif ( $pkgpart eq '0' ) {
445       $hashref->{'pkgnum'} = '';
446     }
447   }
448
449   qsearch({
450     'table'     => 'cust_svc',
451     'addl_from' => $addl_from,
452     'hashref'   => $hashref,
453     'extra_sql' => $extra_sql,
454   });
455 }
456
457 =item num_cust_svc [ PKGPART ] 
458
459 Returns the number of associated customer services (FS::cust_svc records).
460
461 If a PKGPART is specified, returns the number of customer services which are
462 contained within packages of that type (see L<FS::part_pkg>).  If PKGPART
463 is specified as B<0>, returns the number of unlinked customer services.
464
465 =cut
466
467 sub num_cust_svc {
468   my $self = shift;
469
470   my @param = ( $self->svcpart );
471
472   my( $join, $and ) = ( '', '' );
473   if ( @_ ) {
474     my $pkgpart = shift;
475     if ( $pkgpart ) {
476       $join = 'LEFT JOIN cust_pkg USING ( pkgnum )';
477       $and = 'AND pkgpart = ?';
478       push @param, $pkgpart;
479     } elsif ( $pkgpart eq '0' ) {
480       $and = 'AND pkgnum IS NULL';
481     }
482   }
483
484   my $sth = dbh->prepare(
485     "SELECT COUNT(*) FROM cust_svc $join WHERE svcpart = ? $and"
486   ) or die dbh->errstr;
487   $sth->execute(@param)
488     or die $sth->errstr;
489   $sth->fetchrow_arrayref->[0];
490 }
491
492 =item svc_x
493
494 Returns a list of associated FS::svc_* records.
495
496 =cut
497
498 sub svc_x {
499   my $self = shift;
500   map { $_->svc_x } $self->cust_svc;
501 }
502
503
504 =back
505
506 =head1 SUBROUTINES
507
508 =over 4
509
510 =item process
511
512 Job-queue processor for web interface adds/edits
513
514 =cut
515
516 use Storable qw(thaw);
517 use Data::Dumper;
518 use MIME::Base64;
519 sub process {
520   my $job = shift;
521
522   my $param = thaw(decode_base64(shift));
523   warn Dumper($param) if $DEBUG;
524
525   my $old = qsearchs('part_svc', { 'svcpart' => $param->{'svcpart'} }) 
526     if $param->{'svcpart'};
527
528   $param->{'svc_acct__usergroup'} =
529     ref($param->{'svc_acct__usergroup'})
530       ? join(',', @{$param->{'svc_acct__usergroup'}} )
531       : $param->{'svc_acct__usergroup'};
532   
533   my $new = new FS::part_svc ( {
534     map {
535       $_ => $param->{$_};
536   #  } qw(svcpart svc svcdb)
537     } ( fields('part_svc'),
538         map { my $svcdb = $_;
539               my @fields = fields($svcdb);
540               push @fields, 'usergroup' if $svcdb eq 'svc_acct'; #kludge
541
542               map {
543                     if ( $param->{ $svcdb.'__'.$_.'_flag' } =~ /^[MA]$/ ) {
544                       $param->{ $svcdb.'__'.$_ } =
545                         delete( $param->{ $svcdb.'__'.$_.'_classnum' } );
546                     }
547                     if ( $param->{ $svcdb.'__'.$_.'_flag' } =~ /^S$/ ) {
548                       $param->{ $svcdb.'__'.$_} =
549                         ref($param->{ $svcdb.'__'.$_})
550                           ? join(',', @{$param->{ $svcdb.'__'.$_ }} )
551                           : $param->{ $svcdb.'__'.$_ };
552                     }
553                     ( $svcdb.'__'.$_, $svcdb.'__'.$_.'_flag' );
554                   }
555                   @fields;
556
557             } grep defined( dbdef->table($_) ),
558                    qw( svc_acct svc_domain svc_forward svc_www svc_broadband
559                        svc_phone svc_external
560                      )
561       )
562   } );
563   
564   my %exportnums =
565     map { $_->exportnum => ( $param->{'exportnum'.$_->exportnum} || '') }
566         qsearch('part_export', {} );
567
568   my $error;
569   if ( $param->{'svcpart'} ) {
570     $error = $new->replace( $old,
571                             '1.3-COMPAT',
572                             [ 'usergroup' ],
573                             \%exportnums,
574                             $job
575                           );
576   } else {
577     $error = $new->insert( [ 'usergroup' ],
578                            \%exportnums,
579                            $job,
580                          );
581     $param->{'svcpart'} = $new->getfield('svcpart');
582   }
583
584   die "$error\n" if $error;
585 }
586
587 =item process_bulk_cust_svc
588
589 Job-queue processor for web interface bulk customer service changes
590
591 =cut
592
593 use Storable qw(thaw);
594 use Data::Dumper;
595 use MIME::Base64;
596 sub process_bulk_cust_svc {
597   my $job = shift;
598
599   my $param = thaw(decode_base64(shift));
600   warn Dumper($param) if $DEBUG;
601
602   my $old_part_svc =
603     qsearchs('part_svc', { 'svcpart' => $param->{'old_svcpart'} } );
604
605   die "Must select a new service definition\n" unless $param->{'new_svcpart'};
606
607   #the rest should be abstracted out to to its own subroutine?
608
609   local $SIG{HUP} = 'IGNORE';
610   local $SIG{INT} = 'IGNORE';
611   local $SIG{QUIT} = 'IGNORE';
612   local $SIG{TERM} = 'IGNORE';
613   local $SIG{TSTP} = 'IGNORE';
614   local $SIG{PIPE} = 'IGNORE';
615
616   my $oldAutoCommit = $FS::UID::AutoCommit;
617   local $FS::UID::AutoCommit = 0;
618   my $dbh = dbh;
619
620   local( $FS::cust_svc::ignore_quantity ) = 1;
621
622   my $total = $old_part_svc->num_cust_svc( $param->{'pkgpart'} );
623
624   my $n = 0;
625   foreach my $old_cust_svc ( $old_part_svc->cust_svc( $param->{'pkgpart'} ) ) {
626
627     my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
628
629     $new_cust_svc->svcpart( $param->{'new_svcpart'} );
630     my $error = $new_cust_svc->replace($old_cust_svc);
631     if ( $error ) {
632       $dbh->rollback if $oldAutoCommit;
633       die "$error\n" if $error;
634     }
635
636     $error = $job->update_statustext( int( 100 * ++$n / $total ) );
637     if ( $error ) {
638       $dbh->rollback if $oldAutoCommit;
639       die $error if $error;
640     }
641
642   }
643
644   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
645
646   '';
647
648 }
649
650 =head1 BUGS
651
652 Delete is unimplemented.
653
654 The list of svc_* tables is hardcoded.  When svc_acct_pop is renamed, this
655 should be fixed.
656
657 all_part_svc_column methods should be documented
658
659 =head1 SEE ALSO
660
661 L<FS::Record>, L<FS::part_svc_column>, L<FS::part_pkg>, L<FS::pkg_svc>,
662 L<FS::cust_svc>, L<FS::svc_acct>, L<FS::svc_forward>, L<FS::svc_domain>,
663 schema.html from the base documentation.
664
665 =cut
666
667 1;
668