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