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