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