add self-service methods renew_info, order_renew and process_payment_order_renew...
[freeside.git] / FS / FS / part_pkg.pm
1 package FS::part_pkg;
2
3 use strict;
4 use vars qw( @ISA %plans $DEBUG );
5 use Carp qw(carp cluck confess);
6 use Scalar::Util qw( blessed );
7 use Time::Local qw( timelocal_nocheck );
8 use Tie::IxHash;
9 use FS::Conf;
10 use FS::Record qw( qsearch qsearchs dbh dbdef );
11 use FS::pkg_svc;
12 use FS::part_svc;
13 use FS::cust_pkg;
14 use FS::agent_type;
15 use FS::type_pkgs;
16 use FS::part_pkg_option;
17 use FS::pkg_class;
18 use FS::agent;
19 use FS::part_pkg_taxoverride;
20 use FS::part_pkg_taxproduct;
21 use FS::part_pkg_link;
22
23 @ISA = qw( FS::m2m_Common FS::option_Common );
24 $DEBUG = 0;
25
26 =head1 NAME
27
28 FS::part_pkg - Object methods for part_pkg objects
29
30 =head1 SYNOPSIS
31
32   use FS::part_pkg;
33
34   $record = new FS::part_pkg \%hash
35   $record = new FS::part_pkg { 'column' => 'value' };
36
37   $custom_record = $template_record->clone;
38
39   $error = $record->insert;
40
41   $error = $new_record->replace($old_record);
42
43   $error = $record->delete;
44
45   $error = $record->check;
46
47   @pkg_svc = $record->pkg_svc;
48
49   $svcnum = $record->svcpart;
50   $svcnum = $record->svcpart( 'svc_acct' );
51
52 =head1 DESCRIPTION
53
54 An FS::part_pkg object represents a package definition.  FS::part_pkg
55 inherits from FS::Record.  The following fields are currently supported:
56
57 =over 4
58
59 =item pkgpart - primary key (assigned automatically for new package definitions)
60
61 =item pkg - Text name of this package definition (customer-viewable)
62
63 =item comment - Text name of this package definition (non-customer-viewable)
64
65 =item classnum - Optional package class (see L<FS::pkg_class>)
66
67 =item promo_code - Promotional code
68
69 =item setup - Setup fee expression (deprecated)
70
71 =item freq - Frequency of recurring fee
72
73 =item recur - Recurring fee expression (deprecated)
74
75 =item setuptax - Setup fee tax exempt flag, empty or `Y'
76
77 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
78
79 =item taxclass - Tax class 
80
81 =item plan - Price plan
82
83 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
84
85 =item disabled - Disabled flag, empty or `Y'
86
87 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
88
89 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
90
91 =item agentnum - Optional agentnum (see L<FS::agent>)
92
93 =back
94
95 =head1 METHODS
96
97 =over 4 
98
99 =item new HASHREF
100
101 Creates a new package definition.  To add the package definition to
102 the database, see L<"insert">.
103
104 =cut
105
106 sub table { 'part_pkg'; }
107
108 =item clone
109
110 An alternate constructor.  Creates a new package definition by duplicating
111 an existing definition.  A new pkgpart is assigned and `(CUSTOM) ' is prepended
112 to the comment field.  To add the package definition to the database, see
113 L<"insert">.
114
115 =cut
116
117 sub clone {
118   my $self = shift;
119   my $class = ref($self);
120   my %hash = $self->hash;
121   $hash{'pkgpart'} = '';
122   $hash{'comment'} = "(CUSTOM) ". $hash{'comment'}
123     unless $hash{'comment'} =~ /^\(CUSTOM\) /;
124   #new FS::part_pkg ( \%hash ); # ?
125   new $class ( \%hash ); # ?
126 }
127
128 =item insert [ , OPTION => VALUE ... ]
129
130 Adds this package definition to the database.  If there is an error,
131 returns the error, otherwise returns false.
132
133 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>, 
134 I<custnum_ref> and I<options>.
135
136 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
137 values, appropriate FS::pkg_svc records will be inserted.
138
139 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
140 FS::pkg_svc record will be updated.
141
142 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
143 record itself), the object will be updated to point to this package definition.
144
145 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
146 the scalar will be updated with the custnum value from the cust_pkg record.
147
148 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
149 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
150 records will be inserted.
151
152 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
153 records will be inserted.
154
155 =cut
156
157 sub insert {
158   my $self = shift;
159   my %options = @_;
160   warn "FS::part_pkg::insert called on $self with options ".
161        join(', ', map "$_=>$options{$_}", keys %options)
162     if $DEBUG;
163
164   local $SIG{HUP} = 'IGNORE';
165   local $SIG{INT} = 'IGNORE';
166   local $SIG{QUIT} = 'IGNORE';
167   local $SIG{TERM} = 'IGNORE';
168   local $SIG{TSTP} = 'IGNORE';
169   local $SIG{PIPE} = 'IGNORE';
170
171   my $oldAutoCommit = $FS::UID::AutoCommit;
172   local $FS::UID::AutoCommit = 0;
173   my $dbh = dbh;
174
175   warn "  inserting part_pkg record" if $DEBUG;
176   my $error = $self->SUPER::insert( $options{options} );
177   if ( $error ) {
178     $dbh->rollback if $oldAutoCommit;
179     return $error;
180   }
181
182   my $conf = new FS::Conf;
183   if ( $conf->exists('agent_defaultpkg') ) {
184     warn "  agent_defaultpkg set; allowing all agents to purchase package"
185       if $DEBUG;
186     foreach my $agent_type ( qsearch('agent_type', {} ) ) {
187       my $type_pkgs = new FS::type_pkgs({
188         'typenum' => $agent_type->typenum,
189         'pkgpart' => $self->pkgpart,
190       });
191       my $error = $type_pkgs->insert;
192       if ( $error ) {
193         $dbh->rollback if $oldAutoCommit;
194         return $error;
195       }
196     }
197   }
198
199   warn "  inserting part_pkg_taxoverride records" if $DEBUG;
200   my %overrides = %{ $options{'tax_overrides'} || {} };
201   foreach my $usage_class ( keys %overrides ) {
202     my @overrides = (grep "$_", split (',', $overrides{$usage_class}) );
203     my $error = $self->process_m2m (
204                   'link_table'   => 'part_pkg_taxoverride',
205                   'target_table' => 'tax_class',
206                   'hashref'      => { 'usage_class' => $usage_class },
207                   'params'       => \@overrides,
208                 );
209     if ( $error ) {
210       $dbh->rollback if $oldAutoCommit;
211       return $error;
212     }
213   }
214
215   warn "  inserting pkg_svc records" if $DEBUG;
216   my $pkg_svc = $options{'pkg_svc'} || {};
217   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
218     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
219     my $primary_svc =
220       ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
221         ? 'Y'
222         : '';
223
224     my $pkg_svc = new FS::pkg_svc( {
225       'pkgpart'     => $self->pkgpart,
226       'svcpart'     => $part_svc->svcpart,
227       'quantity'    => $quantity, 
228       'primary_svc' => $primary_svc,
229     } );
230     my $error = $pkg_svc->insert;
231     if ( $error ) {
232       $dbh->rollback if $oldAutoCommit;
233       return $error;
234     }
235   }
236
237   if ( $options{'cust_pkg'} ) {
238     warn "  updating cust_pkg record " if $DEBUG;
239     my $old_cust_pkg =
240       ref($options{'cust_pkg'})
241         ? $options{'cust_pkg'}
242         : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
243     ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
244       if $options{'custnum_ref'};
245     my %hash = $old_cust_pkg->hash;
246     $hash{'pkgpart'} = $self->pkgpart,
247     my $new_cust_pkg = new FS::cust_pkg \%hash;
248     local($FS::cust_pkg::disable_agentcheck) = 1;
249     my $error = $new_cust_pkg->replace($old_cust_pkg);
250     if ( $error ) {
251       $dbh->rollback if $oldAutoCommit;
252       return "Error modifying cust_pkg record: $error";
253     }
254   }
255
256   warn "  commiting transaction" if $DEBUG;
257   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
258
259   '';
260 }
261
262 =item delete
263
264 Currently unimplemented.
265
266 =cut
267
268 sub delete {
269   return "Can't (yet?) delete package definitions.";
270 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
271 }
272
273 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
274
275 Replaces OLD_RECORD with this one in the database.  If there is an error,
276 returns the error, otherwise returns false.
277
278 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
279
280 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
281 values, the appropriate FS::pkg_svc records will be replaced.
282
283 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
284 FS::pkg_svc record will be updated.
285
286 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
287 will be replaced.
288
289 =cut
290
291 sub replace {
292   my $new = shift;
293
294   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
295               ? shift
296               : $new->replace_old;
297
298   my $options = 
299     ( ref($_[0]) eq 'HASH' )
300       ? shift
301       : { @_ };
302
303   $options->{options} = {} unless defined($options->{options});
304
305   warn "FS::part_pkg::replace called on $new to replace $old with options".
306        join(', ', map "$_ => ". $options->{$_}, keys %$options)
307     if $DEBUG;
308
309   local $SIG{HUP} = 'IGNORE';
310   local $SIG{INT} = 'IGNORE';
311   local $SIG{QUIT} = 'IGNORE';
312   local $SIG{TERM} = 'IGNORE';
313   local $SIG{TSTP} = 'IGNORE';
314   local $SIG{PIPE} = 'IGNORE';
315
316   my $oldAutoCommit = $FS::UID::AutoCommit;
317   local $FS::UID::AutoCommit = 0;
318   my $dbh = dbh;
319
320   #plandata shit stays in replace for upgrades until after 2.0 (or edit
321   #_upgrade_data)
322   warn "  saving legacy plandata" if $DEBUG;
323   my $plandata = $new->get('plandata');
324   $new->set('plandata', '');
325
326   warn "  deleting old part_pkg_option records" if $DEBUG;
327   foreach my $part_pkg_option ( $old->part_pkg_option ) {
328     my $error = $part_pkg_option->delete;
329     if ( $error ) {
330       $dbh->rollback if $oldAutoCommit;
331       return $error;
332     }
333   }
334
335   warn "  replacing part_pkg record" if $DEBUG;
336   my $error = $new->SUPER::replace($old, $options->{options} );
337   if ( $error ) {
338     $dbh->rollback if $oldAutoCommit;
339     return $error;
340   }
341
342   warn "  inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
343   foreach my $part_pkg_option ( 
344     map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
345                                  return "illegal plandata: $plandata";
346                                };
347           new FS::part_pkg_option {
348             'pkgpart'     => $new->pkgpart,
349             'optionname'  => $1,
350             'optionvalue' => $2,
351           };
352         }
353     split("\n", $plandata)
354   ) {
355     my $error = $part_pkg_option->insert;
356     if ( $error ) {
357       $dbh->rollback if $oldAutoCommit;
358       return $error;
359     }
360   }
361
362   warn "  replacing pkg_svc records" if $DEBUG;
363   my $pkg_svc = $options->{'pkg_svc'} || {};
364   foreach my $part_svc ( qsearch('part_svc', {} ) ) {
365     my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
366     my $primary_svc =
367       ( defined($options->{'primary_svc'})
368         && $options->{'primary_svc'} == $part_svc->svcpart
369       )
370         ? 'Y'
371         : '';
372
373
374     my $old_pkg_svc = qsearchs('pkg_svc', {
375       'pkgpart' => $old->pkgpart,
376       'svcpart' => $part_svc->svcpart,
377     } );
378     my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
379     my $old_primary_svc =
380       ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
381         ? $old_pkg_svc->primary_svc
382         : '';
383     next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
384   
385     my $new_pkg_svc = new FS::pkg_svc( {
386       'pkgsvcnum'   => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
387       'pkgpart'     => $new->pkgpart,
388       'svcpart'     => $part_svc->svcpart,
389       'quantity'    => $quantity, 
390       'primary_svc' => $primary_svc,
391     } );
392     my $error = $old_pkg_svc
393                   ? $new_pkg_svc->replace($old_pkg_svc)
394                   : $new_pkg_svc->insert;
395     if ( $error ) {
396       $dbh->rollback if $oldAutoCommit;
397       return $error;
398     }
399   }
400
401   warn "  commiting transaction" if $DEBUG;
402   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
403   '';
404 }
405
406 =item check
407
408 Checks all fields to make sure this is a valid package definition.  If
409 there is an error, returns the error, otherwise returns false.  Called by the
410 insert and replace methods.
411
412 =cut
413
414 sub check {
415   my $self = shift;
416   warn "FS::part_pkg::check called on $self" if $DEBUG;
417
418   for (qw(setup recur plandata)) {
419     #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
420     return "Use of $_ field is deprecated; set a plan and options: ".
421            $self->get($_)
422       if length($self->get($_));
423     $self->set($_, '');
424   }
425
426   if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
427     my $error = $self->ut_number('freq');
428     return $error if $error;
429   } else {
430     $self->freq =~ /^(\d+[hdw]?)$/
431       or return "Illegal or empty freq: ". $self->freq;
432     $self->freq($1);
433   }
434
435   my $error = $self->ut_numbern('pkgpart')
436     || $self->ut_text('pkg')
437     || $self->ut_text('comment')
438     || $self->ut_textn('promo_code')
439     || $self->ut_alphan('plan')
440     || $self->ut_enum('setuptax', [ '', 'Y' ] )
441     || $self->ut_enum('recurtax', [ '', 'Y' ] )
442     || $self->ut_textn('taxclass')
443     || $self->ut_enum('disabled', [ '', 'Y' ] )
444     || $self->ut_floatn('pay_weight')
445     || $self->ut_floatn('credit_weight')
446     || $self->ut_numbern('taxproductnum')
447     || $self->ut_foreign_keyn('taxproductnum',
448                               'part_pkg_taxproduct',
449                               'taxproductnum'
450                              )
451     || $self->ut_agentnum_acl('agentnum', 'Edit global package definitions')
452     || $self->SUPER::check
453   ;
454   return $error if $error;
455
456   if ( $self->classnum !~ /^$/ ) {
457     my $error = $self->ut_foreign_key('classnum', 'pkg_class', 'classnum');
458     return $error if $error;
459   } else {
460     $self->classnum('');
461   }
462
463   return 'Unknown plan '. $self->plan
464     unless exists($plans{$self->plan});
465
466   my $conf = new FS::Conf;
467   return 'Taxclass is required'
468     if ! $self->taxclass && $conf->exists('require_taxclasses');
469
470   '';
471 }
472
473 =item pkg_comment
474
475 Returns an (internal) string representing this package.  Currently,
476 "pkgpart: pkg - comment", is returned.  "pkg - comment" may be returned in the
477 future, omitting pkgpart.
478
479 =cut
480
481 sub pkg_comment {
482   my $self = shift;
483
484   #$self->pkg. ' - '. $self->comment;
485   #$self->pkg. ' ('. $self->comment. ')';
486   $self->pkgpart. ': '. $self->pkg. ' - '. $self->comment;
487 }
488
489 =item pkg_class
490
491 Returns the package class, as an FS::pkg_class object, or the empty string
492 if there is no package class.
493
494 =cut
495
496 sub pkg_class {
497   my $self = shift;
498   if ( $self->classnum ) {
499     qsearchs('pkg_class', { 'classnum' => $self->classnum } );
500   } else {
501     return '';
502   }
503 }
504
505 =item categoryname 
506
507 Returns the package category name, or the empty string if there is no package
508 category.
509
510 =cut
511
512 sub categoryname {
513   my $self = shift;
514   my $pkg_class = $self->pkg_class;
515   $pkg_class
516     ? $pkg_class->categoryname
517     : '';
518 }
519
520 =item classname 
521
522 Returns the package class name, or the empty string if there is no package
523 class.
524
525 =cut
526
527 sub classname {
528   my $self = shift;
529   my $pkg_class = $self->pkg_class;
530   $pkg_class
531     ? $pkg_class->classname
532     : '';
533 }
534
535 =item agent 
536
537 Returns the associated agent for this event, if any, as an FS::agent object.
538
539 =cut
540
541 sub agent {
542   my $self = shift;
543   qsearchs('agent', { 'agentnum' => $self->agentnum } );
544 }
545
546 =item pkg_svc [ HASHREF | OPTION => VALUE ]
547
548 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
549 definition (with non-zero quantity).
550
551 One option is available, I<disable_linked>.  If set true it will return the
552 services for this package definition alone, omitting services from any add-on
553 packages.
554
555 =cut
556
557 sub pkg_svc {
558   my $self = shift;
559
560 #  #sort { $b->primary cmp $a->primary } 
561 #    grep { $_->quantity }
562 #      qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
563
564   my $opt = ref($_[0]) ? $_[0] : { @_ };
565   my %pkg_svc = map  { $_->svcpart => $_ }
566                 grep { $_->quantity }
567                 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
568
569   unless ( $opt->{disable_linked} ) {
570     foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
571       my @pkg_svc = grep { $_->quantity }
572                     qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
573       foreach my $pkg_svc ( @pkg_svc ) {
574         if ( $pkg_svc{$pkg_svc->svcpart} ) {
575           my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
576           $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
577         } else {
578           $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
579         }
580       }
581     }
582   }
583
584   values(%pkg_svc);
585
586 }
587
588 =item svcpart [ SVCDB ]
589
590 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
591 associated with this package definition (see L<FS::pkg_svc>).  Returns
592 false if there not a primary service definition or exactly one service
593 definition with quantity 1, or if SVCDB is specified and does not match the
594 svcdb of the service definition, 
595
596 =cut
597
598 sub svcpart {
599   my $self = shift;
600   my $svcdb = scalar(@_) ? shift : '';
601   my @svcdb_pkg_svc =
602     grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
603   my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
604   @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
605     unless @pkg_svc;
606   return '' if scalar(@pkg_svc) != 1;
607   $pkg_svc[0]->svcpart;
608 }
609
610 =item svcpart_unique_svcdb SVCDB
611
612 Returns the svcpart of the a service definition (see L<FS::part_svc>) matching
613 SVCDB associated with this package definition (see L<FS::pkg_svc>).  Returns
614 false if there not a primary service definition for SVCDB or there are multiple
615 service definitions for SVCDB.
616
617 =cut
618
619 sub svcpart_unique_svcdb {
620   my( $self, $svcdb ) = @_;
621   my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
622   return '' if scalar(@svcdb_pkg_svc) != 1;
623   $svcdb_pkg_svc[0]->svcpart;
624 }
625
626 =item payby
627
628 Returns a list of the acceptable payment types for this package.  Eventually
629 this should come out of a database table and be editable, but currently has the
630 following logic instead:
631
632 If the package is free, the single item B<BILL> is
633 returned, otherwise, the single item B<CARD> is returned.
634
635 (CHEK?  LEC?  Probably shouldn't accept those by default, prone to abuse)
636
637 =cut
638
639 sub payby {
640   my $self = shift;
641   if ( $self->is_free ) {
642     ( 'BILL' );
643   } else {
644     ( 'CARD' );
645   }
646 }
647
648 =item is_free
649
650 Returns true if this package is free.  
651
652 =cut
653
654 sub is_free {
655   my $self = shift;
656   unless ( $self->plan ) {
657     $self->setup =~ /^\s*0+(\.0*)?\s*$/
658       && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
659   } elsif ( $self->can('is_free_options') ) {
660     not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
661          map { $self->option($_) } 
662              $self->is_free_options;
663   } else {
664     warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
665          "provides neither is_free_options nor is_free method; returning false";
666     0;
667   }
668 }
669
670
671 sub freqs_href {
672   #method, class method or sub? #my $self = shift;
673
674   tie my %freq, 'Tie::IxHash', 
675     '0'    => '(no recurring fee)',
676     '1h'   => 'hourly',
677     '1d'   => 'daily',
678     '2d'   => 'every two days',
679     '3d'   => 'every three days',
680     '1w'   => 'weekly',
681     '2w'   => 'biweekly (every 2 weeks)',
682     '1'    => 'monthly',
683     '45d'  => 'every 45 days',
684     '2'    => 'bimonthly (every 2 months)',
685     '3'    => 'quarterly (every 3 months)',
686     '4'    => 'every 4 months',
687     '137d' => 'every 4 1/2 months (137 days)',
688     '6'    => 'semiannually (every 6 months)',
689     '12'   => 'annually',
690     '13'   => 'every 13 months (annually +1 month)',
691     '24'   => 'biannually (every 2 years)',
692     '36'   => 'triannually (every 3 years)',
693     '48'   => '(every 4 years)',
694     '60'   => '(every 5 years)',
695     '120'  => '(every 10 years)',
696   ;
697
698   \%freq;
699
700 }
701
702 =item freq_pretty
703
704 Returns an english representation of the I<freq> field, such as "monthly",
705 "weekly", "semi-annually", etc.
706
707 =cut
708
709 sub freq_pretty {
710   my $self = shift;
711   my $freq = $self->freq;
712
713   #my $freqs_href = $self->freqs_href;
714   my $freqs_href = freqs_href();
715
716   if ( exists($freqs_href->{$freq}) ) {
717     $freqs_href->{$freq};
718   } else {
719     my $interval = 'month';
720     if ( $freq =~ /^(\d+)([hdw])$/ ) {
721       my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
722       $interval = $interval{$2};
723     }
724     if ( $1 == 1 ) {
725       "every $interval";
726     } else {
727       "every $freq ${interval}s";
728     }
729   }
730 }
731
732 =item add_freq TIMESTAMP
733
734 Adds the frequency of this package to the provided timestamp and returns
735 the resulting timestamp, or -1 if the frequency of this package could not be
736 parsed (shouldn't happen).
737
738 =cut
739
740 sub add_freq {
741   my( $self, $date ) = @_;
742   my $freq = $self->freq;
743
744   #change this bit to use Date::Manip? CAREFUL with timezones (see
745   # mailing list archive)
746   my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
747
748   if ( $self->freq =~ /^\d+$/ ) {
749     $mon += $self->freq;
750     until ( $mon < 12 ) { $mon -= 12; $year++; }
751   } elsif ( $self->freq =~ /^(\d+)w$/ ) {
752     my $weeks = $1;
753     $mday += $weeks * 7;
754   } elsif ( $self->freq =~ /^(\d+)d$/ ) {
755     my $days = $1;
756     $mday += $days;
757   } elsif ( $self->freq =~ /^(\d+)h$/ ) {
758     my $hours = $1;
759     $hour += $hours;
760   } else {
761     return -1;
762   }
763
764   timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
765 }
766
767 =item plandata
768
769 For backwards compatibility, returns the plandata field as well as all options
770 from FS::part_pkg_option.
771
772 =cut
773
774 sub plandata {
775   my $self = shift;
776   carp "plandata is deprecated";
777   if ( @_ ) {
778     $self->SUPER::plandata(@_);
779   } else {
780     my $plandata = $self->get('plandata');
781     my %options = $self->options;
782     $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
783     $plandata;
784   }
785 }
786
787 =item part_pkg_option
788
789 Returns all options as FS::part_pkg_option objects (see
790 L<FS::part_pkg_option>).
791
792 =cut
793
794 sub part_pkg_option {
795   my $self = shift;
796   qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
797 }
798
799 =item options 
800
801 Returns a list of option names and values suitable for assigning to a hash.
802
803 =cut
804
805 sub options {
806   my $self = shift;
807   map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
808 }
809
810 =item option OPTIONNAME
811
812 Returns the option value for the given name, or the empty string.
813
814 =cut
815
816 sub option {
817   my( $self, $opt, $ornull ) = @_;
818   my $part_pkg_option =
819     qsearchs('part_pkg_option', {
820       pkgpart    => $self->pkgpart,
821       optionname => $opt,
822   } );
823   return $part_pkg_option->optionvalue if $part_pkg_option;
824   my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
825                      split("\n", $self->get('plandata') );
826   return $plandata{$opt} if exists $plandata{$opt};
827   cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
828         "not found in options or plandata!\n"
829     unless $ornull;
830   '';
831 }
832
833 =item bill_part_pkg_link
834
835 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
836
837 =cut
838
839 sub bill_part_pkg_link {
840   shift->_part_pkg_link('bill', @_);
841 }
842
843 =item svc_part_pkg_link
844
845 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
846
847 =cut
848
849 sub svc_part_pkg_link {
850   shift->_part_pkg_link('svc', @_);
851 }
852
853 sub _part_pkg_link {
854   my( $self, $type ) = @_;
855   qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
856                              'link_type'   => $type,
857                            }
858          );
859 }
860
861 sub self_and_bill_linked {
862   shift->_self_and_linked('bill', @_);
863 }
864
865 sub _self_and_linked {
866   my( $self, $type ) = @_;
867
868   ( $self,
869     map { $_->dst_pkg->_self_and_linked($type) }
870         $self->_part_pkg_link($type)
871   );
872 }
873
874 =item part_pkg_taxoverride [ CLASS ]
875
876 Returns all associated FS::part_pkg_taxoverride objects (see
877 L<FS::part_pkg_taxoverride>).  Limits the returned set to those
878 of class CLASS if defined.  Class may be one of 'setup', 'recur',
879 the empty string (default), or a usage class number (see L<FS::usage_class>).
880 When a class is specified, the empty string class (default) is returned
881 if no more specific values exist.
882
883 =cut
884
885 sub part_pkg_taxoverride {
886   my $self = shift;
887   my $class = shift;
888
889   my $hashref = { 'pkgpart' => $self->pkgpart };
890   $hashref->{'usage_class'} = $class if defined($class);
891   my @overrides = qsearch('part_pkg_taxoverride', $hashref );
892
893   unless ( scalar(@overrides) || !defined($class) || !$class ){
894     $hashref->{'usage_class'} = '';
895     @overrides = qsearch('part_pkg_taxoverride', $hashref );
896   }
897
898   @overrides;
899 }
900
901 =item has_taxproduct
902
903 Returns true if this package has any taxproduct associated with it.  
904
905 =cut
906
907 sub has_taxproduct {
908   my $self = shift;
909
910   $self->taxproductnum ||
911   scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) } 
912           keys %{ {$self->options} }
913   )
914
915 }
916
917
918 =item taxproduct [ CLASS ]
919
920 Returns the associated tax product for this package definition (see
921 L<FS::part_pkg_taxproduct>).  CLASS may be one of 'setup', 'recur' or
922 the usage classnum (see L<FS::usage_class>).  Returns the default
923 tax product for this record if the more specific CLASS value does
924 not exist.
925
926 =cut
927
928 sub taxproduct {
929   my $self = shift;
930   my $class = shift;
931
932   my $part_pkg_taxproduct;
933
934   my $taxproductnum = $self->taxproductnum;
935   if ($class) { 
936     my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
937     $taxproductnum = $class_taxproductnum
938       if $class_taxproductnum
939   }
940   
941   $part_pkg_taxproduct =
942     qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
943
944   unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
945     $taxproductnum = $self->taxproductnum;
946     $part_pkg_taxproduct =
947       qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
948   }
949
950   $part_pkg_taxproduct;
951 }
952
953 =item taxproduct_description [ CLASS ]
954
955 Returns the description of the associated tax product for this package
956 definition (see L<FS::part_pkg_taxproduct>).
957
958 =cut
959
960 sub taxproduct_description {
961   my $self = shift;
962   my $part_pkg_taxproduct = $self->taxproduct(@_);
963   $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
964 }
965
966 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
967
968 Returns the package to taxrate m2m records for this package in the location
969 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
970 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
971 (see L<FS::usage_class>).
972
973 =cut
974
975 sub _expand_cch_taxproductnum {
976   my $self = shift;
977   my $class = shift;
978   my $part_pkg_taxproduct = $self->taxproduct($class);
979
980   my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
981                          ? ( split ':', $part_pkg_taxproduct->taxproduct )
982                          : ()
983                      );
984   $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
985   my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
986                       OR taxproduct = '$a:$b:$c:'
987                       OR taxproduct = '$a:$b:".":$d'
988                       OR taxproduct = '$a:$b:".":' )";
989   map { $_->taxproductnum } qsearch( { 'table'     => 'part_pkg_taxproduct',
990                                        'hashref'   => { 'data_vendor'=>'cch' },
991                                        'extra_sql' => $extra_sql,
992                                    } );
993                                      
994 }
995
996 sub part_pkg_taxrate {
997   my $self = shift;
998   my ($data_vendor, $geocode, $class) = @_;
999
1000   my $dbh = dbh;
1001   my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1002                   dbh->quote($data_vendor);
1003   
1004   # CCH oddness in m2m
1005   $extra_sql .= ' AND ('.
1006     join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1007                  qw(10 5 2)
1008         ).
1009     ')';
1010   # much more CCH oddness in m2m -- this is kludgy
1011   my @tpnums = $self->_expand_cch_taxproductnum($class);
1012   $extra_sql .= ' AND ('.
1013                           join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1014                      ')'
1015      if @tpnums;
1016
1017   my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1018   my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1019   my $select   = 'DISTINCT ON(taxclassnum) *, taxproduct';
1020
1021   # should qsearch preface columns with the table to facilitate joins?
1022   qsearch( { 'table'     => 'part_pkg_taxrate',
1023              'select'    => $select,
1024              'hashref'   => { # 'data_vendor'   => $data_vendor,
1025                               # 'taxproductnum' => $self->taxproductnum,
1026                             },
1027              'addl_from' => $addl_from,
1028              'extra_sql' => $extra_sql,
1029              'order_by'  => $order_by,
1030          } );
1031 }
1032
1033 =item _rebless
1034
1035 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1036 PLAN is the object's I<plan> field.  There should be better docs
1037 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1038
1039 =cut
1040
1041 sub _rebless {
1042   my $self = shift;
1043   my $plan = $self->plan;
1044   unless ( $plan ) {
1045     cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1046       if $DEBUG;
1047     return $self;
1048   }
1049   return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1050   my $class = ref($self). "::$plan";
1051   warn "reblessing $self into $class" if $DEBUG;
1052   eval "use $class;";
1053   die $@ if $@;
1054   bless($self, $class) unless $@;
1055   $self;
1056 }
1057
1058 #fallbacks that eval the setup and recur fields, for backwards compat
1059
1060 sub calc_setup {
1061   my $self = shift;
1062   warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1063   $self->_calc_eval('setup', @_);
1064 }
1065
1066 sub calc_recur {
1067   my $self = shift;
1068   warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1069   $self->_calc_eval('recur', @_);
1070 }
1071
1072 use vars qw( $sdate @details );
1073 sub _calc_eval {
1074   #my( $self, $field, $cust_pkg ) = @_;
1075   my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1076   *sdate = $sdateref;
1077   *details = $detailsref;
1078   $self->$field() =~ /^(.*)$/
1079     or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1080             $self->$field(). "\n";
1081   my $prog = $1;
1082   return 0 if $prog =~ /^\s*$/;
1083   my $value = eval $prog;
1084   die $@ if $@;
1085   $value;
1086 }
1087
1088 #fallback that return 0 for old legacy packages with no plan
1089
1090 sub calc_remain { 0; }
1091 sub calc_cancel { 0; }
1092 sub calc_units  { 0; }
1093
1094 =back
1095
1096 =cut
1097
1098 # _upgrade_data
1099 #
1100 # Used by FS::Upgrade to migrate to a new database.
1101
1102 sub _upgrade_data { # class method
1103   my($class, %opts) = @_;
1104
1105   warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1106
1107   my @part_pkg = qsearch({
1108     'table'     => 'part_pkg',
1109     'extra_sql' => "WHERE ". join(' OR ',
1110                      ( map "($_ IS NOT NULL AND $_ != '' )",
1111                            qw( plandata setup recur ) ),
1112                      'plan IS NULL', "plan = '' ",
1113                    ),
1114   });
1115
1116   foreach my $part_pkg (@part_pkg) {
1117
1118     unless ( $part_pkg->plan ) {
1119
1120       $part_pkg->plan('flat');
1121
1122       if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1123
1124         my $opt = new FS::part_pkg_option {
1125           'pkgpart'     => $part_pkg->pkgpart,
1126           'optionname'  => 'setup_fee',
1127           'optionvalue' => $1,
1128         };
1129         my $error = $opt->insert;
1130         die $error if $error;
1131
1132         $part_pkg->setup('');
1133
1134       } else {
1135         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1136             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1137       }
1138
1139       if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1140
1141         my $opt = new FS::part_pkg_option {
1142           'pkgpart'     => $part_pkg->pkgpart,
1143           'optionname'  => 'recur_fee',
1144           'optionvalue' => $1,
1145         };
1146         my $error = $opt->insert;
1147         die $error if $error;
1148
1149         $part_pkg->recur('');
1150
1151       } else {
1152         die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1153             $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1154       }
1155
1156     }
1157
1158     $part_pkg->replace; #this should take care of plandata, right?
1159
1160   }
1161
1162 }
1163
1164 =head1 SUBROUTINES
1165
1166 =over 4
1167
1168 =item plan_info
1169
1170 =cut
1171
1172 #false laziness w/part_export & cdr
1173 my %info;
1174 foreach my $INC ( @INC ) {
1175   warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1176   foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1177     warn "attempting to load plan info from $file\n" if $DEBUG;
1178     $file =~ /\/(\w+)\.pm$/ or do {
1179       warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1180       next;
1181     };
1182     my $mod = $1;
1183     my $info = eval "use FS::part_pkg::$mod; ".
1184                     "\\%FS::part_pkg::$mod\::info;";
1185     if ( $@ ) {
1186       die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1187       next;
1188     }
1189     unless ( keys %$info ) {
1190       warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1191       next;
1192     }
1193     warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1194     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1195       warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1196       next;
1197     }
1198     $info{$mod} = $info;
1199   }
1200 }
1201
1202 tie %plans, 'Tie::IxHash',
1203   map  { $_ => $info{$_} }
1204   sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1205   keys %info;
1206
1207 sub plan_info {
1208   \%plans;
1209 }
1210
1211 =item format OPTION DATA
1212
1213 Returns data formatted according to the function 'format' described
1214 in the plan info.  Returns DATA if no such function exists.
1215
1216 =cut
1217
1218 sub format {
1219   my ($self, $option, $data) = (shift, shift, shift);
1220   if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1221     &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1222   }else{
1223     $data;
1224   }
1225 }
1226
1227 =item parse OPTION DATA
1228
1229 Returns data parsed according to the function 'parse' described
1230 in the plan info.  Returns DATA if no such function exists.
1231
1232 =cut
1233
1234 sub parse {
1235   my ($self, $option, $data) = (shift, shift, shift);
1236   if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1237     &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1238   }else{
1239     $data;
1240   }
1241 }
1242
1243
1244 =back
1245
1246 =head1 NEW PLAN CLASSES
1247
1248 A module should be added in FS/FS/part_pkg/  Eventually, an example may be
1249 found in eg/plan_template.pm.  Until then, it is suggested that you use the
1250 other modules in FS/FS/part_pkg/ as a guide.
1251
1252 =head1 BUGS
1253
1254 The delete method is unimplemented.
1255
1256 setup and recur semantics are not yet defined (and are implemented in
1257 FS::cust_bill.  hmm.).  now they're deprecated and need to go.
1258
1259 plandata should go
1260
1261 part_pkg_taxrate is Pg specific
1262
1263 =head1 SEE ALSO
1264
1265 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1266 schema.html from the base documentation.
1267
1268 =cut
1269
1270 1;
1271