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 setup_cost - for cost tracking
90 =item recur_cost - for cost tracking
92 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
94 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
96 =item agentnum - Optional agentnum (see L<FS::agent>)
106 Creates a new package definition. To add the package definition to
107 the database, see L<"insert">.
111 sub table { 'part_pkg'; }
115 An alternate constructor. Creates a new package definition by duplicating
116 an existing definition. A new pkgpart is assigned and `(CUSTOM) ' is prepended
117 to the comment field. To add the package definition to the database, see
124 my $class = ref($self);
125 my %hash = $self->hash;
126 $hash{'pkgpart'} = '';
127 $hash{'comment'} = "(CUSTOM) ". $hash{'comment'}
128 unless $hash{'comment'} =~ /^\(CUSTOM\) /;
129 #new FS::part_pkg ( \%hash ); # ?
130 new $class ( \%hash ); # ?
133 =item insert [ , OPTION => VALUE ... ]
135 Adds this package definition to the database. If there is an error,
136 returns the error, otherwise returns false.
138 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
139 I<custnum_ref> and I<options>.
141 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
142 values, appropriate FS::pkg_svc records will be inserted.
144 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
145 FS::pkg_svc record will be updated.
147 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
148 record itself), the object will be updated to point to this package definition.
150 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
151 the scalar will be updated with the custnum value from the cust_pkg record.
153 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
154 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
155 records will be inserted.
157 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
158 records will be inserted.
165 warn "FS::part_pkg::insert called on $self with options ".
166 join(', ', map "$_=>$options{$_}", keys %options)
169 local $SIG{HUP} = 'IGNORE';
170 local $SIG{INT} = 'IGNORE';
171 local $SIG{QUIT} = 'IGNORE';
172 local $SIG{TERM} = 'IGNORE';
173 local $SIG{TSTP} = 'IGNORE';
174 local $SIG{PIPE} = 'IGNORE';
176 my $oldAutoCommit = $FS::UID::AutoCommit;
177 local $FS::UID::AutoCommit = 0;
180 warn " inserting part_pkg record" if $DEBUG;
181 my $error = $self->SUPER::insert( $options{options} );
183 $dbh->rollback if $oldAutoCommit;
187 my $conf = new FS::Conf;
188 if ( $conf->exists('agent_defaultpkg') ) {
189 warn " agent_defaultpkg set; allowing all agents to purchase package"
191 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
192 my $type_pkgs = new FS::type_pkgs({
193 'typenum' => $agent_type->typenum,
194 'pkgpart' => $self->pkgpart,
196 my $error = $type_pkgs->insert;
198 $dbh->rollback if $oldAutoCommit;
204 warn " inserting part_pkg_taxoverride records" if $DEBUG;
205 my %overrides = %{ $options{'tax_overrides'} || {} };
206 foreach my $usage_class ( keys %overrides ) {
207 my @overrides = (grep "$_", split (',', $overrides{$usage_class}) );
208 my $error = $self->process_m2m (
209 'link_table' => 'part_pkg_taxoverride',
210 'target_table' => 'tax_class',
211 'hashref' => { 'usage_class' => $usage_class },
212 'params' => \@overrides,
215 $dbh->rollback if $oldAutoCommit;
220 warn " inserting pkg_svc records" if $DEBUG;
221 my $pkg_svc = $options{'pkg_svc'} || {};
222 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
223 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
225 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
229 my $pkg_svc = new FS::pkg_svc( {
230 'pkgpart' => $self->pkgpart,
231 'svcpart' => $part_svc->svcpart,
232 'quantity' => $quantity,
233 'primary_svc' => $primary_svc,
235 my $error = $pkg_svc->insert;
237 $dbh->rollback if $oldAutoCommit;
242 if ( $options{'cust_pkg'} ) {
243 warn " updating cust_pkg record " if $DEBUG;
245 ref($options{'cust_pkg'})
246 ? $options{'cust_pkg'}
247 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
248 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
249 if $options{'custnum_ref'};
250 my %hash = $old_cust_pkg->hash;
251 $hash{'pkgpart'} = $self->pkgpart,
252 my $new_cust_pkg = new FS::cust_pkg \%hash;
253 local($FS::cust_pkg::disable_agentcheck) = 1;
254 my $error = $new_cust_pkg->replace($old_cust_pkg);
256 $dbh->rollback if $oldAutoCommit;
257 return "Error modifying cust_pkg record: $error";
261 warn " commiting transaction" if $DEBUG;
262 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
269 Currently unimplemented.
274 return "Can't (yet?) delete package definitions.";
275 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
278 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
280 Replaces OLD_RECORD with this one in the database. If there is an error,
281 returns the error, otherwise returns false.
283 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
285 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
286 values, the appropriate FS::pkg_svc records will be replaced.
288 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
289 FS::pkg_svc record will be updated.
291 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
299 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
304 ( ref($_[0]) eq 'HASH' )
308 $options->{options} = {} unless defined($options->{options});
310 warn "FS::part_pkg::replace called on $new to replace $old with options".
311 join(', ', map "$_ => ". $options->{$_}, keys %$options)
314 local $SIG{HUP} = 'IGNORE';
315 local $SIG{INT} = 'IGNORE';
316 local $SIG{QUIT} = 'IGNORE';
317 local $SIG{TERM} = 'IGNORE';
318 local $SIG{TSTP} = 'IGNORE';
319 local $SIG{PIPE} = 'IGNORE';
321 my $oldAutoCommit = $FS::UID::AutoCommit;
322 local $FS::UID::AutoCommit = 0;
325 #plandata shit stays in replace for upgrades until after 2.0 (or edit
327 warn " saving legacy plandata" if $DEBUG;
328 my $plandata = $new->get('plandata');
329 $new->set('plandata', '');
331 warn " deleting old part_pkg_option records" if $DEBUG;
332 foreach my $part_pkg_option ( $old->part_pkg_option ) {
333 my $error = $part_pkg_option->delete;
335 $dbh->rollback if $oldAutoCommit;
340 warn " replacing part_pkg record" if $DEBUG;
341 my $error = $new->SUPER::replace($old, $options->{options} );
343 $dbh->rollback if $oldAutoCommit;
347 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
348 foreach my $part_pkg_option (
349 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
350 return "illegal plandata: $plandata";
352 new FS::part_pkg_option {
353 'pkgpart' => $new->pkgpart,
358 split("\n", $plandata)
360 my $error = $part_pkg_option->insert;
362 $dbh->rollback if $oldAutoCommit;
367 warn " replacing pkg_svc records" if $DEBUG;
368 my $pkg_svc = $options->{'pkg_svc'} || {};
369 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
370 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
372 ( defined($options->{'primary_svc'})
373 && $options->{'primary_svc'} == $part_svc->svcpart
379 my $old_pkg_svc = qsearchs('pkg_svc', {
380 'pkgpart' => $old->pkgpart,
381 'svcpart' => $part_svc->svcpart,
383 my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
384 my $old_primary_svc =
385 ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
386 ? $old_pkg_svc->primary_svc
388 next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
390 my $new_pkg_svc = new FS::pkg_svc( {
391 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
392 'pkgpart' => $new->pkgpart,
393 'svcpart' => $part_svc->svcpart,
394 'quantity' => $quantity,
395 'primary_svc' => $primary_svc,
397 my $error = $old_pkg_svc
398 ? $new_pkg_svc->replace($old_pkg_svc)
399 : $new_pkg_svc->insert;
401 $dbh->rollback if $oldAutoCommit;
406 warn " commiting transaction" if $DEBUG;
407 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
413 Checks all fields to make sure this is a valid package definition. If
414 there is an error, returns the error, otherwise returns false. Called by the
415 insert and replace methods.
421 warn "FS::part_pkg::check called on $self" if $DEBUG;
423 for (qw(setup recur plandata)) {
424 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
425 return "Use of $_ field is deprecated; set a plan and options: ".
427 if length($self->get($_));
431 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
432 my $error = $self->ut_number('freq');
433 return $error if $error;
435 $self->freq =~ /^(\d+[hdw]?)$/
436 or return "Illegal or empty freq: ". $self->freq;
440 my @null_agentnum_right = ( 'Edit global package definitions' );
441 push @null_agentnum_right, 'One-time charge'
442 if $self->freq =~ /^0/;
443 push @null_agentnum_right, 'Customize customer package'
444 if $self->disabled eq 'Y'; #good enough
446 my $error = $self->ut_numbern('pkgpart')
447 || $self->ut_text('pkg')
448 || $self->ut_text('comment')
449 || $self->ut_textn('promo_code')
450 || $self->ut_alphan('plan')
451 || $self->ut_enum('setuptax', [ '', 'Y' ] )
452 || $self->ut_enum('recurtax', [ '', 'Y' ] )
453 || $self->ut_textn('taxclass')
454 || $self->ut_enum('disabled', [ '', 'Y' ] )
455 #|| $self->ut_moneyn('setup_cost')
456 #|| $self->ut_moneyn('recur_cost')
457 || $self->ut_floatn('setup_cost')
458 || $self->ut_floatn('recur_cost')
459 || $self->ut_floatn('pay_weight')
460 || $self->ut_floatn('credit_weight')
461 || $self->ut_numbern('taxproductnum')
462 || $self->ut_foreign_keyn('taxproductnum',
463 'part_pkg_taxproduct',
467 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
468 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
470 || $self->SUPER::check
472 return $error if $error;
474 if ( $self->classnum !~ /^$/ ) {
475 my $error = $self->ut_foreign_key('classnum', 'pkg_class', 'classnum');
476 return $error if $error;
481 return 'Unknown plan '. $self->plan
482 unless exists($plans{$self->plan});
484 my $conf = new FS::Conf;
485 return 'Taxclass is required'
486 if ! $self->taxclass && $conf->exists('require_taxclasses');
493 Returns an (internal) string representing this package. Currently,
494 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
495 future, omitting pkgpart.
502 #$self->pkg. ' - '. $self->comment;
503 #$self->pkg. ' ('. $self->comment. ')';
504 $self->pkgpart. ': '. $self->pkg. ' - '. $self->comment;
509 Returns the package class, as an FS::pkg_class object, or the empty string
510 if there is no package class.
516 if ( $self->classnum ) {
517 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
525 Returns the package category name, or the empty string if there is no package
532 my $pkg_class = $self->pkg_class;
534 ? $pkg_class->categoryname
540 Returns the package class name, or the empty string if there is no package
547 my $pkg_class = $self->pkg_class;
549 ? $pkg_class->classname
555 Returns the associated agent for this event, if any, as an FS::agent object.
561 qsearchs('agent', { 'agentnum' => $self->agentnum } );
564 =item pkg_svc [ HASHREF | OPTION => VALUE ]
566 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
567 definition (with non-zero quantity).
569 One option is available, I<disable_linked>. If set true it will return the
570 services for this package definition alone, omitting services from any add-on
577 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
584 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
590 # #sort { $b->primary cmp $a->primary }
591 # grep { $_->quantity }
592 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
594 my $opt = ref($_[0]) ? $_[0] : { @_ };
595 my %pkg_svc = map { $_->svcpart => $_ }
596 grep { $_->quantity }
597 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
599 unless ( $opt->{disable_linked} ) {
600 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
601 my @pkg_svc = grep { $_->quantity }
602 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
603 foreach my $pkg_svc ( @pkg_svc ) {
604 if ( $pkg_svc{$pkg_svc->svcpart} ) {
605 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
606 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
608 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
618 =item svcpart [ SVCDB ]
620 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
621 associated with this package definition (see L<FS::pkg_svc>). Returns
622 false if there not a primary service definition or exactly one service
623 definition with quantity 1, or if SVCDB is specified and does not match the
624 svcdb of the service definition. SVCDB can be specified as a scalar table
625 name, such as 'svc_acct', or as an arrayref of possible table names.
630 my $pkg_svc = shift->_primary_pkg_svc(@_);
631 $pkg_svc ? $pkg_svc->svcpart : '';
634 =item part_svc [ SVCDB ]
636 Like the B<svcpart> method, but returns the FS::part_svc object (see
642 my $pkg_svc = shift->_primary_pkg_svc(@_);
643 $pkg_svc ? $pkg_svc->part_svc : '';
646 sub _primary_pkg_svc {
649 my $svcdb = scalar(@_) ? shift : [];
650 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
651 my %svcdb = map { $_=>1 } @$svcdb;
654 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
657 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
658 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
660 return '' if scalar(@pkg_svc) != 1;
664 =item svcpart_unique_svcdb SVCDB
666 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
667 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
668 false if there not a primary service definition for SVCDB or there are multiple
669 service definitions for SVCDB.
673 sub svcpart_unique_svcdb {
674 my( $self, $svcdb ) = @_;
675 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
676 return '' if scalar(@svcdb_pkg_svc) != 1;
677 $svcdb_pkg_svc[0]->svcpart;
682 Returns a list of the acceptable payment types for this package. Eventually
683 this should come out of a database table and be editable, but currently has the
684 following logic instead:
686 If the package is free, the single item B<BILL> is
687 returned, otherwise, the single item B<CARD> is returned.
689 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
695 if ( $self->is_free ) {
704 Returns true if this package is free.
710 unless ( $self->plan ) {
711 $self->setup =~ /^\s*0+(\.0*)?\s*$/
712 && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
713 } elsif ( $self->can('is_free_options') ) {
714 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
715 map { $self->option($_) }
716 $self->is_free_options;
718 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
719 "provides neither is_free_options nor is_free method; returning false";
726 #method, class method or sub? #my $self = shift;
728 tie my %freq, 'Tie::IxHash',
729 '0' => '(no recurring fee)',
732 '2d' => 'every two days',
733 '3d' => 'every three days',
735 '2w' => 'biweekly (every 2 weeks)',
737 '45d' => 'every 45 days',
738 '2' => 'bimonthly (every 2 months)',
739 '3' => 'quarterly (every 3 months)',
740 '4' => 'every 4 months',
741 '137d' => 'every 4 1/2 months (137 days)',
742 '6' => 'semiannually (every 6 months)',
744 '13' => 'every 13 months (annually +1 month)',
745 '24' => 'biannually (every 2 years)',
746 '36' => 'triannually (every 3 years)',
747 '48' => '(every 4 years)',
748 '60' => '(every 5 years)',
749 '120' => '(every 10 years)',
758 Returns an english representation of the I<freq> field, such as "monthly",
759 "weekly", "semi-annually", etc.
765 my $freq = $self->freq;
767 #my $freqs_href = $self->freqs_href;
768 my $freqs_href = freqs_href();
770 if ( exists($freqs_href->{$freq}) ) {
771 $freqs_href->{$freq};
773 my $interval = 'month';
774 if ( $freq =~ /^(\d+)([hdw])$/ ) {
775 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
776 $interval = $interval{$2};
781 "every $freq ${interval}s";
786 =item add_freq TIMESTAMP
788 Adds the frequency of this package to the provided timestamp and returns
789 the resulting timestamp, or -1 if the frequency of this package could not be
790 parsed (shouldn't happen).
795 my( $self, $date ) = @_;
796 my $freq = $self->freq;
798 #change this bit to use Date::Manip? CAREFUL with timezones (see
799 # mailing list archive)
800 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
802 if ( $self->freq =~ /^\d+$/ ) {
804 until ( $mon < 12 ) { $mon -= 12; $year++; }
805 } elsif ( $self->freq =~ /^(\d+)w$/ ) {
808 } elsif ( $self->freq =~ /^(\d+)d$/ ) {
811 } elsif ( $self->freq =~ /^(\d+)h$/ ) {
818 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
823 For backwards compatibility, returns the plandata field as well as all options
824 from FS::part_pkg_option.
830 carp "plandata is deprecated";
832 $self->SUPER::plandata(@_);
834 my $plandata = $self->get('plandata');
835 my %options = $self->options;
836 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
841 =item part_pkg_option
843 Returns all options as FS::part_pkg_option objects (see
844 L<FS::part_pkg_option>).
848 sub part_pkg_option {
850 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
855 Returns a list of option names and values suitable for assigning to a hash.
861 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
864 =item option OPTIONNAME
866 Returns the option value for the given name, or the empty string.
871 my( $self, $opt, $ornull ) = @_;
872 my $part_pkg_option =
873 qsearchs('part_pkg_option', {
874 pkgpart => $self->pkgpart,
877 return $part_pkg_option->optionvalue if $part_pkg_option;
878 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
879 split("\n", $self->get('plandata') );
880 return $plandata{$opt} if exists $plandata{$opt};
881 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
882 "not found in options or plandata!\n"
887 =item bill_part_pkg_link
889 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
893 sub bill_part_pkg_link {
894 shift->_part_pkg_link('bill', @_);
897 =item svc_part_pkg_link
899 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
903 sub svc_part_pkg_link {
904 shift->_part_pkg_link('svc', @_);
908 my( $self, $type ) = @_;
909 qsearch('part_pkg_link', { 'src_pkgpart' => $self->pkgpart,
910 'link_type' => $type,
915 sub self_and_bill_linked {
916 shift->_self_and_linked('bill', @_);
919 sub _self_and_linked {
920 my( $self, $type ) = @_;
923 map { $_->dst_pkg->_self_and_linked($type) }
924 $self->_part_pkg_link($type)
928 =item part_pkg_taxoverride [ CLASS ]
930 Returns all associated FS::part_pkg_taxoverride objects (see
931 L<FS::part_pkg_taxoverride>). Limits the returned set to those
932 of class CLASS if defined. Class may be one of 'setup', 'recur',
933 the empty string (default), or a usage class number (see L<FS::usage_class>).
934 When a class is specified, the empty string class (default) is returned
935 if no more specific values exist.
939 sub part_pkg_taxoverride {
943 my $hashref = { 'pkgpart' => $self->pkgpart };
944 $hashref->{'usage_class'} = $class if defined($class);
945 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
947 unless ( scalar(@overrides) || !defined($class) || !$class ){
948 $hashref->{'usage_class'} = '';
949 @overrides = qsearch('part_pkg_taxoverride', $hashref );
957 Returns true if this package has any taxproduct associated with it.
964 $self->taxproductnum ||
965 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
966 keys %{ {$self->options} }
972 =item taxproduct [ CLASS ]
974 Returns the associated tax product for this package definition (see
975 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
976 the usage classnum (see L<FS::usage_class>). Returns the default
977 tax product for this record if the more specific CLASS value does
986 my $part_pkg_taxproduct;
988 my $taxproductnum = $self->taxproductnum;
990 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
991 $taxproductnum = $class_taxproductnum
992 if $class_taxproductnum
995 $part_pkg_taxproduct =
996 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
998 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
999 $taxproductnum = $self->taxproductnum;
1000 $part_pkg_taxproduct =
1001 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1004 $part_pkg_taxproduct;
1007 =item taxproduct_description [ CLASS ]
1009 Returns the description of the associated tax product for this package
1010 definition (see L<FS::part_pkg_taxproduct>).
1014 sub taxproduct_description {
1016 my $part_pkg_taxproduct = $self->taxproduct(@_);
1017 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1020 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1022 Returns the package to taxrate m2m records for this package in the location
1023 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1024 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1025 (see L<FS::usage_class>).
1029 sub _expand_cch_taxproductnum {
1032 my $part_pkg_taxproduct = $self->taxproduct($class);
1034 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1035 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1038 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1039 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1040 OR taxproduct = '$a:$b:$c:'
1041 OR taxproduct = '$a:$b:".":$d'
1042 OR taxproduct = '$a:$b:".":' )";
1043 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1044 'hashref' => { 'data_vendor'=>'cch' },
1045 'extra_sql' => $extra_sql,
1050 sub part_pkg_taxrate {
1052 my ($data_vendor, $geocode, $class) = @_;
1055 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1056 dbh->quote($data_vendor);
1058 # CCH oddness in m2m
1059 $extra_sql .= ' AND ('.
1060 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1064 # much more CCH oddness in m2m -- this is kludgy
1065 my @tpnums = $self->_expand_cch_taxproductnum($class);
1066 if (scalar(@tpnums)) {
1067 $extra_sql .= ' AND ('.
1068 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1071 $extra_sql .= ' AND ( 0 = 1 )';
1074 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1075 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1076 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1078 # should qsearch preface columns with the table to facilitate joins?
1079 qsearch( { 'table' => 'part_pkg_taxrate',
1080 'select' => $select,
1081 'hashref' => { # 'data_vendor' => $data_vendor,
1082 # 'taxproductnum' => $self->taxproductnum,
1084 'addl_from' => $addl_from,
1085 'extra_sql' => $extra_sql,
1086 'order_by' => $order_by,
1092 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1093 PLAN is the object's I<plan> field. There should be better docs
1094 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1100 my $plan = $self->plan;
1102 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1106 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1107 my $class = ref($self). "::$plan";
1108 warn "reblessing $self into $class" if $DEBUG;
1111 bless($self, $class) unless $@;
1115 #fallbacks that eval the setup and recur fields, for backwards compat
1119 warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1120 $self->_calc_eval('setup', @_);
1125 warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1126 $self->_calc_eval('recur', @_);
1129 use vars qw( $sdate @details );
1131 #my( $self, $field, $cust_pkg ) = @_;
1132 my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1134 *details = $detailsref;
1135 $self->$field() =~ /^(.*)$/
1136 or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1137 $self->$field(). "\n";
1139 return 0 if $prog =~ /^\s*$/;
1140 my $value = eval $prog;
1145 #fallback that return 0 for old legacy packages with no plan
1147 sub calc_remain { 0; }
1148 sub calc_cancel { 0; }
1149 sub calc_units { 0; }
1151 #fallback for everything except bulk.pm
1152 sub hide_svc_detail { 0; }
1154 =item format OPTION DATA
1156 Returns data formatted according to the function 'format' described
1157 in the plan info. Returns DATA if no such function exists.
1162 my ($self, $option, $data) = (shift, shift, shift);
1163 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1164 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1170 =item parse OPTION DATA
1172 Returns data parsed according to the function 'parse' described
1173 in the plan info. Returns DATA if no such function exists.
1178 my ($self, $option, $data) = (shift, shift, shift);
1179 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1180 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1190 =head1 CLASS METHODS
1198 # Used by FS::Upgrade to migrate to a new database.
1200 sub _upgrade_data { # class method
1201 my($class, %opts) = @_;
1203 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1205 my @part_pkg = qsearch({
1206 'table' => 'part_pkg',
1207 'extra_sql' => "WHERE ". join(' OR ',
1208 ( map "($_ IS NOT NULL AND $_ != '' )",
1209 qw( plandata setup recur ) ),
1210 'plan IS NULL', "plan = '' ",
1214 foreach my $part_pkg (@part_pkg) {
1216 unless ( $part_pkg->plan ) {
1218 $part_pkg->plan('flat');
1220 if ( $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1222 my $opt = new FS::part_pkg_option {
1223 'pkgpart' => $part_pkg->pkgpart,
1224 'optionname' => 'setup_fee',
1225 'optionvalue' => $1,
1227 my $error = $opt->insert;
1228 die $error if $error;
1230 $part_pkg->setup('');
1233 die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1234 $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1237 if ( $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1239 my $opt = new FS::part_pkg_option {
1240 'pkgpart' => $part_pkg->pkgpart,
1241 'optionname' => 'recur_fee',
1242 'optionvalue' => $1,
1244 my $error = $opt->insert;
1245 die $error if $error;
1247 $part_pkg->recur('');
1250 die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1251 $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1256 $part_pkg->replace; #this should take care of plandata, right?
1262 =item curuser_pkgs_sql
1264 Returns an SQL fragment for searching for packages the current user can
1265 use, either via part_pkg.agentnum directly, or via agent type (see
1270 sub curuser_pkgs_sql {
1273 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1277 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1279 Returns an SQL fragment for searching for packages the provided agent or agents
1280 can use, either via part_pkg.agentnum directly, or via agent type (see
1285 sub agent_pkgs_sql {
1286 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1287 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1289 $class->_pkgs_sql(@agentnums); #is this why
1294 my( $class, @agentnums ) = @_;
1295 my $agentnums = join(',', @agentnums);
1299 agentnum IS NOT NULL
1301 0 < ( SELECT COUNT(*)
1303 LEFT JOIN agent_type USING ( typenum )
1304 LEFT JOIN agent AS typeagent USING ( typenum )
1305 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1306 AND typeagent.agentnum IN ($agentnums)
1323 #false laziness w/part_export & cdr
1325 foreach my $INC ( @INC ) {
1326 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1327 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1328 warn "attempting to load plan info from $file\n" if $DEBUG;
1329 $file =~ /\/(\w+)\.pm$/ or do {
1330 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1334 my $info = eval "use FS::part_pkg::$mod; ".
1335 "\\%FS::part_pkg::$mod\::info;";
1337 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1340 unless ( keys %$info ) {
1341 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1344 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1345 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1346 warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1349 $info{$mod} = $info;
1353 tie %plans, 'Tie::IxHash',
1354 map { $_ => $info{$_} }
1355 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1365 =head1 NEW PLAN CLASSES
1367 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1368 found in eg/plan_template.pm. Until then, it is suggested that you use the
1369 other modules in FS/FS/part_pkg/ as a guide.
1373 The delete method is unimplemented.
1375 setup and recur semantics are not yet defined (and are implemented in
1376 FS::cust_bill. hmm.). now they're deprecated and need to go.
1380 part_pkg_taxrate is Pg specific
1384 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1385 schema.html from the base documentation.