add skip_dcontext_suffix to skip CDRs with dcontext ending in a definable string...
[freeside.git] / FS / FS / part_svc.pm
1 package FS::part_svc;
2 use base qw(FS::Record);
3
4 use strict;
5 use vars qw( $DEBUG );
6 use Tie::IxHash;
7 use FS::Record qw( qsearch qsearchs fields dbh );
8 use FS::Schema qw( dbdef );
9 use FS::part_svc_column;
10 use FS::part_export;
11 use FS::export_svc;
12 use FS::cust_svc;
13 use FS::part_svc_class;
14
15 FS::UID->install_callback(sub {
16     # preload the cache and make sure all modules load
17     my $svc_defs = FS::part_svc->_svc_defs;
18 });
19
20 $DEBUG = 0;
21
22 =head1 NAME
23
24 FS::part_svc - Object methods for part_svc objects
25
26 =head1 SYNOPSIS
27
28   use FS::part_svc;
29
30   $record = new FS::part_svc \%hash
31   $record = new FS::part_svc { 'column' => 'value' };
32
33   $error = $record->insert;
34   $error = $record->insert( [ 'pseudofield' ] );
35   $error = $record->insert( [ 'pseudofield' ], \%exportnums );
36
37   $error = $new_record->replace($old_record);
38   $error = $new_record->replace($old_record, '1.3-COMPAT', [ 'pseudofield' ] );
39   $error = $new_record->replace($old_record, '1.3-COMPAT', [ 'pseudofield' ], \%exportnums );
40
41   $error = $record->delete;
42
43   $error = $record->check;
44
45 =head1 DESCRIPTION
46
47 An FS::part_svc represents a service definition.  FS::part_svc inherits from
48 FS::Record.  The following fields are currently supported:
49
50 =over 4
51
52 =item svcpart - primary key (assigned automatically for new service definitions)
53
54 =item svc - text name of this service definition
55
56 =item svcdb - table used for this service.  See L<FS::svc_acct>,
57 L<FS::svc_domain>, and L<FS::svc_forward>, among others.
58
59 =item classnum - Optional service class (see L<FS::svc_class>)
60
61 =item disabled - Disabled flag, empty or `Y'
62
63 =item preserve - Preserve after cancellation, empty or 'Y'
64
65 =item selfservice_access - Access allowed to the service via self-service:
66 empty for full access, "readonly" for read-only, "hidden" to hide it entirely
67
68 =item restrict_edit_password - Require the "Provision customer service" access
69 right to change the password field, rather than just "Edit password".  Only
70 relevant to svc_acct for now.
71
72 =item has_router - Allow the service to have an L<FS::router> connected 
73 through it.  Probably only relevant to svc_broadband, svc_acct, and svc_dsl
74 for now.
75
76 =back
77
78 =head1 METHODS
79
80 =over 4
81
82 =item new HASHREF
83
84 Creates a new service definition.  To add the service definition to the
85 database, see L<"insert">.
86
87 =cut
88
89 sub table { 'part_svc'; }
90
91 =item insert [ EXTRA_FIELDS_ARRAYREF [ , EXPORTNUMS_HASHREF [ , JOB ] ] ] 
92
93 Adds this service definition to the database.  If there is an error, returns
94 the error, otherwise returns false.
95
96 The following pseudo-fields may be defined, and will be maintained in
97 the part_svc_column table appropriately (see L<FS::part_svc_column>).
98
99 =over 4
100
101 =item I<svcdb>__I<field> - Default or fixed value for I<field> in I<svcdb>.
102
103 =item I<svcdb>__I<field>_label
104
105 =item I<svcdb>__I<field>_flag - defines I<svcdb>__I<field> action: null or empty (no default), `D' for default, `F' for fixed (unchangeable), , `S' for selectable choice, `M' for manual selection from inventory, or `A' for automatic selection from inventory.  For virtual fields, can also be 'X' for excluded.
106
107 =item I<svcdb>__I<field>_required - I<field> should always have a true value
108
109 =back
110
111 If you want to add part_svc_column records for fields that do not exist as
112 fields in the I<svcdb> table, make sure to list then in 
113 EXTRA_FIELDS_ARRAYREF also.
114
115 If EXPORTNUMS_HASHREF is specified (keys are exportnums and values are
116 boolean), the appopriate export_svc records will be inserted.
117
118 TODOC: JOB
119
120 =cut
121
122 sub insert {
123   my $self = shift;
124   my @fields = ();
125   @fields = @{shift(@_)} if @_;
126   my $exportnums = shift || {};
127   my $job = '';
128   $job = shift if @_;
129
130   local $SIG{HUP} = 'IGNORE';
131   local $SIG{INT} = 'IGNORE';
132   local $SIG{QUIT} = 'IGNORE';
133   local $SIG{TERM} = 'IGNORE';
134   local $SIG{TSTP} = 'IGNORE';
135   local $SIG{PIPE} = 'IGNORE';
136
137   my $oldAutoCommit = $FS::UID::AutoCommit;
138   local $FS::UID::AutoCommit = 0;
139   my $dbh = dbh;
140
141   my $error = $self->SUPER::insert;
142   if ( $error ) {
143     $dbh->rollback if $oldAutoCommit;
144     return $error;
145   }
146
147   # add part_svc_column records
148
149   my $svcdb = $self->svcdb;
150   foreach my $field (fields($svcdb), @fields) {
151     next if $field eq 'svcnum';
152     my $prefix = $svcdb.'__';
153     if ( defined( $self->getfield($prefix.$field.'_flag'))
154       or defined($self->getfield($prefix.$field.'_required'))
155       or length($self->getfield($prefix.$field.'_label'))
156     ) {
157       my $part_svc_column = $self->part_svc_column($field);
158       my $previous = qsearchs('part_svc_column', {
159         'svcpart'    => $self->svcpart,
160         'columnname' => $field,
161       } );
162
163       my $flag  = $self->getfield($prefix.$field.'_flag');
164       my $label = $self->getfield($prefix.$field.'_label');
165       my $required = $self->getfield($prefix.$field.'_required') ? 'Y' : '';
166       if ( uc($flag) =~ /^([A-Z])$/ || $label !~ /^\s*$/ ) {
167
168         if ( uc($flag) =~ /^([A-Z])$/ ) {
169           my $parser = FS::part_svc->svc_table_fields($svcdb)->{$field}->{parse}
170                        || sub { shift };
171           $part_svc_column->setfield('columnflag', $1);
172           $part_svc_column->setfield('columnvalue',
173             &$parser($self->getfield($prefix.$field))
174           );
175         }
176
177         $part_svc_column->setfield('columnlabel', $label)
178           if $label !~ /^\s*$/;
179
180         $part_svc_column->setfield('required', $required);
181
182         if ( $previous ) {
183           $error = $part_svc_column->replace($previous);
184         } else {
185           $error = $part_svc_column->insert;
186         }
187
188       } else {
189         $error = $previous ? $previous->delete : '';
190       }
191       if ( $error ) {
192         $dbh->rollback if $oldAutoCommit;
193         return $error;
194       }
195
196     }
197   }
198
199   # add export_svc records
200   my @exportnums = grep $exportnums->{$_}, keys %$exportnums;
201   my $slice = 100/scalar(@exportnums) if @exportnums;
202   my $done = 0;
203   foreach my $exportnum ( @exportnums ) {
204     my $export_svc = new FS::export_svc ( {
205       'exportnum' => $exportnum,
206       'svcpart'   => $self->svcpart,
207       'role'      => $exportnums->{$exportnum},
208     } );
209     $error = $export_svc->insert($job, $slice*$done++, $slice);
210     if ( $error ) {
211       $dbh->rollback if $oldAutoCommit;
212       return $error;
213     }
214   }
215
216   # XXX shouldn't this update fixed values?
217
218   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
219
220   '';
221 }
222
223 =item delete
224
225 Currently unimplemented.  Set the "disabled" field instead.
226
227 =cut
228
229 sub delete {
230   return "Can't (yet?) delete service definitions.";
231 # check & make sure the svcpart isn't in cust_svc or pkg_svc (in any packages)?
232 }
233
234 =item replace OLD_RECORD [ '1.3-COMPAT' [ , EXTRA_FIELDS_ARRAYREF [ , EXPORTNUMS_HASHREF [ , JOB ] ] ] ]
235
236 Replaces OLD_RECORD with this one in the database.  If there is an error,
237 returns the error, otherwise returns false.
238
239 TODOC: 1.3-COMPAT
240
241 TODOC: EXTRA_FIELDS_ARRAYREF (same as insert method)
242
243 TODOC: JOB
244
245 =cut
246
247 sub replace {
248   my ( $new, $old ) = ( shift, shift );
249   my $compat = '';
250   my @fields = ();
251   my $exportnums;
252   my $job = '';
253   if ( @_ && $_[0] eq '1.3-COMPAT' ) {
254     shift;
255     $compat = '1.3';
256     @fields = @{shift(@_)} if @_;
257     $exportnums = @_ ? shift : '';
258     $job = shift if @_;
259   } else {
260     return 'non-1.3-COMPAT interface not yet written';
261     #not yet implemented
262   }
263
264   return "Can't change svcdb for an existing service definition!"
265     unless $old->svcdb eq $new->svcdb;
266
267   local $SIG{HUP} = 'IGNORE';
268   local $SIG{INT} = 'IGNORE';
269   local $SIG{QUIT} = 'IGNORE';
270   local $SIG{TERM} = 'IGNORE';
271   local $SIG{TSTP} = 'IGNORE';
272   local $SIG{PIPE} = 'IGNORE';
273
274   my $oldAutoCommit = $FS::UID::AutoCommit;
275   local $FS::UID::AutoCommit = 0;
276   my $dbh = dbh;
277
278   my $error = $new->SUPER::replace( $old );
279   if ( $error ) {
280     $dbh->rollback if $oldAutoCommit;
281     return $error;
282   }
283
284   if ( $compat eq '1.3' ) {
285
286    # maintain part_svc_column records
287
288     my $svcdb = $new->svcdb;
289     foreach my $field (fields($svcdb),@fields) {
290       next if $field eq 'svcnum';
291       my $prefix = $svcdb.'__';
292       if ( defined( $new->getfield($prefix.$field.'_flag'))
293         or defined($new->getfield($prefix.$field.'_required'))
294         or length($new->getfield($prefix.$field.'_label'))
295       ) {
296         my $part_svc_column = $new->part_svc_column($field);
297         my $previous = qsearchs('part_svc_column', {
298           'svcpart'    => $new->svcpart,
299           'columnname' => $field,
300         } );
301
302         my $flag  = $new->getfield($svcdb.'__'.$field.'_flag');
303         my $label = $new->getfield($svcdb.'__'.$field.'_label');
304         my $required = $new->getfield($svcdb.'__'.$field.'_required') ? 'Y' : '';
305  
306         if ( uc($flag) =~ /^([A-Z])$/ || $label !~ /^\s*$/ ) {
307
308           if ( uc($flag) =~ /^([A-Z])$/ ) {
309             $part_svc_column->setfield('columnflag', $1);
310             my $parser = FS::part_svc->svc_table_fields($svcdb)->{$field}->{parse}
311                        || sub { shift };
312             $part_svc_column->setfield('columnvalue',
313               &$parser($new->getfield($svcdb.'__'.$field))
314             );
315           } else {
316             $part_svc_column->setfield('columnflag',  '');
317             $part_svc_column->setfield('columnvalue', '');
318           }
319
320           $part_svc_column->setfield('columnlabel', $label)
321             if $label !~ /^\s*$/;
322
323           $part_svc_column->setfield('required', $required);
324
325           if ( $previous ) {
326             $error = $part_svc_column->replace($previous);
327           } else {
328             $error = $part_svc_column->insert;
329           }
330         } else {
331           $error = $previous ? $previous->delete : '';
332         }
333         if ( $error ) {
334           $dbh->rollback if $oldAutoCommit;
335           return $error;
336         }
337       }
338     }
339
340     # maintain export_svc records
341
342     if ( $exportnums ) { # hash of exportnum => role
343
344       #false laziness w/ edit/process/agent_type.cgi
345       #and, more importantly, with m2m_Common
346       my @new_export_svc = ();
347       foreach my $part_export ( qsearch('part_export', {}) ) {
348         my $exportnum = $part_export->exportnum;
349         my $hashref = {
350           'exportnum' => $exportnum,
351           'svcpart'   => $new->svcpart,
352         };
353         my $export_svc = qsearchs('export_svc', $hashref);
354
355         if ( $export_svc ) {
356           my $old_role = $export_svc->role || 1; # 1 = null in the db
357           if ( ! $exportnums->{$exportnum}
358                or $old_role ne $exportnums->{$exportnum} ) {
359
360             $error = $export_svc->delete;
361             if ( $error ) {
362               $dbh->rollback if $oldAutoCommit;
363               return $error;
364             }
365             undef $export_svc; # on a role change, force it to be reinserted
366
367           }
368         } # if $export_svc
369         if ( ! $export_svc && $exportnums->{$exportnum} ) {
370           # also applies if it's been undef'd because of role change
371           $hashref->{role} = $exportnums->{$exportnum};
372           push @new_export_svc, new FS::export_svc ( $hashref );
373         }
374
375       }
376
377       my $slice = 100/scalar(@new_export_svc) if @new_export_svc;
378       my $done = 0;
379       foreach my $export_svc (@new_export_svc) {
380         $error = $export_svc->insert($job, $slice*$done++, $slice);
381         if ( $error ) {
382           $dbh->rollback if $oldAutoCommit;
383           return $error;
384         }
385         if ( $job ) {
386           $error = $job->update_statustext( int( $slice * $done ) );
387           if ( $error ) {
388             $dbh->rollback if $oldAutoCommit;
389             return $error;
390           }
391         }
392       }
393
394     }
395
396   } else {
397     $dbh->rollback if $oldAutoCommit;
398     return 'non-1.3-COMPAT interface not yet written';
399     #not yet implemented
400   }
401
402   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
403
404   '';
405 }
406
407 =item check
408
409 Checks all fields to make sure this is a valid service definition.  If there is
410 an error, returns the error, otherwise returns false.  Called by the insert
411 and replace methods.
412
413 =cut
414
415 sub check {
416   my $self = shift;
417
418   my $error;
419   $error=
420     $self->ut_numbern('svcpart')
421     || $self->ut_text('svc')
422     || $self->ut_alpha('svcdb')
423     || $self->ut_flag('disabled')
424     || $self->ut_flag('preserve')
425     || $self->ut_enum('selfservice_access', [ '', 'hidden', 'readonly' ] )
426     || $self->ut_foreign_keyn('classnum', 'part_svc_class', 'classnum' )
427     || $self->ut_flag('restrict_edit_password')
428     || $self->ut_flag('has_router')
429 ;
430   return $error if $error;
431
432   my @fields = eval { fields( $self->svcdb ) }; #might die
433   return "Unknown svcdb: ". $self->svcdb. " (Error: $@)"
434     unless @fields;
435
436   $self->SUPER::check;
437 }
438
439 =item part_svc_column COLUMNNAME
440
441 Returns the part_svc_column object (see L<FS::part_svc_column>) for the given
442 COLUMNNAME, or a new part_svc_column object if none exists.
443
444 =cut
445
446 sub part_svc_column {
447   my( $self, $columnname) = @_;
448   $self->svcpart &&
449     qsearchs('part_svc_column',  {
450                                    'svcpart'    => $self->svcpart,
451                                    'columnname' => $columnname,
452                                  }
453   ) or new FS::part_svc_column {
454                                  'svcpart'    => $self->svcpart,
455                                  'columnname' => $columnname,
456                                };
457 }
458
459 =item all_part_svc_column
460
461 =cut
462
463 sub all_part_svc_column {
464   my $self = shift;
465   qsearch('part_svc_column', { 'svcpart' => $self->svcpart } );
466 }
467
468 =item part_export [ EXPORTTYPE ]
469
470 Returns a list of all exports (see L<FS::part_export>) for this service, or,
471 if an export type is specified, only returns exports of the given type.
472
473 =cut
474
475 sub part_export {
476   my $self = shift;
477   my %search;
478   $search{'exporttype'} = shift if @_;
479   map { $_ } #behavior of sort undefined in scalar context
480     sort { $a->weight <=> $b->weight }
481       map { qsearchs('part_export', { 'exportnum'=>$_->exportnum, %search } ) }
482         qsearch('export_svc', { 'svcpart'=>$self->svcpart } );
483 }
484
485 =item part_export_usage
486
487 Returns a list of any exports (see L<FS::part_export>) for this service that
488 are capable of reporting usage information.
489
490 =cut
491
492 sub part_export_usage {
493   my $self = shift;
494   grep $_->can('usage_sessions'), $self->part_export;
495 }
496
497 =item part_export_did
498
499 Returns a list of any exports (see L<FS::part_export>) for this service that
500 are capable of returing available DID (phone number) information.
501
502 =cut
503
504 sub part_export_did {
505   my $self = shift;
506   grep $_->can_get_dids, $self->part_export;
507 }
508
509 =item part_export_dsl_pull
510
511 Returns a list of any exports (see L<FS::part_export>) for this service that
512 are capable of pulling/pushing DSL orders.
513
514 =cut
515
516 sub part_export_dsl_pull {
517     my $self = shift;
518     grep $_->can('dsl_pull'), $self->part_export;
519 }
520
521 =item cust_svc [ PKGPART ] 
522
523 Returns a list of associated customer services (FS::cust_svc records).
524
525 If a PKGPART is specified, returns the customer services which are contained
526 within packages of that type (see L<FS::part_pkg>).  If PKGPARTis specified as
527 B<0>, returns unlinked customer services.
528
529 =cut
530
531 sub cust_svc {
532   my $self = shift;
533
534   my $hashref = { 'svcpart' => $self->svcpart };
535
536   my( $addl_from, $extra_sql ) = ( '', '' );
537   if ( @_ ) {
538     my $pkgpart = shift;
539     if ( $pkgpart =~ /^(\d+)$/ ) {
540       $addl_from = 'LEFT JOIN cust_pkg USING ( pkgnum )';
541       $extra_sql = "AND pkgpart = $1";
542     } elsif ( $pkgpart eq '0' ) {
543       $hashref->{'pkgnum'} = '';
544     }
545   }
546
547   qsearch({
548     'table'     => 'cust_svc',
549     'addl_from' => $addl_from,
550     'hashref'   => $hashref,
551     'extra_sql' => $extra_sql,
552   });
553 }
554
555 =item num_cust_svc [ PKGPART ] 
556
557 Returns the number of associated customer services (FS::cust_svc records).
558
559 If a PKGPART is specified, returns the number of customer services which are
560 contained within packages of that type (see L<FS::part_pkg>).  If PKGPART
561 is specified as B<0>, returns the number of unlinked customer services.
562
563 =cut
564
565 sub num_cust_svc {
566   my $self = shift;
567
568   return $self->{Hash}{num_cust_svc}
569     if !@_ && exists($self->{Hash}{num_cust_svc});
570
571   my @param = ( $self->svcpart );
572
573   my( $join, $and ) = ( '', '' );
574   if ( @_ ) {
575     my $pkgpart = shift;
576     if ( $pkgpart ) {
577       $join = 'LEFT JOIN cust_pkg USING ( pkgnum )';
578       $and = 'AND pkgpart = ?';
579       push @param, $pkgpart;
580     } elsif ( $pkgpart eq '0' ) {
581       $and = 'AND pkgnum IS NULL';
582     }
583   }
584
585   my $sth = dbh->prepare(
586     "SELECT COUNT(*) FROM cust_svc $join WHERE svcpart = ? $and"
587   ) or die dbh->errstr;
588   $sth->execute(@param)
589     or die $sth->errstr;
590   $sth->fetchrow_arrayref->[0];
591 }
592
593 =item num_cust_svc_cancelled
594
595 Returns the number of associated customer services that are
596 attached to cancelled packages.
597
598 =cut
599
600 sub num_cust_svc_cancelled {
601   my $self = shift;
602   my $sth = dbh->prepare(
603     "SELECT COUNT(*) FROM cust_svc
604      LEFT JOIN cust_pkg USING ( pkgnum )
605      WHERE svcpart = ?
606      AND cust_pkg.cancel IS NOT NULL"
607   ) or die dbh->errstr;
608   $sth->execute($self->svcpart)
609     or die $sth->errstr;
610   $sth->fetchrow_arrayref->[0];
611 }
612
613 =item svc_x
614
615 Returns a list of associated FS::svc_* records.
616
617 =cut
618
619 sub svc_x {
620   my $self = shift;
621   map { $_->svc_x } $self->cust_svc;
622 }
623
624 =back
625
626 =head1 CLASS METHODS
627
628 =over 4
629
630 =cut
631
632 my $svc_defs;
633 my $svc_info;
634 sub _svc_defs {
635
636   return $svc_defs if $svc_defs; #cache
637
638   my $conf = new FS::Conf;
639
640   #false laziness w/part_pkg.pm::plan_info
641
642   my %info;
643   foreach my $INC ( @INC ) {
644     warn "globbing $INC/FS/svc_*.pm\n" if $DEBUG;
645     foreach my $file ( glob("$INC/FS/svc_*.pm") ) {
646
647       warn "attempting to load service table info from $file\n" if $DEBUG;
648       $file =~ /\/(\w+)\.pm$/ or do {
649         warn "unrecognized file in $INC/FS/: $file\n";
650         next;
651       };
652       my $mod = $1;
653
654       if ( $mod =~ /^svc_[A-Z]/ or $mod =~ /^(svc_acct_pop|svc_export_machine)$/ ) {
655         warn "skipping FS::$mod" if $DEBUG;
656         next;
657       }
658
659       eval "use FS::$mod;";
660       if ( $@ ) {
661         die "error using FS::$mod (skipping): $@\n" if $@;
662         next;
663       }
664       unless ( UNIVERSAL::can("FS::$mod", 'table_info') ) {
665         warn "FS::$mod has no table_info method; skipping";
666         next;
667       }
668
669       my $info = "FS::$mod"->table_info;
670       unless ( keys %$info ) {
671         warn "FS::$mod->table_info doesn't return info, skipping\n";
672         next;
673       }
674       warn "got info from FS::$mod: $info\n" if $DEBUG;
675       if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
676         warn "skipping disabled service FS::$mod" if $DEBUG;
677         next;
678       }
679       $info{$mod} = $info;
680
681       # all svc_* modules are required to have h_svc_* modules for invoice
682       # display. check for them as early as possible.
683       eval "use FS::h_$mod;";
684       if ( $@ ) {
685         die "couldn't load history record module h_$mod: $@\n";
686       }
687     }
688   }
689
690
691   tie my %svc_defs, 'Tie::IxHash', 
692     map  { $_ => $info{$_}->{'fields'} }
693     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
694     keys %info,
695   ;
696
697   tie my %svc_info, 'Tie::IxHash',
698     map  { $_ => $info{$_} }
699     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
700     keys %info,
701   ;
702     
703   $svc_info = \%svc_info; #access via svc_table_info  
704   $svc_defs = \%svc_defs; #cache
705   
706 }
707
708 =item svc_tables
709
710 Returns a list of all svc_ tables.
711
712 =cut
713
714 sub svc_tables {
715   my $class = shift;
716   my $svc_defs = $class->_svc_defs;
717   grep { defined( dbdef->table($_) ) } keys %$svc_defs;
718 }
719
720 =item svc_table_fields TABLE
721
722 Given a table name, returns a hashref of field names.  The field names
723 returned are those with additional (service-definition related) information,
724 not necessarily all database fields of the table.  Pseudo-fields may also
725 be returned (i.e. svc_acct.usergroup).
726
727 Each value of the hashref is another hashref, which can have one or more of
728 the following keys:
729
730 =over 4
731
732 =item label - Description of the field
733
734 =item def_label - Optional description of the field in the context of service definitions
735
736 =item type - Currently "text", "select", "checkbox", "textarea", "disabled", 
737 some components specified by "select-.*.html", and a bunch more...
738
739 =item disable_default - This field should not allow a default value in service definitions
740
741 =item disable_fixed - This field should not allow a fixed value in service definitions
742
743 =item disable_inventory - This field should not allow inventory values in service definitions
744
745 =item select_list - If type is "text", this can be a listref of possible values.
746
747 =item select_table - An alternative to select_list, this defines a database table with the possible choices.
748
749 =item select_key - Used with select_table, this is the field name of keys
750
751 =item select_label - Used with select_table, this is the field name of labels
752
753 =item select_allow_empty - Used with select_table, adds an empty option
754
755 =item required - This field should always have a true value (do not use with type checkbox or disabled)
756
757 =back
758
759 =cut
760
761 #maybe this should move and be a class method in svc_Common.pm
762 sub svc_table_fields {
763   my($class, $table) = @_;
764   my $svc_defs = $class->_svc_defs;
765   my $def = $svc_defs->{$table};
766
767   foreach ( grep !ref($def->{$_}), keys %$def ) {
768
769     #normalize the shortcut in %info hash
770     $def->{$_} = { 'label' => $def->{$_} };
771
772     $def->{$_}{'type'} ||= 'text';
773
774   }
775
776   $def;
777 }
778
779 =item svc_table_info TABLE
780
781 Returns table_info for TABLE from cache, or empty
782 hashref if none is found.
783
784 Caution:  caches table_info for ALL services when run;
785 access a service's table_info directly unless you know
786 you're loading them all.
787
788 Caution:  does not standardize fields into hashrefs;
789 use L</svc_table_fields> to access fields.
790
791 =cut
792
793 sub svc_table_info {
794   my $class = shift;
795   my $table = shift;
796   $class->_svc_defs; #creates cache if needed
797   return $svc_info->{$table} || {};
798 }
799
800 =back
801
802 =head1 SUBROUTINES
803
804 =over 4
805
806 =item process
807
808 Job-queue processor for web interface adds/edits
809
810 =cut
811
812 use Data::Dumper;
813 sub process {
814   my $job = shift;
815   my $param = shift;
816   warn Dumper($param) if $DEBUG;
817
818   my $old = qsearchs('part_svc', { 'svcpart' => $param->{'svcpart'} }) 
819     if $param->{'svcpart'};
820
821   #unmunge cgp_accessmodes (falze laziness-ish w/edit/process/svc_acct.cgi)
822   $param->{'svc_acct__cgp_accessmodes'} ||=
823     join(' ', sort
824       grep { $_ !~ /^(flag|label)$/ }
825            map { /^svc_acct__cgp_accessmodes_([\w\/]+)$/ or die "no way"; $1; }
826                grep $param->{$_},
827                     grep /^svc_acct__cgp_accessmodes_([\w\/]+)$/,
828                          keys %$param
829         );
830   
831
832   my $new = new FS::part_svc ( {
833     map {
834       $_ => $param->{$_};
835   #  } qw(svcpart svc svcdb)
836     } ( fields('part_svc'),
837         map { my $svcdb = $_;
838               my @fields = fields($svcdb);
839               push @fields, 'usergroup' if $svcdb eq 'svc_acct'
840                                         or $svcdb eq 'svc_broadband'; #kludge
841
842               map {
843                     my $f = $svcdb.'__'.$_;
844                     my $flag = $param->{ $f.'_flag' } || ''; #silence warnings
845                     if ( $flag =~ /^[MAH]$/ ) {
846                       $param->{ $f } = delete( $param->{ $f.'_classnum' } );
847                     }
848                     if ( ( $flag =~ /^[MAHS]$/ or $_ eq 'usergroup' )
849                          and ref($param->{ $f }) ) {
850                       $param->{ $f } = join(',', @{ $param->{ $f } });
851                     }
852                     ( $f, $f.'_flag', $f.'_label', $f.'_required' );
853                   }
854                   @fields;
855
856             } FS::part_svc->svc_tables()
857       )
858   } );
859   
860   my %exportnums =
861     map { $_->exportnum => ( $param->{'exportnum'.$_->exportnum} || '') }
862         qsearch('part_export', {} );
863   foreach my $exportnum (%exportnums) {
864     my $role = $param->{'exportnum'.$exportnum.'_role'};
865     # role is undef if the export has no role selector
866     if ( $exportnums{$exportnum} && $role ) {
867       $exportnums{$exportnum} = $role;
868     }
869   }
870   my $error;
871   if ( $param->{'svcpart'} ) {
872     $error = $new->replace( $old,
873                             '1.3-COMPAT',    #totally bunk, as jeff noted
874                             [ 'usergroup' ],
875                             \%exportnums,
876                             $job
877                           );
878   } else {
879     $error = $new->insert( [ 'usergroup' ],
880                            \%exportnums,
881                            $job,
882                          );
883     $param->{'svcpart'} = $new->getfield('svcpart');
884   }
885
886   die "$error\n" if $error;
887 }
888
889 =item process_bulk_cust_svc
890
891 Job-queue processor for web interface bulk customer service changes
892
893 =cut
894
895 use Data::Dumper;
896 sub process_bulk_cust_svc {
897   my $job = shift;
898   my $param = shift;
899   warn Dumper($param) if $DEBUG;
900
901   local($FS::svc_Common::noexport_hack) = 1
902     if $param->{'noexport'};
903
904   my $old_part_svc =
905     qsearchs('part_svc', { 'svcpart' => $param->{'old_svcpart'} } );
906
907   die "Must select a new service definition\n" unless $param->{'new_svcpart'};
908
909   #the rest should be abstracted out to to its own subroutine?
910
911   local $SIG{HUP} = 'IGNORE';
912   local $SIG{INT} = 'IGNORE';
913   local $SIG{QUIT} = 'IGNORE';
914   local $SIG{TERM} = 'IGNORE';
915   local $SIG{TSTP} = 'IGNORE';
916   local $SIG{PIPE} = 'IGNORE';
917
918   my $oldAutoCommit = $FS::UID::AutoCommit;
919   local $FS::UID::AutoCommit = 0;
920   my $dbh = dbh;
921
922   local( $FS::cust_svc::ignore_quantity ) = 1;
923
924   my $total = $old_part_svc->num_cust_svc( $param->{'pkgpart'} );
925
926   my $n = 0;
927   foreach my $old_cust_svc ( $old_part_svc->cust_svc( $param->{'pkgpart'} ) ) {
928
929     my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
930
931     $new_cust_svc->svcpart( $param->{'new_svcpart'} );
932     my $error = $new_cust_svc->replace($old_cust_svc);
933     if ( $error ) {
934       $dbh->rollback if $oldAutoCommit;
935       die "$error\n" if $error;
936     }
937
938     $error = $job->update_statustext( int( 100 * ++$n / $total ) );
939     if ( $error ) {
940       $dbh->rollback if $oldAutoCommit;
941       die $error if $error;
942     }
943
944   }
945
946   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
947
948   '';
949
950 }
951
952 sub _upgrade_data {  #class method
953   my ($class, %opts) = @_;
954
955   my @part_svc_column = qsearch('part_svc_column', { 'columnname' => 'usergroup' });
956   foreach my $col ( @part_svc_column ) {
957     next if $col->columnvalue =~ /^[\d,]+$/ || !$col->columnvalue;
958     my @groupnames = split(',',$col->columnvalue);
959     my @groupnums;
960     my $error = '';
961     foreach my $groupname ( @groupnames ) {
962         my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
963         unless ( $g ) {
964             $g = new FS::radius_group {
965                             'groupname' => $groupname,
966                             'description' => $groupname,
967                             };
968             $error = $g->insert;
969             die "Error inserting new radius_group for service definition group \"$groupname\": $error"
970               if $error;
971         }
972         push @groupnums, $g->groupnum;
973     }
974     $col->columnvalue(join(',',@groupnums));
975     $error = $col->replace;
976     die $error if $error;
977   }
978
979   my @badlabels = qsearch({
980     'table' => 'part_svc_column',
981     'hashref' => {},
982     'extra_sql' => 'WHERE columnlabel IN ('.
983       "'Descriptive label for this particular device.',".
984       "'IP address.  Leave blank for automatic assignment.',".
985       "'Maximum upload speed for this service in Kbps.  0 denotes unlimited.',".
986       "'Maximum download speed for this service in Kbps.  0 denotes unlimited.')"
987   });
988   foreach my $col ( @badlabels ) {
989     $col->columnlabel('');
990     my $error = $col->replace;
991     die $error if $error;
992   }
993
994 }
995
996 =head1 BUGS
997
998 Delete is unimplemented.
999
1000 The list of svc_* tables is no longer hardcoded, but svc_acct_pop is skipped
1001 as a special case until it is renamed.
1002
1003 all_part_svc_column methods should be documented
1004
1005 =head1 SEE ALSO
1006
1007 L<FS::Record>, L<FS::part_svc_column>, L<FS::part_pkg>, L<FS::pkg_svc>,
1008 L<FS::cust_svc>, L<FS::svc_acct>, L<FS::svc_forward>, L<FS::svc_domain>,
1009 schema.html from the base documentation.
1010
1011 =cut
1012
1013 1;
1014