stray closing /TABLE in the no-ticket case
[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::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 cust_svc [ PKGPART ] 
523
524 Returns a list of associated customer services (FS::cust_svc records).
525
526 If a PKGPART is specified, returns the customer services which are contained
527 within packages of that type (see L<FS::part_pkg>).  If PKGPARTis specified as
528 B<0>, returns unlinked customer services.
529
530 =cut
531
532 sub cust_svc {
533   my $self = shift;
534
535   my $hashref = { 'svcpart' => $self->svcpart };
536
537   my( $addl_from, $extra_sql ) = ( '', '' );
538   if ( @_ ) {
539     my $pkgpart = shift;
540     if ( $pkgpart =~ /^(\d+)$/ ) {
541       $addl_from = 'LEFT JOIN cust_pkg USING ( pkgnum )';
542       $extra_sql = "AND pkgpart = $1";
543     } elsif ( $pkgpart eq '0' ) {
544       $hashref->{'pkgnum'} = '';
545     }
546   }
547
548   qsearch({
549     'table'     => 'cust_svc',
550     'addl_from' => $addl_from,
551     'hashref'   => $hashref,
552     'extra_sql' => $extra_sql,
553   });
554 }
555
556 =item num_cust_svc [ PKGPART ] 
557
558 Returns the number of associated customer services (FS::cust_svc records).
559
560 If a PKGPART is specified, returns the number of customer services which are
561 contained within packages of that type (see L<FS::part_pkg>).  If PKGPART
562 is specified as B<0>, returns the number of unlinked customer services.
563
564 =cut
565
566 sub num_cust_svc {
567   my $self = shift;
568
569   return $self->{Hash}{num_cust_svc}
570     if !@_ && exists($self->{Hash}{num_cust_svc});
571
572   my @param = ( $self->svcpart );
573
574   my( $join, $and ) = ( '', '' );
575   if ( @_ ) {
576     my $pkgpart = shift;
577     if ( $pkgpart ) {
578       $join = 'LEFT JOIN cust_pkg USING ( pkgnum )';
579       $and = 'AND pkgpart = ?';
580       push @param, $pkgpart;
581     } elsif ( $pkgpart eq '0' ) {
582       $and = 'AND pkgnum IS NULL';
583     }
584   }
585
586   my $sth = dbh->prepare(
587     "SELECT COUNT(*) FROM cust_svc $join WHERE svcpart = ? $and"
588   ) or die dbh->errstr;
589   $sth->execute(@param)
590     or die $sth->errstr;
591   $sth->fetchrow_arrayref->[0];
592 }
593
594 =item num_cust_svc_cancelled
595
596 Returns the number of associated customer services that are
597 attached to cancelled packages.
598
599 =cut
600
601 sub num_cust_svc_cancelled {
602   my $self = shift;
603   my $sth = dbh->prepare(
604     "SELECT COUNT(*) FROM cust_svc
605      LEFT JOIN cust_pkg USING ( pkgnum )
606      WHERE svcpart = ?
607      AND cust_pkg.cancel IS NOT NULL"
608   ) or die dbh->errstr;
609   $sth->execute($self->svcpart)
610     or die $sth->errstr;
611   $sth->fetchrow_arrayref->[0];
612 }
613
614 =item svc_x
615
616 Returns a list of associated FS::svc_* records.
617
618 =cut
619
620 sub svc_x {
621   my $self = shift;
622   map { $_->svc_x } $self->cust_svc;
623 }
624
625 =item svc_locale LOCALE
626
627 Returns a customer-viewable service definition label in the chosen LOCALE.
628 If there is no entry for that locale or if LOCALE is empty, returns
629 part_svc.svc.
630
631 =cut
632
633 sub svc_locale {
634   my( $self, $locale ) = @_;
635   return $self->svc unless $locale;
636   my $part_svc_msgcat = qsearchs('part_svc_msgcat', {
637     svcpart => $self->svcpart,
638     locale  => $locale
639   }) or return $self->svc;
640   $part_svc_msgcat->svc;
641 }
642
643 =back
644
645 =head1 CLASS METHODS
646
647 =over 4
648
649 =cut
650
651 my $svc_defs;
652 my $svc_info;
653 sub _svc_defs {
654
655   return $svc_defs if $svc_defs; #cache
656
657   my $conf = new FS::Conf;
658
659   #false laziness w/part_pkg.pm::plan_info
660
661   my %info;
662   foreach my $INC ( @INC ) {
663     warn "globbing $INC/FS/svc_*.pm\n" if $DEBUG;
664     foreach my $file ( glob("$INC/FS/svc_*.pm") ) {
665
666       warn "attempting to load service table info from $file\n" if $DEBUG;
667       $file =~ /\/(\w+)\.pm$/ or do {
668         warn "unrecognized file in $INC/FS/: $file\n";
669         next;
670       };
671       my $mod = $1;
672
673       if ( $mod =~ /^svc_[A-Z]/ or $mod =~ /^(svc_acct_pop|svc_export_machine)$/ ) {
674         warn "skipping FS::$mod" if $DEBUG;
675         next;
676       }
677
678       eval "use FS::$mod;";
679       if ( $@ ) {
680         die "error using FS::$mod (skipping): $@\n" if $@;
681         next;
682       }
683       unless ( UNIVERSAL::can("FS::$mod", 'table_info') ) {
684         warn "FS::$mod has no table_info method; skipping";
685         next;
686       }
687
688       my $info = "FS::$mod"->table_info;
689       unless ( keys %$info ) {
690         warn "FS::$mod->table_info doesn't return info, skipping\n";
691         next;
692       }
693       warn "got info from FS::$mod: $info\n" if $DEBUG;
694       if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
695         warn "skipping disabled service FS::$mod" if $DEBUG;
696         next;
697       }
698       $info{$mod} = $info;
699
700       # all svc_* modules are required to have h_svc_* modules for invoice
701       # display. check for them as early as possible.
702       eval "use FS::h_$mod;";
703       if ( $@ ) {
704         die "couldn't load history record module h_$mod: $@\n";
705       }
706     }
707   }
708
709
710   tie my %svc_defs, 'Tie::IxHash', 
711     map  { $_ => $info{$_}->{'fields'} }
712     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
713     keys %info,
714   ;
715
716   tie my %svc_info, 'Tie::IxHash',
717     map  { $_ => $info{$_} }
718     sort { $info{$a}->{'display_weight'} <=> $info{$b}->{'display_weight'} }
719     keys %info,
720   ;
721     
722   $svc_info = \%svc_info; #access via svc_table_info  
723   $svc_defs = \%svc_defs; #cache
724   
725 }
726
727 =item svc_tables
728
729 Returns a list of all svc_ tables.
730
731 =cut
732
733 sub svc_tables {
734   my $class = shift;
735   my $svc_defs = $class->_svc_defs;
736   grep { defined( dbdef->table($_) ) } keys %$svc_defs;
737 }
738
739 =item svc_table_fields TABLE
740
741 Given a table name, returns a hashref of field names.  The field names
742 returned are those with additional (service-definition related) information,
743 not necessarily all database fields of the table.  Pseudo-fields may also
744 be returned (i.e. svc_acct.usergroup).
745
746 Each value of the hashref is another hashref, which can have one or more of
747 the following keys:
748
749 =over 4
750
751 =item label - Description of the field
752
753 =item def_label - Optional description of the field in the context of service definitions
754
755 =item type - Currently "text", "select", "checkbox", "textarea", "disabled", 
756 some components specified by "select-.*.html", and a bunch more...
757
758 =item disable_default - This field should not allow a default value in service definitions
759
760 =item disable_fixed - This field should not allow a fixed value in service definitions
761
762 =item disable_inventory - This field should not allow inventory values in service definitions
763
764 =item select_list - If type is "text", this can be a listref of possible values.
765
766 =item select_table - An alternative to select_list, this defines a database table with the possible choices.
767
768 =item select_key - Used with select_table, this is the field name of keys
769
770 =item select_label - Used with select_table, this is the field name of labels
771
772 =item select_allow_empty - Used with select_table, adds an empty option
773
774 =item required - This field should always have a true value (do not use with type checkbox or disabled)
775
776 =back
777
778 =cut
779
780 #maybe this should move and be a class method in svc_Common.pm
781 sub svc_table_fields {
782   my($class, $table) = @_;
783   my $svc_defs = $class->_svc_defs;
784   my $def = $svc_defs->{$table};
785
786   foreach ( grep !ref($def->{$_}), keys %$def ) {
787
788     #normalize the shortcut in %info hash
789     $def->{$_} = { 'label' => $def->{$_} };
790
791     $def->{$_}{'type'} ||= 'text';
792
793   }
794
795   $def;
796 }
797
798 =item svc_table_info TABLE
799
800 Returns table_info for TABLE from cache, or empty
801 hashref if none is found.
802
803 Caution:  caches table_info for ALL services when run;
804 access a service's table_info directly unless you know
805 you're loading them all.
806
807 Caution:  does not standardize fields into hashrefs;
808 use L</svc_table_fields> to access fields.
809
810 =cut
811
812 sub svc_table_info {
813   my $class = shift;
814   my $table = shift;
815   $class->_svc_defs; #creates cache if needed
816   return $svc_info->{$table} || {};
817 }
818
819 =back
820
821 =head1 SUBROUTINES
822
823 =over 4
824
825 =item process
826
827 Job-queue processor for web interface adds/edits
828
829 =cut
830
831 use Data::Dumper;
832 sub process {
833   my $job = shift;
834   my $param = shift;
835   warn Dumper($param) if $DEBUG;
836
837   my $old = qsearchs('part_svc', { 'svcpart' => $param->{'svcpart'} }) 
838     if $param->{'svcpart'};
839
840   #unmunge cgp_accessmodes (falze laziness-ish w/edit/process/svc_acct.cgi)
841   $param->{'svc_acct__cgp_accessmodes'} ||=
842     join(' ', sort
843       grep { $_ !~ /^(flag|label)$/ }
844            map { /^svc_acct__cgp_accessmodes_([\w\/]+)$/ or die "no way"; $1; }
845                grep $param->{$_},
846                     grep /^svc_acct__cgp_accessmodes_([\w\/]+)$/,
847                          keys %$param
848         );
849   
850
851   my $new = new FS::part_svc ( {
852     map {
853       $_ => $param->{$_};
854   #  } qw(svcpart svc svcdb)
855     } ( fields('part_svc'),
856         map { my $svcdb = $_;
857               my @fields = fields($svcdb);
858               push @fields, 'usergroup' if $svcdb eq 'svc_acct'
859                                         or $svcdb eq 'svc_broadband'; #kludge
860
861               map {
862                     my $f = $svcdb.'__'.$_;
863                     my $flag = $param->{ $f.'_flag' } || ''; #silence warnings
864                     if ( $flag =~ /^[MAH]$/ ) {
865                       $param->{ $f } = delete( $param->{ $f.'_classnum' } );
866                     }
867                     if ( ( $flag =~ /^[MAHS]$/ or $_ eq 'usergroup' )
868                          and ref($param->{ $f }) ) {
869                       $param->{ $f } = join(',', @{ $param->{ $f } });
870                     }
871                     ( $f, $f.'_flag', $f.'_label', $f.'_required' );
872                   }
873                   @fields;
874
875             } FS::part_svc->svc_tables()
876       )
877   } );
878   
879   my %exportnums =
880     map { $_->exportnum => ( $param->{'exportnum'.$_->exportnum} || '') }
881         qsearch('part_export', {} );
882   foreach my $exportnum (%exportnums) {
883     my $role = $param->{'exportnum'.$exportnum.'_role'};
884     # role is undef if the export has no role selector
885     if ( $exportnums{$exportnum} && $role ) {
886       $exportnums{$exportnum} = $role;
887     }
888   }
889   my $error;
890   if ( $param->{'svcpart'} ) {
891     $error = $new->replace( $old,
892                             '1.3-COMPAT',    #totally bunk, as jeff noted
893                             [ 'usergroup' ],
894                             \%exportnums,
895                             $job
896                           );
897   } else {
898     $error = $new->insert( [ 'usergroup' ],
899                            \%exportnums,
900                            $job,
901                          );
902     $param->{'svcpart'} = $new->getfield('svcpart');
903   }
904
905   $error ||= $new->process_o2m(
906     'table'   => 'part_svc_msgcat',
907     'params'  => $param,
908     'fields'  => [ 'locale', 'svc' ],
909   );
910
911   die "$error\n" if $error;
912 }
913
914 =item process_bulk_cust_svc
915
916 Job-queue processor for web interface bulk customer service changes
917
918 =cut
919
920 use Data::Dumper;
921 sub process_bulk_cust_svc {
922   my $job = shift;
923   my $param = shift;
924   warn Dumper($param) if $DEBUG;
925
926   local($FS::svc_Common::noexport_hack) = 1
927     if $param->{'noexport'};
928
929   my $old_part_svc =
930     qsearchs('part_svc', { 'svcpart' => $param->{'old_svcpart'} } );
931
932   die "Must select a new service definition\n" unless $param->{'new_svcpart'};
933
934   #the rest should be abstracted out to to its own subroutine?
935
936   local $SIG{HUP} = 'IGNORE';
937   local $SIG{INT} = 'IGNORE';
938   local $SIG{QUIT} = 'IGNORE';
939   local $SIG{TERM} = 'IGNORE';
940   local $SIG{TSTP} = 'IGNORE';
941   local $SIG{PIPE} = 'IGNORE';
942
943   my $oldAutoCommit = $FS::UID::AutoCommit;
944   local $FS::UID::AutoCommit = 0;
945   my $dbh = dbh;
946
947   local( $FS::cust_svc::ignore_quantity ) = 1;
948
949   my $total = $old_part_svc->num_cust_svc( $param->{'pkgpart'} );
950
951   my $n = 0;
952   foreach my $old_cust_svc ( $old_part_svc->cust_svc( $param->{'pkgpart'} ) ) {
953
954     my $new_cust_svc = new FS::cust_svc { $old_cust_svc->hash };
955
956     $new_cust_svc->svcpart( $param->{'new_svcpart'} );
957     my $error = $new_cust_svc->replace($old_cust_svc);
958     if ( $error ) {
959       $dbh->rollback if $oldAutoCommit;
960       die "$error\n" if $error;
961     }
962
963     $error = $job->update_statustext( int( 100 * ++$n / $total ) );
964     if ( $error ) {
965       $dbh->rollback if $oldAutoCommit;
966       die $error if $error;
967     }
968
969   }
970
971   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
972
973   '';
974
975 }
976
977 sub _upgrade_data {  #class method
978   my ($class, %opts) = @_;
979
980   my @part_svc_column = qsearch('part_svc_column', { 'columnname' => 'usergroup' });
981   foreach my $col ( @part_svc_column ) {
982     next if $col->columnvalue =~ /^[\d,]+$/ || !$col->columnvalue;
983     my @groupnames = split(',',$col->columnvalue);
984     my @groupnums;
985     my $error = '';
986     foreach my $groupname ( @groupnames ) {
987         my $g = qsearchs('radius_group', { 'groupname' => $groupname } );
988         unless ( $g ) {
989             $g = new FS::radius_group {
990                             'groupname' => $groupname,
991                             'description' => $groupname,
992                             };
993             $error = $g->insert;
994             die "Error inserting new radius_group for service definition group \"$groupname\": $error"
995               if $error;
996         }
997         push @groupnums, $g->groupnum;
998     }
999     $col->columnvalue(join(',',@groupnums));
1000     $error = $col->replace;
1001     die $error if $error;
1002   }
1003
1004   my @badlabels = qsearch({
1005     'table' => 'part_svc_column',
1006     'hashref' => {},
1007     'extra_sql' => 'WHERE columnlabel IN ('.
1008       "'Descriptive label for this particular device.',".
1009       "'IP address.  Leave blank for automatic assignment.',".
1010       "'Maximum upload speed for this service in Kbps.  0 denotes unlimited.',".
1011       "'Maximum download speed for this service in Kbps.  0 denotes unlimited.')"
1012   });
1013   foreach my $col ( @badlabels ) {
1014     $col->columnlabel('');
1015     my $error = $col->replace;
1016     die $error if $error;
1017   }
1018
1019 }
1020
1021 =head1 BUGS
1022
1023 Delete is unimplemented.
1024
1025 The list of svc_* tables is no longer hardcoded, but svc_acct_pop is skipped
1026 as a special case until it is renamed.
1027
1028 all_part_svc_column methods should be documented
1029
1030 =head1 SEE ALSO
1031
1032 L<FS::Record>, L<FS::part_svc_column>, L<FS::part_pkg>, L<FS::pkg_svc>,
1033 L<FS::cust_svc>, L<FS::svc_acct>, L<FS::svc_forward>, L<FS::svc_domain>,
1034 schema.html from the base documentation.
1035
1036 =cut
1037
1038 1;
1039