creditcard-less promo code signup
[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 is free, 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->is_free ) {
468     ( 'BILL' );
469   } else {
470     ( 'CARD' );
471   }
472 }
473
474 =item is_free
475
476 Returns true if this package is free.  
477
478 =cut
479
480 sub is_free {
481   my $self = shift;
482   unless ( $self->plan ) {
483     $self->setup =~ /^\s*0+(\.0*)?\s*$/
484       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
485   } elsif ( $self->can('is_free_options') ) {
486     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
487          map { $self->option($_) } 
488              $self->is_free_options;
489   } else {
490     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
491          "provides neither is_free_options nor is_free method; returning false";
492     0;
493   }
494 }
495
496 =item freq_pretty
497
498 Returns an english representation of the I<freq> field, such as "monthly",
499 "weekly", "semi-annually", etc.
500
501 =cut
502
503 tie %freq, 'Tie::IxHash', 
504   '0'  => '(no recurring fee)',
505   '1d' => 'daily',
506   '1w' => 'weekly',
507   '2w' => 'biweekly (every 2 weeks)',
508   '1'  => 'monthly',
509   '2'  => 'bimonthly (every 2 months)',
510   '3'  => 'quarterly (every 3 months)',
511   '6'  => 'semiannually (every 6 months)',
512   '12' => 'annually',
513   '24' => 'biannually (every 2 years)',
514 ;
515
516 sub freq_pretty {
517   my $self = shift;
518   my $freq = $self->freq;
519   if ( exists($freq{$freq}) ) {
520     $freq{$freq};
521   } else {
522     my $interval = 'month';
523     if ( $freq =~ /^(\d+)([dw])$/ ) {
524       my %interval = ( 'd'=>'day', 'w'=>'week' );
525       $interval = $interval{$2};
526     }
527     if ( $1 == 1 ) {
528       "every $interval";
529     } else {
530       "every $freq ${interval}s";
531     }
532   }
533 }
534
535 =item plandata
536
537 For backwards compatibility, returns the plandata field as well as all options
538 from FS::part_pkg_option.
539
540 =cut
541
542 sub plandata {
543   my $self = shift;
544   carp "plandata is deprecated";
545   if ( @_ ) {
546     $self->SUPER::plandata(@_);
547   } else {
548     my $plandata = $self->get('plandata');
549     my %options = $self->options;
550     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
551     $plandata;
552   }
553 }
554
555 =item part_pkg_option
556
557 Returns all options as FS::part_pkg_option objects (see
558 L<FS::part_pkg_option>).
559
560 =cut
561
562 sub part_pkg_option {
563   my $self = shift;
564   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
565 }
566
567 =item options 
568
569 Returns a list of option names and values suitable for assigning to a hash.
570
571 =cut
572
573 sub options {
574   my $self = shift;
575   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
576 }
577
578 =item option OPTIONNAME
579
580 Returns the option value for the given name, or the empty string.
581
582 =cut
583
584 sub option {
585   my( $self, $opt ) = @_;
586   my $part_pkg_option =
587     qsearchs('part_pkg_option', {
588       pkgpart    => $self->pkgpart,
589       optionname => $opt,
590   } );
591   return $part_pkg_option->optionvalue if $part_pkg_option;
592   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
593                      split("\n", $self->get('plandata') );
594   return $plandata{$opt} if exists $plandata{$opt};
595   cluck "Package definition option $opt not found in options or plandata!\n";
596   '';
597 }
598
599 =item _rebless
600
601 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
602 PLAN is the object's I<plan> field.  There should be better docs
603 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
604
605 =cut
606
607 sub _rebless {
608   my $self = shift;
609   my $plan = $self->plan;
610   my $class = ref($self). "::$plan";
611   eval "use $class;";
612   #die $@ if $@;
613   bless($self, $class) unless $@;
614   $self;
615 }
616
617 #fallbacks that eval the setup and recur fields, for backwards compat
618
619 sub calc_setup {
620   my $self = shift;
621   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
622   $self->_calc_eval('setup', @_);
623 }
624
625 sub calc_recur {
626   my $self = shift;
627   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
628   $self->_calc_eval('recur', @_);
629 }
630
631 use vars qw( $sdate @details );
632 sub _calc_eval {
633   #my( $self, $field, $cust_pkg ) = @_;
634   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
635   *sdate = $sdateref;
636   *details = $detailsref;
637   $self->$field() =~ /^(.*)$/
638     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
639             $self->$field(). "\n";
640   my $prog = $1;
641   return 0 if $prog =~ /^\s*$/;
642   my $value = eval $prog;
643   die $@ if $@;
644   $value;
645 }
646
647 =back
648
649 =head1 SUBROUTINES
650
651 =over 4
652
653 =item plan_info
654
655 =cut
656
657 my %info;
658 foreach my $INC ( @INC ) {
659   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
660     warn "attempting to load plan info from $file\n" if $DEBUG;
661     $file =~ /\/(\w+)\.pm$/ or do {
662       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
663       next;
664     };
665     my $mod = $1;
666     my $info = eval "use FS::part_pkg::$mod; ".
667                     "\\%FS::part_pkg::$mod\::info;";
668     if ( $@ ) {
669       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
670       next;
671     }
672     unless ( keys %$info ) {
673       warn "no %info hash found in FS::part_pkg::$mod, skipping\n"
674         unless $mod =~ /^(passwdfile|null)$/; #hack but what the heck
675       next;
676     }
677     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
678     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
679       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
680       next;
681     }
682     $info{$mod} = $info;
683   }
684 }
685
686 tie %plans, 'Tie::IxHash',
687   map { $_ => $info{$_} }
688   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
689   keys %info;
690
691 sub plan_info {
692   \%plans;
693 }
694
695 =back
696
697 =head1 NEW PLAN CLASSES
698
699 A module should be added in FS/FS/part_pkg/ (an example may be found in
700 eg/plan_template.pm)
701
702 =head1 BUGS
703
704 The delete method is unimplemented.
705
706 setup and recur semantics are not yet defined (and are implemented in
707 FS::cust_bill.  hmm.).
708
709 =head1 SEE ALSO
710
711 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
712 schema.html from the base documentation.
713
714 =cut
715
716 1;
717