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