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