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