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