4 use vars qw( @ISA %plans $DEBUG $setup_hack );
5 use Carp qw(carp cluck confess);
6 use Scalar::Util qw( blessed );
7 use Time::Local qw( timelocal_nocheck );
10 use FS::Record qw( qsearch qsearchs dbh dbdef );
16 use FS::part_pkg_option;
19 use FS::part_pkg_taxoverride;
20 use FS::part_pkg_taxproduct;
21 use FS::part_pkg_link;
23 @ISA = qw( FS::m2m_Common FS::option_Common );
29 FS::part_pkg - Object methods for part_pkg objects
35 $record = new FS::part_pkg \%hash
36 $record = new FS::part_pkg { 'column' => 'value' };
38 $custom_record = $template_record->clone;
40 $error = $record->insert;
42 $error = $new_record->replace($old_record);
44 $error = $record->delete;
46 $error = $record->check;
48 @pkg_svc = $record->pkg_svc;
50 $svcnum = $record->svcpart;
51 $svcnum = $record->svcpart( 'svc_acct' );
55 An FS::part_pkg object represents a package definition. FS::part_pkg
56 inherits from FS::Record. The following fields are currently supported:
60 =item pkgpart - primary key (assigned automatically for new package definitions)
62 =item pkg - Text name of this package definition (customer-viewable)
64 =item comment - Text name of this package definition (non-customer-viewable)
66 =item classnum - Optional package class (see L<FS::pkg_class>)
68 =item promo_code - Promotional code
70 =item setup - Setup fee expression (deprecated)
72 =item freq - Frequency of recurring fee
74 =item recur - Recurring fee expression (deprecated)
76 =item setuptax - Setup fee tax exempt flag, empty or `Y'
78 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
80 =item taxclass - Tax class
82 =item plan - Price plan
84 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
86 =item disabled - Disabled flag, empty or `Y'
88 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
90 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
92 =item agentnum - Optional agentnum (see L<FS::agent>)
102 Creates a new package definition. To add the package definition to
103 the database, see L<"insert">.
107 sub table { 'part_pkg'; }
111 An alternate constructor. Creates a new package definition by duplicating
112 an existing definition. A new pkgpart is assigned and `(CUSTOM) ' is prepended
113 to the comment field. To add the package definition to the database, see
120 my $class = ref($self);
121 my %hash = $self->hash;
122 $hash{'pkgpart'} = '';
123 $hash{'comment'} = "(CUSTOM) ". $hash{'comment'}
124 unless $hash{'comment'} =~ /^\(CUSTOM\) /;
125 #new FS::part_pkg ( \%hash ); # ?
126 new $class ( \%hash ); # ?
129 =item insert [ , OPTION => VALUE ... ]
131 Adds this package definition to the database. If there is an error,
132 returns the error, otherwise returns false.
134 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
135 I<custnum_ref> and I<options>.
137 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
138 values, appropriate FS::pkg_svc records will be inserted.
140 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
141 FS::pkg_svc record will be updated.
143 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
144 record itself), the object will be updated to point to this package definition.
146 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
147 the scalar will be updated with the custnum value from the cust_pkg record.
149 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
150 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
151 records will be inserted.
153 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
154 records will be inserted.
161 warn "FS::part_pkg::insert called on $self with options ".
162 join(', ', map "$_=>$options{$_}", keys %options)
165 local $SIG{HUP} = 'IGNORE';
166 local $SIG{INT} = 'IGNORE';
167 local $SIG{QUIT} = 'IGNORE';
168 local $SIG{TERM} = 'IGNORE';
169 local $SIG{TSTP} = 'IGNORE';
170 local $SIG{PIPE} = 'IGNORE';
172 my $oldAutoCommit = $FS::UID::AutoCommit;
173 local $FS::UID::AutoCommit = 0;
176 warn " inserting part_pkg record" if $DEBUG;
177 my $error = $self->SUPER::insert( $options{options} );
179 $dbh->rollback if $oldAutoCommit;
183 my $conf = new FS::Conf;
184 if ( $conf->exists('agent_defaultpkg') ) {
185 warn " agent_defaultpkg set; allowing all agents to purchase package"
187 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
188 my $type_pkgs = new FS::type_pkgs({
189 'typenum' => $agent_type->typenum,
190 'pkgpart' => $self->pkgpart,
192 my $error = $type_pkgs->insert;
194 $dbh->rollback if $oldAutoCommit;
200 warn " inserting part_pkg_taxoverride records" if $DEBUG;
201 my %overrides = %{ $options{'tax_overrides'} || {} };
202 foreach my $usage_class ( keys %overrides ) {
203 my @overrides = (grep "$_", split (',', $overrides{$usage_class}) );
204 my $error = $self->process_m2m (
205 'link_table' => 'part_pkg_taxoverride',
206 'target_table' => 'tax_class',
207 'hashref' => { 'usage_class' => $usage_class },
208 'params' => \@overrides,
211 $dbh->rollback if $oldAutoCommit;
216 warn " inserting pkg_svc records" if $DEBUG;
217 my $pkg_svc = $options{'pkg_svc'} || {};
218 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
219 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
221 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
225 my $pkg_svc = new FS::pkg_svc( {
226 'pkgpart' => $self->pkgpart,
227 'svcpart' => $part_svc->svcpart,
228 'quantity' => $quantity,
229 'primary_svc' => $primary_svc,
231 my $error = $pkg_svc->insert;
233 $dbh->rollback if $oldAutoCommit;
238 if ( $options{'cust_pkg'} ) {
239 warn " updating cust_pkg record " if $DEBUG;
241 ref($options{'cust_pkg'})
242 ? $options{'cust_pkg'}
243 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
244 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
245 if $options{'custnum_ref'};
246 my %hash = $old_cust_pkg->hash;
247 $hash{'pkgpart'} = $self->pkgpart,
248 my $new_cust_pkg = new FS::cust_pkg \%hash;
249 local($FS::cust_pkg::disable_agentcheck) = 1;
250 my $error = $new_cust_pkg->replace($old_cust_pkg);
252 $dbh->rollback if $oldAutoCommit;
253 return "Error modifying cust_pkg record: $error";
257 warn " commiting transaction" if $DEBUG;
258 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
265 Currently unimplemented.
270 return "Can't (yet?) delete package definitions.";
271 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
274 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
276 Replaces OLD_RECORD with this one in the database. If there is an error,
277 returns the error, otherwise returns false.
279 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
281 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
282 values, the appropriate FS::pkg_svc records will be replaced.
284 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
285 FS::pkg_svc record will be updated.
287 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
295 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
300 ( ref($_[0]) eq 'HASH' )
304 $options->{options} = {} unless defined($options->{options});
306 warn "FS::part_pkg::replace called on $new to replace $old with options".
307 join(', ', map "$_ => ". $options->{$_}, keys %$options)
310 local $SIG{HUP} = 'IGNORE';
311 local $SIG{INT} = 'IGNORE';
312 local $SIG{QUIT} = 'IGNORE';
313 local $SIG{TERM} = 'IGNORE';
314 local $SIG{TSTP} = 'IGNORE';
315 local $SIG{PIPE} = 'IGNORE';
317 my $oldAutoCommit = $FS::UID::AutoCommit;
318 local $FS::UID::AutoCommit = 0;
321 #plandata shit stays in replace for upgrades until after 2.0 (or edit
323 warn " saving legacy plandata" if $DEBUG;
324 my $plandata = $new->get('plandata');
325 $new->set('plandata', '');
327 warn " deleting old part_pkg_option records" if $DEBUG;
328 foreach my $part_pkg_option ( $old->part_pkg_option ) {
329 my $error = $part_pkg_option->delete;
331 $dbh->rollback if $oldAutoCommit;
336 warn " replacing part_pkg record" if $DEBUG;
337 my $error = $new->SUPER::replace($old, $options->{options} );
339 $dbh->rollback if $oldAutoCommit;
343 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
344 foreach my $part_pkg_option (
345 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
346 return "illegal plandata: $plandata";
348 new FS::part_pkg_option {
349 'pkgpart' => $new->pkgpart,
354 split("\n", $plandata)
356 my $error = $part_pkg_option->insert;
358 $dbh->rollback if $oldAutoCommit;
363 warn " replacing pkg_svc records" if $DEBUG;
364 my $pkg_svc = $options->{'pkg_svc'} || {};
365 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
366 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
368 ( defined($options->{'primary_svc'})
369 && $options->{'primary_svc'} == $part_svc->svcpart
375 my $old_pkg_svc = qsearchs('pkg_svc', {
376 'pkgpart' => $old->pkgpart,
377 'svcpart' => $part_svc->svcpart,
379 my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
380 my $old_primary_svc =
381 ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
382 ? $old_pkg_svc->primary_svc
384 next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
386 my $new_pkg_svc = new FS::pkg_svc( {
387 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
388 'pkgpart' => $new->pkgpart,
389 'svcpart' => $part_svc->svcpart,
390 'quantity' => $quantity,
391 'primary_svc' => $primary_svc,
393 my $error = $old_pkg_svc
394 ? $new_pkg_svc->replace($old_pkg_svc)
395 : $new_pkg_svc->insert;
397 $dbh->rollback if $oldAutoCommit;
402 warn " commiting transaction" if $DEBUG;
403 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
409 Checks all fields to make sure this is a valid package definition. If
410 there is an error, returns the error, otherwise returns false. Called by the
411 insert and replace methods.
417 warn "FS::part_pkg::check called on $self" if $DEBUG;
419 for (qw(setup recur plandata)) {
420 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
421 return "Use of $_ field is deprecated; set a plan and options: ".
423 if length($self->get($_));
427 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
428 my $error = $self->ut_number('freq');
429 return $error if $error;
431 $self->freq =~ /^(\d+[hdw]?)$/
432 or return "Illegal or empty freq: ". $self->freq;
436 my @null_agentnum_right = ( 'Edit global package definitions' );
437 push @null_agentnum_right, 'One-time charge'
438 if $self->freq =~ /^0/;
439 push @null_agentnum_right, 'Customize customer package'
440 if $self->disabled eq 'Y'; #good enough
442 my $error = $self->ut_numbern('pkgpart')
443 || $self->ut_text('pkg')
444 || $self->ut_text('comment')
445 || $self->ut_textn('promo_code')
446 || $self->ut_alphan('plan')
447 || $self->ut_enum('setuptax', [ '', 'Y' ] )
448 || $self->ut_enum('recurtax', [ '', 'Y' ] )
449 || $self->ut_textn('taxclass')
450 || $self->ut_enum('disabled', [ '', 'Y' ] )
451 || $self->ut_floatn('pay_weight')
452 || $self->ut_floatn('credit_weight')
453 || $self->ut_numbern('taxproductnum')
454 || $self->ut_foreign_keyn('taxproductnum',
455 'part_pkg_taxproduct',
459 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
460 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
462 || $self->SUPER::check
464 return $error if $error;
466 if ( $self->classnum !~ /^$/ ) {
467 my $error = $self->ut_foreign_key('classnum', 'pkg_class', 'classnum');
468 return $error if $error;
473 return 'Unknown plan '. $self->plan
474 unless exists($plans{$self->plan});
476 my $conf = new FS::Conf;
477 return 'Taxclass is required'
478 if ! $self->taxclass && $conf->exists('require_taxclasses');
485 Returns an (internal) string representing this package. Currently,
486 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
487 future, omitting pkgpart.
494 #$self->pkg. ' - '. $self->comment;
495 #$self->pkg. ' ('. $self->comment. ')';
496 $self->pkgpart. ': '. $self->pkg. ' - '. $self->comment;
501 Returns the package class, as an FS::pkg_class object, or the empty string
502 if there is no package class.
508 if ( $self->classnum ) {
509 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
517 Returns the package category name, or the empty string if there is no package
524 my $pkg_class = $self->pkg_class;
526 ? $pkg_class->categoryname
532 Returns the package class name, or the empty string if there is no package
539 my $pkg_class = $self->pkg_class;
541 ? $pkg_class->classname
547 Returns the associated agent for this event, if any, as an FS::agent object.
553 qsearchs('agent', { 'agentnum' => $self->agentnum } );
556 =item pkg_svc [ HASHREF | OPTION => VALUE ]
558 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
559 definition (with non-zero quantity).
561 One option is available, I<disable_linked>. If set true it will return the
562 services for this package definition alone, omitting services from any add-on
569 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
576 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
582 # #sort { $b->primary cmp $a->primary }
583 # grep { $_->quantity }
584 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
586 my $opt = ref($_[0]) ? $_[0] : { @_ };
587 my %pkg_svc = map { $_->svcpart => $_ }
588 grep { $_->quantity }
589 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
591 unless ( $opt->{disable_linked} ) {
592 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
593 my @pkg_svc = grep { $_->quantity }
594 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
595 foreach my $pkg_svc ( @pkg_svc ) {
596 if ( $pkg_svc{$pkg_svc->svcpart} ) {
597 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
598 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
600 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
610 =item svcpart [ SVCDB ]
612 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
613 associated with this package definition (see L<FS::pkg_svc>). Returns
614 false if there not a primary service definition or exactly one service
615 definition with quantity 1, or if SVCDB is specified and does not match the
616 svcdb of the service definition,
622 my $svcdb = scalar(@_) ? shift : '';
624 grep { ( $svcdb eq $_->part_svc->svcdb || !$svcdb ) } $self->pkg_svc;
625 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
626 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
628 return '' if scalar(@pkg_svc) != 1;
629 $pkg_svc[0]->svcpart;
632 =item svcpart_unique_svcdb SVCDB
634 Returns the svcpart of the a service definition (see L<FS::part_svc>) matching
635 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
636 false if there not a primary service definition for SVCDB or there are multiple
637 service definitions for SVCDB.
641 sub svcpart_unique_svcdb {
642 my( $self, $svcdb ) = @_;
643 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
644 return '' if scalar(@svcdb_pkg_svc) != 1;
645 $svcdb_pkg_svc[0]->svcpart;
650 Returns a list of the acceptable payment types for this package. Eventually
651 this should come out of a database table and be editable, but currently has the
652 following logic instead:
654 If the package is free, the single item B<BILL> is
655 returned, otherwise, the single item B<CARD> is returned.
657 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
663 if ( $self->is_free ) {
672 Returns true if this package is free.
678 unless ( $self->plan ) {
679 $self->setup =~ /^\s*0+(\.0*)?\s*$/
680 && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
681 } elsif ( $self->can('is_free_options') ) {
682 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
683 map { $self->option($_) }
684 $self->is_free_options;
686 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
687 "provides neither is_free_options nor is_free method; returning false";
694 #method, class method or sub? #my $self = shift;
696 tie my %freq, 'Tie::IxHash',
697 '0' => '(no recurring fee)',
700 '2d' => 'every two days',
701 '3d' => 'every three days',
703 '2w' => 'biweekly (every 2 weeks)',
705 '45d' => 'every 45 days',
706 '2' => 'bimonthly (every 2 months)',
707 '3' => 'quarterly (every 3 months)',
708 '4' => 'every 4 months',
709 '137d' => 'every 4 1/2 months (137 days)',
710 '6' => 'semiannually (every 6 months)',
712 '13' => 'every 13 months (annually +1 month)',
713 '24' => 'biannually (every 2 years)',
714 '36' => 'triannually (every 3 years)',
715 '48' => '(every 4 years)',
716 '60' => '(every 5 years)',
717 '120' => '(every 10 years)',
726 Returns an english representation of the I<freq> field, such as "monthly",
727 "weekly", "semi-annually", etc.
733 my $freq = $self->freq;
735 #my $freqs_href = $self->freqs_href;
736 my $freqs_href = freqs_href();
738 if ( exists($freqs_href->{$freq}) ) {
739 $freqs_href->{$freq};
741 my $interval = 'month';
742 if ( $freq =~ /^(\d+)([hdw])$/ ) {
743 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
744 $interval = $interval{$2};
749 "every $freq ${interval}s";
754 =item add_freq TIMESTAMP
756 Adds the frequency of this package to the provided timestamp and returns
757 the resulting timestamp, or -1 if the frequency of this package could not be
758 parsed (shouldn't happen).
763 my( $self, $date ) = @_;
764 my $freq = $self->freq;
766 #change this bit to use Date::Manip? CAREFUL with timezones (see
767 # mailing list archive)
768 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
770 if ( $self->freq =~ /^\d+$/ ) {
772 until ( $mon < 12 ) { $mon -= 12; $year++; }
773 } elsif ( $self->freq =~ /^(\d+)w$/ ) {
776 } elsif ( $self->freq =~ /^(\d+)d$/ ) {
779 } elsif ( $self->freq =~ /^(\d+)h$/ ) {
786 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
791 For backwards compatibility, returns the plandata field as well as all options
792 from FS::part_pkg_option.
798 carp "plandata is deprecated";
800 $self->SUPER::plandata(@_);
802 my $plandata = $self->get('plandata');
803 my %options = $self->options;
804 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
809 =item part_pkg_option
811 Returns all options as FS::part_pkg_option objects (see
812 L<FS::part_pkg_option>).
816 sub part_pkg_option {
818 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
823 Returns a list of option names and values suitable for assigning to a hash.
829 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
832 =item option OPTIONNAME
834 Returns the option value for the given name, or the empty string.
839 my( $self, $opt, $ornull ) = @_;
840 my $part_pkg_option =
841 qsearchs('part_pkg_option', {
842 pkgpart => $self->pkgpart,
845 return $part_pkg_option->optionvalue if $part_pkg_option;
846 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
847 split("\n", $self->get('plandata') );
848 return $plandata{$opt} if exists $plandata{$opt};
849 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
850 "not found in options or plandata!\n"
855 =item bill_part_pkg_link
857 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
861 sub bill_part_pkg_link {
862 shift->_part_pkg_link('bill', @_);
865 =item svc_part_pkg_link
867 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
871 sub svc_part_pkg_link {
872 shift->_part_pkg_link('svc', @_);
876 my( $self, $type ) = @_;
877 qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
878 'link_type' => $type,
883 sub self_and_bill_linked {
884 shift->_self_and_linked('bill', @_);
887 sub _self_and_linked {
888 my( $self, $type ) = @_;
891 map { $_->dst_pkg->_self_and_linked($type) }
892 $self->_part_pkg_link($type)
896 =item part_pkg_taxoverride [ CLASS ]
898 Returns all associated FS::part_pkg_taxoverride objects (see
899 L<FS::part_pkg_taxoverride>). Limits the returned set to those
900 of class CLASS if defined. Class may be one of 'setup', 'recur',
901 the empty string (default), or a usage class number (see L<FS::usage_class>).
902 When a class is specified, the empty string class (default) is returned
903 if no more specific values exist.
907 sub part_pkg_taxoverride {
911 my $hashref = { 'pkgpart' => $self->pkgpart };
912 $hashref->{'usage_class'} = $class if defined($class);
913 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
915 unless ( scalar(@overrides) || !defined($class) || !$class ){
916 $hashref->{'usage_class'} = '';
917 @overrides = qsearch('part_pkg_taxoverride', $hashref );
925 Returns true if this package has any taxproduct associated with it.
932 $self->taxproductnum ||
933 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
934 keys %{ {$self->options} }
940 =item taxproduct [ CLASS ]
942 Returns the associated tax product for this package definition (see
943 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
944 the usage classnum (see L<FS::usage_class>). Returns the default
945 tax product for this record if the more specific CLASS value does
954 my $part_pkg_taxproduct;
956 my $taxproductnum = $self->taxproductnum;
958 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
959 $taxproductnum = $class_taxproductnum
960 if $class_taxproductnum
963 $part_pkg_taxproduct =
964 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
966 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
967 $taxproductnum = $self->taxproductnum;
968 $part_pkg_taxproduct =
969 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
972 $part_pkg_taxproduct;
975 =item taxproduct_description [ CLASS ]
977 Returns the description of the associated tax product for this package
978 definition (see L<FS::part_pkg_taxproduct>).
982 sub taxproduct_description {
984 my $part_pkg_taxproduct = $self->taxproduct(@_);
985 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
988 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
990 Returns the package to taxrate m2m records for this package in the location
991 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
992 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
993 (see L<FS::usage_class>).
997 sub _expand_cch_taxproductnum {
1000 my $part_pkg_taxproduct = $self->taxproduct($class);
1002 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1003 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1006 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1007 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1008 OR taxproduct = '$a:$b:$c:'
1009 OR taxproduct = '$a:$b:".":$d'
1010 OR taxproduct = '$a:$b:".":' )";
1011 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1012 'hashref' => { 'data_vendor'=>'cch' },
1013 'extra_sql' => $extra_sql,
1018 sub part_pkg_taxrate {
1020 my ($data_vendor, $geocode, $class) = @_;
1023 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1024 dbh->quote($data_vendor);
1026 # CCH oddness in m2m
1027 $extra_sql .= ' AND ('.
1028 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1032 # much more CCH oddness in m2m -- this is kludgy
1033 my @tpnums = $self->_expand_cch_taxproductnum($class);
1034 if (scalar(@tpnums)) {
1035 $extra_sql .= ' AND ('.
1036 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1039 $extra_sql .= ' AND ( 0 = 1 )';
1042 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1043 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1044 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1046 # should qsearch preface columns with the table to facilitate joins?
1047 qsearch( { 'table' => 'part_pkg_taxrate',
1048 'select' => $select,
1049 'hashref' => { # 'data_vendor' => $data_vendor,
1050 # 'taxproductnum' => $self->taxproductnum,
1052 'addl_from' => $addl_from,
1053 'extra_sql' => $extra_sql,
1054 'order_by' => $order_by,
1060 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1061 PLAN is the object's I<plan> field. There should be better docs
1062 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1068 my $plan = $self->plan;
1070 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1074 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1075 my $class = ref($self). "::$plan";
1076 warn "reblessing $self into $class" if $DEBUG;
1079 bless($self, $class) unless $@;
1083 #fallbacks that eval the setup and recur fields, for backwards compat
1087 warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1088 $self->_calc_eval('setup', @_);
1093 warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1094 $self->_calc_eval('recur', @_);
1097 use vars qw( $sdate @details );
1099 #my( $self, $field, $cust_pkg ) = @_;
1100 my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1102 *details = $detailsref;
1103 $self->$field() =~ /^(.*)$/
1104 or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1105 $self->$field(). "\n";
1107 return 0 if $prog =~ /^\s*$/;
1108 my $value = eval $prog;
1113 #fallback that return 0 for old legacy packages with no plan
1115 sub calc_remain { 0; }
1116 sub calc_cancel { 0; }
1117 sub calc_units { 0; }
1119 =item format OPTION DATA
1121 Returns data formatted according to the function 'format' described
1122 in the plan info. Returns DATA if no such function exists.
1127 my ($self, $option, $data) = (shift, shift, shift);
1128 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1129 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1135 =item parse OPTION DATA
1137 Returns data parsed according to the function 'parse' described
1138 in the plan info. Returns DATA if no such function exists.
1143 my ($self, $option, $data) = (shift, shift, shift);
1144 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1145 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1155 =head1 CLASS METHODS
1163 # Used by FS::Upgrade to migrate to a new database.
1165 sub _upgrade_data { # class method
1166 my($class, %opts) = @_;
1168 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1170 my @part_pkg = qsearch({
1171 'table' => 'part_pkg',
1172 'extra_sql' => "WHERE ". join(' OR ',
1173 ( map "($_ IS NOT NULL AND $_ != '' )",
1174 qw( plandata setup recur ) ),
1175 'plan IS NULL', "plan = '' ",
1179 foreach my $part_pkg (@part_pkg) {
1181 unless ( $part_pkg->plan ) {
1183 $part_pkg->plan('flat');
1185 if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1187 my $opt = new FS::part_pkg_option {
1188 'pkgpart' => $part_pkg->pkgpart,
1189 'optionname' => 'setup_fee',
1190 'optionvalue' => $1,
1192 my $error = $opt->insert;
1193 die $error if $error;
1195 $part_pkg->setup('');
1198 die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1199 $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1202 if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1204 my $opt = new FS::part_pkg_option {
1205 'pkgpart' => $part_pkg->pkgpart,
1206 'optionname' => 'recur_fee',
1207 'optionvalue' => $1,
1209 my $error = $opt->insert;
1210 die $error if $error;
1212 $part_pkg->recur('');
1215 die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1216 $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1221 $part_pkg->replace; #this should take care of plandata, right?
1227 =item curuser_pkgs_sql
1229 Returns an SQL fragment for searching for packages the current user can
1230 use, either via part_pkg.agentnum directly, or via agent type (see
1235 sub curuser_pkgs_sql {
1236 #my($class) = shift;
1238 my $agentnums = join(',', $FS::CurrentUser::CurrentUser->agentnums);
1242 agentnum IS NOT NULL
1244 0 < ( SELECT COUNT(*)
1246 LEFT JOIN agent_type USING ( typenum )
1247 LEFT JOIN agent AS typeagent USING ( typenum )
1248 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1249 AND typeagent.agentnum IN ($agentnums)
1266 #false laziness w/part_export & cdr
1268 foreach my $INC ( @INC ) {
1269 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1270 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1271 warn "attempting to load plan info from $file\n" if $DEBUG;
1272 $file =~ /\/(\w+)\.pm$/ or do {
1273 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1277 my $info = eval "use FS::part_pkg::$mod; ".
1278 "\\%FS::part_pkg::$mod\::info;";
1280 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1283 unless ( keys %$info ) {
1284 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1287 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1288 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1289 warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1292 $info{$mod} = $info;
1296 tie %plans, 'Tie::IxHash',
1297 map { $_ => $info{$_} }
1298 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1308 =head1 NEW PLAN CLASSES
1310 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1311 found in eg/plan_template.pm. Until then, it is suggested that you use the
1312 other modules in FS/FS/part_pkg/ as a guide.
1316 The delete method is unimplemented.
1318 setup and recur semantics are not yet defined (and are implemented in
1319 FS::cust_bill. hmm.). now they're deprecated and need to go.
1323 part_pkg_taxrate is Pg specific
1327 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1328 schema.html from the base documentation.