move part_pkg transactional stuff from web interface to part_pkg.pm, bumps Bug#18...
[freeside.git] / FS / FS / part_pkg.pm
1 package FS::part_pkg;
2
3 use strict;
4 use vars qw( @ISA %freq %plans $DEBUG );
5 use Carp qw(carp cluck);
6 use Tie::IxHash;
7 use FS::Conf;
8 use FS::Record qw( qsearch qsearchs dbh dbdef );
9 use FS::pkg_svc;
10 use FS::part_svc;
11 use FS::cust_pkg;
12 use FS::agent_type;
13 use FS::type_pkgs;
14 use FS::part_pkg_option;
15
16 @ISA = qw( FS::Record );
17
18 $DEBUG = 0;
19
20 =head1 NAME
21
22 FS::part_pkg - Object methods for part_pkg objects
23
24 =head1 SYNOPSIS
25
26   use FS::part_pkg;
27
28   $record = new FS::part_pkg \%hash
29   $record = new FS::part_pkg { 'column' => 'value' };
30
31   $custom_record = $template_record->clone;
32
33   $error = $record->insert;
34
35   $error = $new_record->replace($old_record);
36
37   $error = $record->delete;
38
39   $error = $record->check;
40
41   @pkg_svc = $record->pkg_svc;
42
43   $svcnum = $record->svcpart;
44   $svcnum = $record->svcpart( 'svc_acct' );
45
46 =head1 DESCRIPTION
47
48 An FS::part_pkg object represents a package definition.  FS::part_pkg
49 inherits from FS::Record.  The following fields are currently supported:
50
51 =over 4
52
53 =item pkgpart - primary key (assigned automatically for new package definitions)
54
55 =item pkg - Text name of this package definition (customer-viewable)
56
57 =item comment - Text name of this package definition (non-customer-viewable)
58
59 =item promo_code - Promotional code
60
61 =item setup - Setup fee expression (deprecated)
62
63 =item freq - Frequency of recurring fee
64
65 =item recur - Recurring fee expression (deprecated)
66
67 =item setuptax - Setup fee tax exempt flag, empty or `Y'
68
69 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
70
71 =item taxclass - Tax class 
72
73 =item plan - Price plan
74
75 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
76
77 =item disabled - Disabled flag, empty or `Y'
78
79 =back
80
81 =head1 METHODS
82
83 =over 4 
84
85 =item new HASHREF
86
87 Creates a new package definition.  To add the package definition to
88 the database, see L<"insert">.
89
90 =cut
91
92 sub table { 'part_pkg'; }
93
94 =item clone
95
96 An alternate constructor.  Creates a new package definition by duplicating
97 an existing definition.  A new pkgpart is assigned and `(CUSTOM) ' is prepended
98 to the comment field.  To add the package definition to the database, see
99 L<"insert">.
100
101 =cut
102
103 sub clone {
104   my $self = shift;
105   my $class = ref($self);
106   my %hash = $self->hash;
107   $hash{'pkgpart'} = '';
108   $hash{'comment'} = "(CUSTOM) ". $hash{'comment'}
109     unless $hash{'comment'} =~ /^\(CUSTOM\) /;
110   #new FS::part_pkg ( \%hash ); # ?
111   new $class ( \%hash ); # ?
112 }
113
114 =item insert [ , OPTION => VALUE ... ]
115
116 Adds this package definition to the database.  If there is an error,
117 returns the error, otherwise returns false.
118
119 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg> and
120 I<custnum_ref>.
121
122 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
123 values, appropriate FS::pkg_svc records will be inserted.
124
125 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
126 FS::pkg_svc record will be updated.
127
128 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
129 record itself), the object will be updated to point to this package definition.
130
131 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
132 the scalar will be updated with the custnum value from the cust_pkg record.
133
134 =cut
135
136 sub insert {
137   my $self = shift;
138   my %options = @_;
139   warn "FS::part_pkg::insert called on $self with options %options" if $DEBUG;
140
141   local $SIG{HUP} = 'IGNORE';
142   local $SIG{INT} = 'IGNORE';
143   local $SIG{QUIT} = 'IGNORE';
144   local $SIG{TERM} = 'IGNORE';
145   local $SIG{TSTP} = 'IGNORE';
146   local $SIG{PIPE} = 'IGNORE';
147
148   my $oldAutoCommit = $FS::UID::AutoCommit;
149   local $FS::UID::AutoCommit = 0;
150   my $dbh = dbh;
151
152   warn "  saving legacy plandata" if $DEBUG;
153   my $plandata = $self->get('plandata');
154   $self->set('plandata', '');
155
156   warn "  inserting part_pkg record" if $DEBUG;
157   my $error = $self->SUPER::insert;
158   if ( $error ) {
159     $dbh->rollback if $oldAutoCommit;
160     return $error;
161   }
162
163   if ( $plandata ) {
164   warn "  inserting part_pkg_option records for plandata" if $DEBUG;
165     foreach my $part_pkg_option ( 
166       map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
167                                    return "illegal plandata: $plandata";
168                                  };
169             new FS::part_pkg_option {
170               'pkgpart'     => $self->pkgpart,
171               'optionname'  => $1,
172               'optionvalue' => $2,
173             };
174           }
175       split("\n", $plandata)
176     ) {
177       my $error = $part_pkg_option->insert;
178       if ( $error ) {
179         $dbh->rollback if $oldAutoCommit;
180         return $error;
181       }
182     }
183   }
184
185   my $conf = new FS::Conf;
186   if ( $conf->exists('agent_defaultpkg') ) {
187     warn "  agent_defaultpkg set; allowing all agents to purchase package"
188       if $DEBUG;
189     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
190       my $type_pkgs = new FS::type_pkgs({
191         'typenum' => $agent_type->typenum,
192         'pkgpart' => $self->pkgpart,
193       });
194       my $error = $type_pkgs->insert;
195       if ( $error ) {
196         $dbh->rollback if $oldAutoCommit;
197         return $error;
198       }
199     }
200   }
201
202   warn "  inserting pkg_svc records" if $DEBUG;
203   my $pkg_svc = $options{'pkg_svc'} || {};
204   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
205     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
206     my $primary_svc = $options{'primary_svc'} == $part_svc->svcpart ? 'Y' : '';
207
208     my $pkg_svc = new FS::pkg_svc( {
209       'pkgpart'     => $self->pkgpart,
210       'svcpart'     => $part_svc->svcpart,
211       'quantity'    => $quantity, 
212       'primary_svc' => $primary_svc,
213     } );
214     my $error = $pkg_svc->insert;
215     if ( $error ) {
216       $dbh->rollback if $oldAutoCommit;
217       return $error;
218     }
219   }
220
221   if ( $options{'cust_pkg'} ) {
222     warn "  updating cust_pkg record " if $DEBUG;
223     my $old_cust_pkg =
224       ref($options{'cust_pkg'})
225         ? $options{'cust_pkg'}
226         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
227     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
228       if $options{'custnum_ref'};
229     my %hash = $old_cust_pkg->hash;
230     $hash{'pkgpart'} = $self->pkgpart,
231     my $new_cust_pkg = new FS::cust_pkg \%hash;
232     local($FS::cust_pkg::disable_agentcheck) = 1;
233     my $error = $new_cust_pkg->replace($old_cust_pkg);
234     if ( $error ) {
235       $dbh->rollback if $oldAutoCommit;
236       return "Error modifying cust_pkg record: $error";
237     }
238   }
239
240   warn "  commiting transaction" if $DEBUG;
241   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
242
243   '';
244 }
245
246 =item delete
247
248 Currently unimplemented.
249
250 =cut
251
252 sub delete {
253   return "Can't (yet?) delete package definitions.";
254 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
255 }
256
257 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
258
259 Replaces OLD_RECORD with this one in the database.  If there is an error,
260 returns the error, otherwise returns false.
261
262 Currently available options are: I<pkg_svc> and I<primary_svc>
263
264 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
265 values, the appropriate FS::pkg_svc records will be replace.
266
267 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
268 FS::pkg_svc record will be updated.
269
270 =cut
271
272 sub replace {
273   my( $new, $old ) = ( shift, shift );
274   my %options = @_;
275   warn "FS::part_pkg::replace called on $new to replace $old ".
276        "with options %options"
277     if $DEBUG;
278
279   local $SIG{HUP} = 'IGNORE';
280   local $SIG{INT} = 'IGNORE';
281   local $SIG{QUIT} = 'IGNORE';
282   local $SIG{TERM} = 'IGNORE';
283   local $SIG{TSTP} = 'IGNORE';
284   local $SIG{PIPE} = 'IGNORE';
285
286   my $oldAutoCommit = $FS::UID::AutoCommit;
287   local $FS::UID::AutoCommit = 0;
288   my $dbh = dbh;
289
290   warn "  saving legacy plandata" if $DEBUG;
291   my $plandata = $new->get('plandata');
292   $new->set('plandata', '');
293
294   warn "  deleting old part_pkg_option records" if $DEBUG;
295   foreach my $part_pkg_option ( $old->part_pkg_option ) {
296     my $error = $part_pkg_option->delete;
297     if ( $error ) {
298       $dbh->rollback if $oldAutoCommit;
299       return $error;
300     }
301   }
302
303   warn "  replacing part_pkg record" if $DEBUG;
304   my $error = $new->SUPER::replace($old);
305   if ( $error ) {
306     $dbh->rollback if $oldAutoCommit;
307     return $error;
308   }
309
310   warn "  inserting part_pkg_option records for plandata" if $DEBUG;
311   foreach my $part_pkg_option ( 
312     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
313                                  return "illegal plandata: $plandata";
314                                };
315           new FS::part_pkg_option {
316             'pkgpart'     => $new->pkgpart,
317             'optionname'  => $1,
318             'optionvalue' => $2,
319           };
320         }
321     split("\n", $plandata)
322   ) {
323     my $error = $part_pkg_option->insert;
324     if ( $error ) {
325       $dbh->rollback if $oldAutoCommit;
326       return $error;
327     }
328   }
329
330   warn "  replacing pkg_svc records" if $DEBUG;
331   my $pkg_svc = $options{'pkg_svc'} || {};
332   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
333     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
334     my $primary_svc = $options{'primary_svc'} == $part_svc->svcpart ? 'Y' : '';
335
336     my $old_pkg_svc = qsearchs('pkg_svc', {
337       'pkgpart' => $old->pkgpart,
338       'svcpart' => $part_svc->svcpart,
339     } );
340     my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
341     my $old_primary_svc =
342       ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
343         ? $old_pkg_svc->primary_svc
344         : '';
345     next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
346   
347     my $new_pkg_svc = new FS::pkg_svc( {
348       'pkgpart'     => $new->pkgpart,
349       'svcpart'     => $part_svc->svcpart,
350       'quantity'    => $quantity, 
351       'primary_svc' => $primary_svc,
352     } );
353     my $error = $old_pkg_svc
354                   ? $new_pkg_svc->replace($old_pkg_svc)
355                   : $new_pkg_svc->insert;
356     if ( $error ) {
357       $dbh->rollback if $oldAutoCommit;
358       return $error;
359     }
360   }
361
362   warn "  commiting transaction" if $DEBUG;
363   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
364   '';
365 }
366
367 =item check
368
369 Checks all fields to make sure this is a valid package definition.  If
370 there is an error, returns the error, otherwise returns false.  Called by the
371 insert and replace methods.
372
373 =cut
374
375 sub check {
376   my $self = shift;
377   warn "FS::part_pkg::check called on $self" if $DEBUG;
378
379   for (qw(setup recur plandata)) {
380     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
381     return "Use of $_ field is deprecated; set a plan and options"
382       if length($self->get($_));
383     $self->set($_, '');
384   }
385
386   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
387     my $error = $self->ut_number('freq');
388     return $error if $error;
389   } else {
390     $self->freq =~ /^(\d+[dw]?)$/
391       or return "Illegal or empty freq: ". $self->freq;
392     $self->freq($1);
393   }
394
395   my $error = $self->ut_numbern('pkgpart')
396     || $self->ut_text('pkg')
397     || $self->ut_text('comment')
398     || $self->ut_textn('promo_code')
399     || $self->ut_alphan('plan')
400     || $self->ut_enum('setuptax', [ '', 'Y' ] )
401     || $self->ut_enum('recurtax', [ '', 'Y' ] )
402     || $self->ut_textn('taxclass')
403     || $self->ut_enum('disabled', [ '', 'Y' ] )
404     || $self->SUPER::check
405   ;
406   return $error if $error;
407
408   return 'Unknown plan '. $self->plan
409     unless exists($plans{$self->plan});
410
411   '';
412 }
413
414 =item pkg_svc
415
416 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
417 definition (with non-zero quantity).
418
419 =cut
420
421 sub pkg_svc {
422   my $self = shift;
423   #sort { $b->primary cmp $a->primary } 
424     grep { $_->quantity }
425       qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
426 }
427
428 =item svcpart [ SVCDB ]
429
430 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
431 associated with this package definition (see L<FS::pkg_svc>).  Returns
432 false if there not a primary service definition or exactly one service
433 definition with quantity 1, or if SVCDB is specified and does not match the
434 svcdb of the service definition, 
435
436 =cut
437
438 sub svcpart {
439   my $self = shift;
440   my $svcdb = scalar(@_) ? shift : '';
441   my @svcdb_pkg_svc =
442     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
443   my @pkg_svc = ();
444   @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc
445     if dbdef->table('pkg_svc')->column('primary_svc');
446   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
447     unless @pkg_svc;
448   return '' if scalar(@pkg_svc) != 1;
449   $pkg_svc[0]->svcpart;
450 }
451
452 =item payby
453
454 Returns a list of the acceptable payment types for this package.  Eventually
455 this should come out of a database table and be editable, but currently has the
456 following logic instead;
457
458 If the package has B<0> setup and B<0> recur, the single item B<BILL> is
459 returned, otherwise, the single item B<CARD> is returned.
460
461 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
462
463 =cut
464
465 sub payby {
466   my $self = shift;
467   #if ( $self->setup == 0 && $self->recur == 0 ) {
468   if (    $self->setup =~ /^\s*0+(\.0*)?\s*$/
469        && $self->recur =~ /^\s*0+(\.0*)?\s*$/ ) {
470     ( 'BILL' );
471   } else {
472     ( 'CARD' );
473   }
474 }
475
476 =item freq_pretty
477
478 Returns an english representation of the I<freq> field, such as "monthly",
479 "weekly", "semi-annually", etc.
480
481 =cut
482
483 tie %freq, 'Tie::IxHash', 
484   '0'  => '(no recurring fee)',
485   '1d' => 'daily',
486   '1w' => 'weekly',
487   '2w' => 'biweekly (every 2 weeks)',
488   '1'  => 'monthly',
489   '2'  => 'bimonthly (every 2 months)',
490   '3'  => 'quarterly (every 3 months)',
491   '6'  => 'semiannually (every 6 months)',
492   '12' => 'annually',
493   '24' => 'biannually (every 2 years)',
494 ;
495
496 sub freq_pretty {
497   my $self = shift;
498   my $freq = $self->freq;
499   if ( exists($freq{$freq}) ) {
500     $freq{$freq};
501   } else {
502     my $interval = 'month';
503     if ( $freq =~ /^(\d+)([dw])$/ ) {
504       my %interval = ( 'd'=>'day', 'w'=>'week' );
505       $interval = $interval{$2};
506     }
507     if ( $1 == 1 ) {
508       "every $interval";
509     } else {
510       "every $freq ${interval}s";
511     }
512   }
513 }
514
515 =item plandata
516
517 For backwards compatibility, returns the plandata field as well as all options
518 from FS::part_pkg_option.
519
520 =cut
521
522 sub plandata {
523   my $self = shift;
524   carp "plandata is deprecated";
525   if ( @_ ) {
526     $self->SUPER::plandata(@_);
527   } else {
528     my $plandata = $self->get('plandata');
529     my %options = $self->options;
530     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
531     $plandata;
532   }
533 }
534
535 =item part_pkg_option
536
537 Returns all options as FS::part_pkg_option objects (see
538 L<FS::part_pkg_option>).
539
540 =cut
541
542 sub part_pkg_option {
543   my $self = shift;
544   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
545 }
546
547 =item options 
548
549 Returns a list of option names and values suitable for assigning to a hash.
550
551 =cut
552
553 sub options {
554   my $self = shift;
555   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
556 }
557
558 =item option OPTIONNAME
559
560 Returns the option value for the given name, or the empty string.
561
562 =cut
563
564 sub option {
565   my( $self, $opt ) = @_;
566   my $part_pkg_option =
567     qsearchs('part_pkg_option', {
568       pkgpart    => $self->pkgpart,
569       optionname => $opt,
570   } );
571   return $part_pkg_option->optionvalue if $part_pkg_option;
572   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
573                      split("\n", $self->get('plandata') );
574   return $plandata{$opt} if exists $plandata{$opt};
575   cluck "Package definition option $opt not found in options or plandata!\n";
576   '';
577 }
578
579 =item _rebless
580
581 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
582 PLAN is the object's I<plan> field.  There should be better docs
583 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
584
585 =cut
586
587 sub _rebless {
588   my $self = shift;
589   my $plan = $self->plan;
590   my $class = ref($self). "::$plan";
591   eval "use $class;";
592   #die $@ if $@;
593   bless($self, $class) unless $@;
594   $self;
595 }
596
597 #fallbacks that eval the setup and recur fields, for backwards compat
598
599 sub calc_setup {
600   my $self = shift;
601   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
602   $self->_calc_eval('setup', @_);
603 }
604
605 sub calc_recur {
606   my $self = shift;
607   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
608   $self->_calc_eval('recur', @_);
609 }
610
611 use vars qw( $sdate @details );
612 sub _calc_eval {
613   #my( $self, $field, $cust_pkg ) = @_;
614   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
615   *sdate = $sdateref;
616   *details = $detailsref;
617   $self->$field() =~ /^(.*)$/
618     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
619             $self->$field(). "\n";
620   my $prog = $1;
621   return 0 if $prog =~ /^\s*$/;
622   my $value = eval $prog;
623   die $@ if $@;
624   $value;
625 }
626
627 =back
628
629 =head1 SUBROUTINES
630
631 =over 4
632
633 =item plan_info
634
635 =cut
636
637 my %info;
638 foreach my $INC ( @INC ) {
639   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
640     warn "attempting to load plan info from $file\n" if $DEBUG;
641     $file =~ /\/(\w+)\.pm$/ or do {
642       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
643       next;
644     };
645     my $mod = $1;
646     my $info = eval "use FS::part_pkg::$mod; ".
647                     "\\%FS::part_pkg::$mod\::info;";
648     if ( $@ ) {
649       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
650       next;
651     }
652     unless ( keys %$info ) {
653       warn "no %info hash found in FS::part_pkg::$mod, skipping\n"
654         unless $mod =~ /^(passwdfile|null)$/; #hack but what the heck
655       next;
656     }
657     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
658     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
659       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
660       next;
661     }
662     $info{$mod} = $info;
663   }
664 }
665
666 tie %plans, 'Tie::IxHash',
667   map { $_ => $info{$_} }
668   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
669   keys %info;
670
671 sub plan_info {
672   \%plans;
673 }
674
675 =back
676
677 =head1 NEW PLAN CLASSES
678
679 A module should be added in FS/FS/part_pkg/ (an example may be found in
680 eg/plan_template.pm)
681
682 =head1 BUGS
683
684 The delete method is unimplemented.
685
686 setup and recur semantics are not yet defined (and are implemented in
687 FS::cust_bill.  hmm.).
688
689 =head1 SEE ALSO
690
691 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
692 schema.html from the base documentation.
693
694 =cut
695
696 1;
697