RT# 81961 Repair broken links in POD documentation
[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::part_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
712       foreach ("FS::$mod"->virtual_fields_hash) {
713         $info->{'fields'}->{$_->{'name'}} = $_->{'label'};
714       }
715
716       $info{$mod} = $info;
717     }
718   }
719
720   tie my %svc_defs, 'Tie::IxHash', 
721     map  { $_ => $info{$_}->{'fields'} }
722     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
723     keys %info,
724   ;
725
726   tie my %svc_info, 'Tie::IxHash',
727     map  { $_ => $info{$_} }
728     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
729     keys %info,
730   ;
731     
732   $svc_info = \%svc_info; #access via svc_table_info  
733   $svc_defs = \%svc_defs; #cache
734   
735 }
736
737 =item svc_tables
738
739 Returns a list of all svc_ tables.
740
741 =cut
742
743 sub svc_tables {
744   my $class = shift;
745   my $svc_defs = $class->_svc_defs;
746   grep { defined( dbdef->table($_) ) } keys %$svc_defs;
747 }
748
749 =item svc_table_fields TABLE
750
751 Given a table name, returns a hashref of field names.  The field names
752 returned are those with additional (service-definition related) information,
753 not necessarily all database fields of the table.  Pseudo-fields may also
754 be returned (i.e. svc_acct.usergroup).
755
756 Each value of the hashref is another hashref, which can have one or more of
757 the following keys:
758
759 =over 4
760
761 =item label - Description of the field
762
763 =item def_label - Optional description of the field in the context of service definitions
764
765 =item type - Currently "text", "select", "checkbox", "textarea", "disabled", 
766 some components specified by "select-.*.html", and a bunch more...
767
768 =item disable_default - This field should not allow a default value in service definitions
769
770 =item disable_fixed - This field should not allow a fixed value in service definitions
771
772 =item disable_inventory - This field should not allow inventory values in service definitions
773
774 =item select_list - If type is "text", this can be a listref of possible values.
775
776 =item select_table - An alternative to select_list, this defines a database table with the possible choices.
777
778 =item select_key - Used with select_table, this is the field name of keys
779
780 =item select_label - Used with select_table, this is the field name of labels
781
782 =item select_allow_empty - Used with select_table, adds an empty option
783
784 =item required - This field should always have a true value (do not use with type checkbox or disabled)
785
786 =back
787
788 =cut
789
790 #maybe this should move and be a class method in svc_Common.pm
791 sub svc_table_fields {
792   my($class, $table) = @_;
793   my $svc_defs = $class->_svc_defs;
794   my $def = $svc_defs->{$table};
795
796   foreach ( grep !ref($def->{$_}), keys %$def ) {
797
798     #normalize the shortcut in %info hash
799     $def->{$_} = { 'label' => $def->{$_} };
800
801     $def->{$_}{'type'} ||= 'text';
802
803   }
804
805   $def;
806 }
807
808 =item svc_table_info TABLE
809
810 Returns table_info for TABLE from cache, or empty
811 hashref if none is found.
812
813 Caution:  caches table_info for ALL services when run;
814 access a service's table_info directly unless you know
815 you're loading them all.
816
817 Caution:  does not standardize fields into hashrefs;
818 use L</svc_table_fields> to access fields.
819
820 =cut
821
822 sub svc_table_info {
823   my $class = shift;
824   my $table = shift;
825   $class->_svc_defs; #creates cache if needed
826   return $svc_info->{$table} || {};
827 }
828
829 =back
830
831 =head1 SUBROUTINES
832
833 =over 4
834
835 =item process
836
837 Job-queue processor for web interface adds/edits
838
839 =cut
840
841 use Storable qw(thaw);
842 use Data::Dumper;
843 use MIME::Base64;
844 sub process {
845   my $job = shift;
846
847   my $param = thaw(decode_base64(shift));
848   warn Dumper($param) if $DEBUG;
849
850   my $old = qsearchs('part_svc', { 'svcpart' => $param->{'svcpart'} }) 
851     if $param->{'svcpart'};
852
853   #unmunge cgp_accessmodes (falze laziness-ish w/edit/process/svc_acct.cgi)
854   $param->{'svc_acct__cgp_accessmodes'} ||=
855     join(' ', sort
856       grep { $_ !~ /^(flag|label)$/ }
857            map { /^svc_acct__cgp_accessmodes_([\w\/]+)$/ or die "no way"; $1; }
858                grep $param->{$_},
859                     grep /^svc_acct__cgp_accessmodes_([\w\/]+)$/,
860                          keys %$param
861         );
862   
863
864   my $new = new FS::part_svc ( {
865     map {
866       $_ => $param->{$_};
867   #  } qw(svcpart svc svcdb)
868     } ( fields('part_svc'),
869         map { my $svcdb = $_;
870               my @fields = fields($svcdb);
871               push @fields, 'usergroup' if $svcdb eq 'svc_acct'
872                                         or $svcdb eq 'svc_broadband'; #kludge
873
874               map {
875                     my $f = $svcdb.'__'.$_;
876                     my $flag = $param->{ $f.'_flag' } || ''; #silence warnings
877                     if ( $flag =~ /^[MAHP]$/ ) {
878                       $param->{ $f } = delete( $param->{ $f.'_classnum' } );
879                     }
880                     if ( ( $flag =~ /^[MAHSP]$/ or $_ eq 'usergroup' )
881                          and ref($param->{ $f }) ) {
882                       $param->{ $f } = join(',', @{ $param->{ $f } });
883                     }
884                     ( $f, $f.'_flag', $f.'_label', $f.'_required' );
885                   }
886                   @fields;
887
888             } FS::part_svc->svc_tables()
889       )
890   } );
891   
892   my %exportnums =
893     map { $_->exportnum => ( $param->{'exportnum'.$_->exportnum} || '') }
894         qsearch('part_export', {} );
895   foreach my $exportnum (%exportnums) {
896     my $role = $param->{'exportnum'.$exportnum.'_role'};
897     # role is undef if the export has no role selector
898     if ( $exportnums{$exportnum} && $role ) {
899       $exportnums{$exportnum} = $role;
900     }
901   }
902   my $error;
903   if ( $param->{'svcpart'} ) {
904     $error = $new->replace( $old,
905                             '1.3-COMPAT',    #totally bunk, as jeff noted
906                             [ 'usergroup' ],
907                             \%exportnums,
908                             $job
909                           );
910   } else {
911     $error = $new->insert( [ 'usergroup' ],
912                            \%exportnums,
913                            $job,
914                          );
915     $param->{'svcpart'} = $new->getfield('svcpart');
916   }
917
918   $error ||= $new->process_o2m(
919     'table'   => 'part_svc_msgcat',
920     'params'  => $param,
921     'fields'  => [ 'locale', 'svc' ],
922   );
923
924   die "$error\n" if $error;
925
926   foreach my $part_svc_export ( $new->part_export_partsvc ) {
927     $error = $part_svc_export->export_partsvc($new);
928   }
929   return $error if $error;
930 }
931
932 =item process_bulk_cust_svc
933
934 Job-queue processor for web interface bulk customer service changes
935
936 =cut
937
938 use Storable qw(thaw);
939 use Data::Dumper;
940 use MIME::Base64;
941 sub process_bulk_cust_svc {
942   my $job = shift;
943
944   my $param = thaw(decode_base64(shift));
945   warn Dumper($param) if $DEBUG;
946
947   local($FS::svc_Common::noexport_hack) = 1
948     if $param->{'noexport'};
949
950   my $old_part_svc =
951     qsearchs('part_svc', { 'svcpart' => $param->{'old_svcpart'} } );
952
953   die "Must select a new service definition\n" unless $param->{'new_svcpart'};
954
955   #the rest should be abstracted out to to its own subroutine?
956
957   local $SIG{HUP} = 'IGNORE';
958   local $SIG{INT} = 'IGNORE';
959   local $SIG{QUIT} = 'IGNORE';
960   local $SIG{TERM} = 'IGNORE';
961   local $SIG{TSTP} = 'IGNORE';
962   local $SIG{PIPE} = 'IGNORE';
963
964   my $oldAutoCommit = $FS::UID::AutoCommit;
965   local $FS::UID::AutoCommit = 0;
966   my $dbh = dbh;
967
968   local( $FS::cust_svc::ignore_quantity ) = 1;
969
970   my $total = $old_part_svc->num_cust_svc( $param->{'pkgpart'} );
971
972   my $n = 0;
973   foreach my $old_cust_svc ( $old_part_svc->cust_svc( $param->{'pkgpart'} ) ) {
974
975     my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
976
977     $new_cust_svc->svcpart( $param->{'new_svcpart'} );
978     my $error = $new_cust_svc->replace($old_cust_svc);
979     if ( $error ) {
980       $dbh->rollback if $oldAutoCommit;
981       die "$error\n" if $error;
982     }
983
984     $error = $job->update_statustext( int( 100 * ++$n / $total ) );
985     if ( $error ) {
986       $dbh->rollback if $oldAutoCommit;
987       die $error if $error;
988     }
989
990   }
991
992   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
993
994   '';
995
996 }
997
998 sub _upgrade_data {  #class method
999   my ($class, %opts) = @_;
1000
1001   my @part_svc_column = qsearch('part_svc_column', { 'columnname' => 'usergroup' });
1002   foreach my $col ( @part_svc_column ) {
1003     next if $col->columnvalue =~ /^[\d,]+$/ || !$col->columnvalue;
1004     my @groupnames = split(',',$col->columnvalue);
1005     my @groupnums;
1006     my $error = '';
1007     foreach my $groupname ( @groupnames ) {
1008         my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
1009         unless ( $g ) {
1010             $g = new FS::radius_group {
1011                             'groupname' => $groupname,
1012                             'description' => $groupname,
1013                             };
1014             $error = $g->insert;
1015             die "Error inserting new radius_group for service definition group \"$groupname\": $error"
1016               if $error;
1017         }
1018         push @groupnums, $g->groupnum;
1019     }
1020     $col->columnvalue(join(',',@groupnums));
1021     $error = $col->replace;
1022     die $error if $error;
1023   }
1024
1025   my @badlabels = qsearch({
1026     'table' => 'part_svc_column',
1027     'hashref' => {},
1028     'extra_sql' => 'WHERE columnlabel IN ('.
1029       "'Descriptive label for this particular device.',".
1030       "'IP address.  Leave blank for automatic assignment.',".
1031       "'Maximum upload speed for this service in Kbps.  0 denotes unlimited.',".
1032       "'Maximum download speed for this service in Kbps.  0 denotes unlimited.')"
1033   });
1034   foreach my $col ( @badlabels ) {
1035     $col->columnlabel('');
1036     my $error = $col->replace;
1037     die $error if $error;
1038   }
1039
1040 }
1041
1042 =head1 BUGS
1043
1044 Delete is unimplemented.
1045
1046 The list of svc_* tables is no longer hardcoded, but svc_acct_pop is skipped
1047 as a special case until it is renamed.
1048
1049 all_part_svc_column methods should be documented
1050
1051 =head1 SEE ALSO
1052
1053 L<FS::Record>, L<FS::part_svc_column>, L<FS::part_pkg>, L<FS::pkg_svc>,
1054 L<FS::cust_svc>, L<FS::svc_acct>, L<FS::svc_forward>, L<FS::svc_domain>,
1055 schema.html from the base documentation.
1056
1057 =cut
1058
1059 1;
1060