4 use vars qw( @ISA %plans $DEBUG $setup_hack $skip_pkg_svc_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_taxrate;
20 use FS::part_pkg_taxoverride;
21 use FS::part_pkg_taxproduct;
22 use FS::part_pkg_link;
23 use FS::part_pkg_discount;
25 @ISA = qw( FS::m2m_Common FS::option_Common );
28 $skip_pkg_svc_hack = 0;
32 FS::part_pkg - Object methods for part_pkg objects
38 $record = new FS::part_pkg \%hash
39 $record = new FS::part_pkg { 'column' => 'value' };
41 $custom_record = $template_record->clone;
43 $error = $record->insert;
45 $error = $new_record->replace($old_record);
47 $error = $record->delete;
49 $error = $record->check;
51 @pkg_svc = $record->pkg_svc;
53 $svcnum = $record->svcpart;
54 $svcnum = $record->svcpart( 'svc_acct' );
58 An FS::part_pkg object represents a package definition. FS::part_pkg
59 inherits from FS::Record. The following fields are currently supported:
63 =item pkgpart - primary key (assigned automatically for new package definitions)
65 =item pkg - Text name of this package definition (customer-viewable)
67 =item comment - Text name of this package definition (non-customer-viewable)
69 =item classnum - Optional package class (see L<FS::pkg_class>)
71 =item promo_code - Promotional code
73 =item setup - Setup fee expression (deprecated)
75 =item freq - Frequency of recurring fee
77 =item recur - Recurring fee expression (deprecated)
79 =item setuptax - Setup fee tax exempt flag, empty or `Y'
81 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
83 =item taxclass - Tax class
85 =item plan - Price plan
87 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
89 =item disabled - Disabled flag, empty or `Y'
91 =item custom - Custom flag, empty or `Y'
93 =item setup_cost - for cost tracking
95 =item recur_cost - for cost tracking
97 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
99 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
101 =item agentnum - Optional agentnum (see L<FS::agent>)
103 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
113 Creates a new package definition. To add the package definition to
114 the database, see L<"insert">.
118 sub table { 'part_pkg'; }
122 An alternate constructor. Creates a new package definition by duplicating
123 an existing definition. A new pkgpart is assigned and the custom flag is
124 set to Y. To add the package definition to the database, see L<"insert">.
130 my $class = ref($self);
131 my %hash = $self->hash;
132 $hash{'pkgpart'} = '';
133 $hash{'custom'} = 'Y';
134 #new FS::part_pkg ( \%hash ); # ?
135 new $class ( \%hash ); # ?
138 =item insert [ , OPTION => VALUE ... ]
140 Adds this package definition to the database. If there is an error,
141 returns the error, otherwise returns false.
143 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
144 I<custnum_ref> and I<options>.
146 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
147 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
148 be set to a hashref of svcparts and flag values ('Y' or '') to set the
149 'hidden' field in these records.
151 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
152 FS::pkg_svc record will be updated.
154 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
155 record itself), the object will be updated to point to this package definition.
157 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
158 the scalar will be updated with the custnum value from the cust_pkg record.
160 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
161 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
162 records will be inserted.
164 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
165 records will be inserted.
172 warn "FS::part_pkg::insert called on $self with options ".
173 join(', ', map "$_=>$options{$_}", keys %options)
176 local $SIG{HUP} = 'IGNORE';
177 local $SIG{INT} = 'IGNORE';
178 local $SIG{QUIT} = 'IGNORE';
179 local $SIG{TERM} = 'IGNORE';
180 local $SIG{TSTP} = 'IGNORE';
181 local $SIG{PIPE} = 'IGNORE';
183 my $oldAutoCommit = $FS::UID::AutoCommit;
184 local $FS::UID::AutoCommit = 0;
187 warn " inserting part_pkg record" if $DEBUG;
188 my $error = $self->SUPER::insert( $options{options} );
190 $dbh->rollback if $oldAutoCommit;
194 my $conf = new FS::Conf;
195 if ( $conf->exists('agent_defaultpkg') ) {
196 warn " agent_defaultpkg set; allowing all agents to purchase package"
198 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
199 my $type_pkgs = new FS::type_pkgs({
200 'typenum' => $agent_type->typenum,
201 'pkgpart' => $self->pkgpart,
203 my $error = $type_pkgs->insert;
205 $dbh->rollback if $oldAutoCommit;
211 warn " inserting part_pkg_taxoverride records" if $DEBUG;
212 my %overrides = %{ $options{'tax_overrides'} || {} };
213 foreach my $usage_class ( keys %overrides ) {
215 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
216 ? $overrides{$usage_class}
218 my @overrides = (grep "$_", split(',', $override) );
219 my $error = $self->process_m2m (
220 'link_table' => 'part_pkg_taxoverride',
221 'target_table' => 'tax_class',
222 'hashref' => { 'usage_class' => $usage_class },
223 'params' => \@overrides,
226 $dbh->rollback if $oldAutoCommit;
231 unless ( $skip_pkg_svc_hack ) {
233 warn " inserting pkg_svc records" if $DEBUG;
234 my $pkg_svc = $options{'pkg_svc'} || {};
235 my $hidden_svc = $options{'hidden_svc'} || {};
236 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
237 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
239 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
243 my $pkg_svc = new FS::pkg_svc( {
244 'pkgpart' => $self->pkgpart,
245 'svcpart' => $part_svc->svcpart,
246 'quantity' => $quantity,
247 'primary_svc' => $primary_svc,
248 'hidden' => $hidden_svc->{$part_svc->svcpart},
250 my $error = $pkg_svc->insert;
252 $dbh->rollback if $oldAutoCommit;
259 if ( $options{'cust_pkg'} ) {
260 warn " updating cust_pkg record " if $DEBUG;
262 ref($options{'cust_pkg'})
263 ? $options{'cust_pkg'}
264 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
265 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
266 if $options{'custnum_ref'};
267 my %hash = $old_cust_pkg->hash;
268 $hash{'pkgpart'} = $self->pkgpart,
269 my $new_cust_pkg = new FS::cust_pkg \%hash;
270 local($FS::cust_pkg::disable_agentcheck) = 1;
271 my $error = $new_cust_pkg->replace($old_cust_pkg);
273 $dbh->rollback if $oldAutoCommit;
274 return "Error modifying cust_pkg record: $error";
278 warn " commiting transaction" if $DEBUG;
279 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
286 Currently unimplemented.
291 return "Can't (yet?) delete package definitions.";
292 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
295 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
297 Replaces OLD_RECORD with this one in the database. If there is an error,
298 returns the error, otherwise returns false.
300 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
303 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
304 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
305 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
306 'hidden' field in these records.
308 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
309 FS::pkg_svc record will be updated.
311 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
319 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
324 ( ref($_[0]) eq 'HASH' )
328 $options->{options} = {} unless defined($options->{options});
330 warn "FS::part_pkg::replace called on $new to replace $old with options".
331 join(', ', map "$_ => ". $options->{$_}, keys %$options)
334 local $SIG{HUP} = 'IGNORE';
335 local $SIG{INT} = 'IGNORE';
336 local $SIG{QUIT} = 'IGNORE';
337 local $SIG{TERM} = 'IGNORE';
338 local $SIG{TSTP} = 'IGNORE';
339 local $SIG{PIPE} = 'IGNORE';
341 my $oldAutoCommit = $FS::UID::AutoCommit;
342 local $FS::UID::AutoCommit = 0;
345 #plandata shit stays in replace for upgrades until after 2.0 (or edit
347 warn " saving legacy plandata" if $DEBUG;
348 my $plandata = $new->get('plandata');
349 $new->set('plandata', '');
351 warn " deleting old part_pkg_option records" if $DEBUG;
352 foreach my $part_pkg_option ( $old->part_pkg_option ) {
353 my $error = $part_pkg_option->delete;
355 $dbh->rollback if $oldAutoCommit;
360 warn " replacing part_pkg record" if $DEBUG;
361 my $error = $new->SUPER::replace($old, $options->{options} );
363 $dbh->rollback if $oldAutoCommit;
367 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
368 foreach my $part_pkg_option (
369 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
370 return "illegal plandata: $plandata";
372 new FS::part_pkg_option {
373 'pkgpart' => $new->pkgpart,
378 split("\n", $plandata)
380 my $error = $part_pkg_option->insert;
382 $dbh->rollback if $oldAutoCommit;
387 warn " replacing pkg_svc records" if $DEBUG;
388 my $pkg_svc = $options->{'pkg_svc'} || {};
389 my $hidden_svc = $options->{'hidden_svc'} || {};
390 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
391 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
392 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
394 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
395 && $options->{'primary_svc'} == $part_svc->svcpart
400 my $old_pkg_svc = qsearchs('pkg_svc', {
401 'pkgpart' => $old->pkgpart,
402 'svcpart' => $part_svc->svcpart,
405 my $old_quantity = 0;
406 my $old_primary_svc = '';
408 if ( $old_pkg_svc ) {
409 $old_quantity = $old_pkg_svc->quantity;
410 $old_primary_svc = $old_pkg_svc->primary_svc
411 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
412 $old_hidden = $old_pkg_svc->hidden;
415 next unless $old_quantity != $quantity ||
416 $old_primary_svc ne $primary_svc ||
417 $old_hidden ne $hidden;
419 my $new_pkg_svc = new FS::pkg_svc( {
420 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
421 'pkgpart' => $new->pkgpart,
422 'svcpart' => $part_svc->svcpart,
423 'quantity' => $quantity,
424 'primary_svc' => $primary_svc,
427 my $error = $old_pkg_svc
428 ? $new_pkg_svc->replace($old_pkg_svc)
429 : $new_pkg_svc->insert;
431 $dbh->rollback if $oldAutoCommit;
436 warn " commiting transaction" if $DEBUG;
437 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
443 Checks all fields to make sure this is a valid package definition. If
444 there is an error, returns the error, otherwise returns false. Called by the
445 insert and replace methods.
451 warn "FS::part_pkg::check called on $self" if $DEBUG;
453 for (qw(setup recur plandata)) {
454 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
455 return "Use of $_ field is deprecated; set a plan and options: ".
457 if length($self->get($_));
461 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
462 my $error = $self->ut_number('freq');
463 return $error if $error;
465 $self->freq =~ /^(\d+[hdw]?)$/
466 or return "Illegal or empty freq: ". $self->freq;
470 my @null_agentnum_right = ( 'Edit global package definitions' );
471 push @null_agentnum_right, 'One-time charge'
472 if $self->freq =~ /^0/;
473 push @null_agentnum_right, 'Customize customer package'
474 if $self->disabled eq 'Y'; #good enough
476 my $error = $self->ut_numbern('pkgpart')
477 || $self->ut_text('pkg')
478 || $self->ut_text('comment')
479 || $self->ut_textn('promo_code')
480 || $self->ut_alphan('plan')
481 || $self->ut_enum('setuptax', [ '', 'Y' ] )
482 || $self->ut_enum('recurtax', [ '', 'Y' ] )
483 || $self->ut_textn('taxclass')
484 || $self->ut_enum('disabled', [ '', 'Y' ] )
485 || $self->ut_enum('custom', [ '', 'Y' ] )
486 || $self->ut_enum('no_auto', [ '', 'Y' ])
487 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
488 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
489 #|| $self->ut_moneyn('setup_cost')
490 #|| $self->ut_moneyn('recur_cost')
491 || $self->ut_floatn('setup_cost')
492 || $self->ut_floatn('recur_cost')
493 || $self->ut_floatn('pay_weight')
494 || $self->ut_floatn('credit_weight')
495 || $self->ut_numbern('taxproductnum')
496 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
497 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
498 || $self->ut_foreign_keyn('taxproductnum',
499 'part_pkg_taxproduct',
503 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
504 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
506 || $self->ut_numbern('fcc_ds0s')
507 || $self->SUPER::check
509 return $error if $error;
511 return 'Unknown plan '. $self->plan
512 unless exists($plans{$self->plan});
514 my $conf = new FS::Conf;
515 return 'Taxclass is required'
516 if ! $self->taxclass && $conf->exists('require_taxclasses');
521 =item pkg_comment [ OPTION => VALUE... ]
523 Returns an (internal) string representing this package. Currently,
524 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
525 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
528 If the option nopkgpart is true then the "pkgpart: ' is omitted.
536 #$self->pkg. ' - '. $self->comment;
537 #$self->pkg. ' ('. $self->comment. ')';
538 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
539 $pre. $self->pkg. ' - '. $self->custom_comment;
542 sub price_info { # safety, in case a part_pkg hasn't defined price_info
548 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment . ' ' . $self->price_info;
553 Returns the package class, as an FS::pkg_class object, or the empty string
554 if there is no package class.
560 if ( $self->classnum ) {
561 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
567 =item addon_pkg_class
569 Returns the add-on package class, as an FS::pkg_class object, or the empty
570 string if there is no add-on package class.
574 sub addon_pkg_class {
576 if ( $self->addon_classnum ) {
577 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
585 Returns the package category name, or the empty string if there is no package
592 my $pkg_class = $self->pkg_class;
594 ? $pkg_class->categoryname
600 Returns the package class name, or the empty string if there is no package
607 my $pkg_class = $self->pkg_class;
609 ? $pkg_class->classname
613 =item addon_classname
615 Returns the add-on package class name, or the empty string if there is no
616 add-on package class.
620 sub addon_classname {
622 my $pkg_class = $self->addon_pkg_class;
624 ? $pkg_class->classname
630 Returns the associated agent for this event, if any, as an FS::agent object.
636 qsearchs('agent', { 'agentnum' => $self->agentnum } );
639 =item pkg_svc [ HASHREF | OPTION => VALUE ]
641 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
642 definition (with non-zero quantity).
644 One option is available, I<disable_linked>. If set true it will return the
645 services for this package definition alone, omitting services from any add-on
652 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
659 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
665 # #sort { $b->primary cmp $a->primary }
666 # grep { $_->quantity }
667 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
669 my $opt = ref($_[0]) ? $_[0] : { @_ };
670 my %pkg_svc = map { $_->svcpart => $_ }
671 grep { $_->quantity }
672 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
674 unless ( $opt->{disable_linked} ) {
675 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
676 my @pkg_svc = grep { $_->quantity }
677 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
678 foreach my $pkg_svc ( @pkg_svc ) {
679 if ( $pkg_svc{$pkg_svc->svcpart} ) {
680 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
681 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
683 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
693 =item svcpart [ SVCDB ]
695 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
696 associated with this package definition (see L<FS::pkg_svc>). Returns
697 false if there not a primary service definition or exactly one service
698 definition with quantity 1, or if SVCDB is specified and does not match the
699 svcdb of the service definition. SVCDB can be specified as a scalar table
700 name, such as 'svc_acct', or as an arrayref of possible table names.
705 my $pkg_svc = shift->_primary_pkg_svc(@_);
706 $pkg_svc ? $pkg_svc->svcpart : '';
709 =item part_svc [ SVCDB ]
711 Like the B<svcpart> method, but returns the FS::part_svc object (see
717 my $pkg_svc = shift->_primary_pkg_svc(@_);
718 $pkg_svc ? $pkg_svc->part_svc : '';
721 sub _primary_pkg_svc {
724 my $svcdb = scalar(@_) ? shift : [];
725 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
726 my %svcdb = map { $_=>1 } @$svcdb;
729 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
732 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
733 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
735 return '' if scalar(@pkg_svc) != 1;
739 =item svcpart_unique_svcdb SVCDB
741 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
742 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
743 false if there not a primary service definition for SVCDB or there are multiple
744 service definitions for SVCDB.
748 sub svcpart_unique_svcdb {
749 my( $self, $svcdb ) = @_;
750 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
751 return '' if scalar(@svcdb_pkg_svc) != 1;
752 $svcdb_pkg_svc[0]->svcpart;
757 Returns a list of the acceptable payment types for this package. Eventually
758 this should come out of a database table and be editable, but currently has the
759 following logic instead:
761 If the package is free, the single item B<BILL> is
762 returned, otherwise, the single item B<CARD> is returned.
764 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
770 if ( $self->is_free ) {
779 Returns true if this package is free.
785 if ( $self->can('is_free_options') ) {
786 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
787 map { $self->option($_) }
788 $self->is_free_options;
790 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
791 "provides neither is_free_options nor is_free method; returning false";
796 sub can_discount { 0; }
798 sub can_start_date { 1; }
801 # moved to FS::Misc to make this accessible to other packages
803 FS::Misc::pkg_freqs();
808 Returns an english representation of the I<freq> field, such as "monthly",
809 "weekly", "semi-annually", etc.
815 my $freq = $self->freq;
817 #my $freqs_href = $self->freqs_href;
818 my $freqs_href = freqs_href();
820 if ( exists($freqs_href->{$freq}) ) {
821 $freqs_href->{$freq};
823 my $interval = 'month';
824 if ( $freq =~ /^(\d+)([hdw])$/ ) {
825 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
826 $interval = $interval{$2};
831 "every $freq ${interval}s";
836 =item add_freq TIMESTAMP [ FREQ ]
838 Adds a billing period of some frequency to the provided timestamp and
839 returns the resulting timestamp, or -1 if the frequency could not be
840 parsed (shouldn't happen). By default, the frequency of this package
841 will be used; to override this, pass a different frequency as a second
847 my( $self, $date, $freq ) = @_;
848 $freq = $self->freq unless $freq;
850 #change this bit to use Date::Manip? CAREFUL with timezones (see
851 # mailing list archive)
852 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
854 if ( $freq =~ /^\d+$/ ) {
856 until ( $mon < 12 ) { $mon -= 12; $year++; }
857 } elsif ( $freq =~ /^(\d+)w$/ ) {
860 } elsif ( $freq =~ /^(\d+)d$/ ) {
863 } elsif ( $freq =~ /^(\d+)h$/ ) {
870 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
875 For backwards compatibility, returns the plandata field as well as all options
876 from FS::part_pkg_option.
882 carp "plandata is deprecated";
884 $self->SUPER::plandata(@_);
886 my $plandata = $self->get('plandata');
887 my %options = $self->options;
888 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
893 =item part_pkg_option
895 Returns all options as FS::part_pkg_option objects (see
896 L<FS::part_pkg_option>).
900 sub part_pkg_option {
902 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
907 Returns a list of option names and values suitable for assigning to a hash.
913 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
916 =item option OPTIONNAME [ QUIET ]
918 Returns the option value for the given name, or the empty string. If a true
919 value is passed as the second argument, warnings about missing the option
925 my( $self, $opt, $ornull ) = @_;
926 my $part_pkg_option =
927 qsearchs('part_pkg_option', {
928 pkgpart => $self->pkgpart,
931 return $part_pkg_option->optionvalue if $part_pkg_option;
932 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
933 split("\n", $self->get('plandata') );
934 return $plandata{$opt} if exists $plandata{$opt};
935 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
936 "not found in options or plandata!\n"
941 =item bill_part_pkg_link
943 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
947 sub bill_part_pkg_link {
948 shift->_part_pkg_link('bill', @_);
951 =item svc_part_pkg_link
953 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
957 sub svc_part_pkg_link {
958 shift->_part_pkg_link('svc', @_);
962 my( $self, $type ) = @_;
963 qsearch({ table => 'part_pkg_link',
964 hashref => { 'src_pkgpart' => $self->pkgpart,
965 'link_type' => $type,
966 #protection against infinite recursive links
967 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
969 order_by => "ORDER BY hidden",
973 sub self_and_bill_linked {
974 shift->_self_and_linked('bill', @_);
977 sub self_and_svc_linked {
978 shift->_self_and_linked('svc', @_);
981 sub _self_and_linked {
982 my( $self, $type, $hidden ) = @_;
986 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
987 $self->_part_pkg_link($type) ) )
989 $_->hidden($hidden) if $hidden;
996 =item part_pkg_taxoverride [ CLASS ]
998 Returns all associated FS::part_pkg_taxoverride objects (see
999 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1000 of class CLASS if defined. Class may be one of 'setup', 'recur',
1001 the empty string (default), or a usage class number (see L<FS::usage_class>).
1002 When a class is specified, the empty string class (default) is returned
1003 if no more specific values exist.
1007 sub part_pkg_taxoverride {
1011 my $hashref = { 'pkgpart' => $self->pkgpart };
1012 $hashref->{'usage_class'} = $class if defined($class);
1013 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1015 unless ( scalar(@overrides) || !defined($class) || !$class ){
1016 $hashref->{'usage_class'} = '';
1017 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1023 =item has_taxproduct
1025 Returns true if this package has any taxproduct associated with it.
1029 sub has_taxproduct {
1032 $self->taxproductnum ||
1033 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1034 keys %{ {$self->options} }
1040 =item taxproduct [ CLASS ]
1042 Returns the associated tax product for this package definition (see
1043 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1044 the usage classnum (see L<FS::usage_class>). Returns the default
1045 tax product for this record if the more specific CLASS value does
1054 my $part_pkg_taxproduct;
1056 my $taxproductnum = $self->taxproductnum;
1058 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1059 $taxproductnum = $class_taxproductnum
1060 if $class_taxproductnum
1063 $part_pkg_taxproduct =
1064 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1066 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1067 $taxproductnum = $self->taxproductnum;
1068 $part_pkg_taxproduct =
1069 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1072 $part_pkg_taxproduct;
1075 =item taxproduct_description [ CLASS ]
1077 Returns the description of the associated tax product for this package
1078 definition (see L<FS::part_pkg_taxproduct>).
1082 sub taxproduct_description {
1084 my $part_pkg_taxproduct = $self->taxproduct(@_);
1085 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1088 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1090 Returns the package to taxrate m2m records for this package in the location
1091 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1092 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1093 (see L<FS::usage_class>).
1097 sub _expand_cch_taxproductnum {
1100 my $part_pkg_taxproduct = $self->taxproduct($class);
1102 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1103 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1106 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1107 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1108 OR taxproduct = '$a:$b:$c:'
1109 OR taxproduct = '$a:$b:".":$d'
1110 OR taxproduct = '$a:$b:".":' )";
1111 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1112 'hashref' => { 'data_vendor'=>'cch' },
1113 'extra_sql' => $extra_sql,
1118 sub part_pkg_taxrate {
1120 my ($data_vendor, $geocode, $class) = @_;
1123 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1124 dbh->quote($data_vendor);
1126 # CCH oddness in m2m
1127 $extra_sql .= ' AND ('.
1128 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1132 # much more CCH oddness in m2m -- this is kludgy
1133 my @tpnums = $self->_expand_cch_taxproductnum($class);
1134 if (scalar(@tpnums)) {
1135 $extra_sql .= ' AND ('.
1136 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1139 $extra_sql .= ' AND ( 0 = 1 )';
1142 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1143 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1144 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1146 # should qsearch preface columns with the table to facilitate joins?
1147 qsearch( { 'table' => 'part_pkg_taxrate',
1148 'select' => $select,
1149 'hashref' => { # 'data_vendor' => $data_vendor,
1150 # 'taxproductnum' => $self->taxproductnum,
1152 'addl_from' => $addl_from,
1153 'extra_sql' => $extra_sql,
1154 'order_by' => $order_by,
1158 =item part_pkg_discount
1160 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1165 sub part_pkg_discount {
1167 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1172 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1173 PLAN is the object's I<plan> field. There should be better docs
1174 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1180 my $plan = $self->plan;
1182 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1186 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1187 my $class = ref($self). "::$plan";
1188 warn "reblessing $self into $class" if $DEBUG;
1191 bless($self, $class) unless $@;
1196 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1197 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1199 #fallback that return 0 for old legacy packages with no plan
1200 sub calc_remain { 0; }
1201 sub calc_cancel { 0; }
1202 sub calc_units { 0; }
1204 #fallback for everything except bulk.pm
1205 sub hide_svc_detail { 0; }
1207 =item recur_cost_permonth CUST_PKG
1209 recur_cost divided by freq (only supported for monthly and longer frequencies)
1213 sub recur_cost_permonth {
1214 my($self, $cust_pkg) = @_;
1215 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1216 sprintf('%.2f', $self->recur_cost / $self->freq );
1219 =item format OPTION DATA
1221 Returns data formatted according to the function 'format' described
1222 in the plan info. Returns DATA if no such function exists.
1227 my ($self, $option, $data) = (shift, shift, shift);
1228 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1229 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1235 =item parse OPTION DATA
1237 Returns data parsed according to the function 'parse' described
1238 in the plan info. Returns DATA if no such function exists.
1243 my ($self, $option, $data) = (shift, shift, shift);
1244 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1245 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1255 =head1 CLASS METHODS
1263 # Used by FS::Upgrade to migrate to a new database.
1265 sub _upgrade_data { # class method
1266 my($class, %opts) = @_;
1268 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1270 my @part_pkg = qsearch({
1271 'table' => 'part_pkg',
1272 'extra_sql' => "WHERE ". join(' OR ',
1273 ( map "($_ IS NOT NULL AND $_ != '' )",
1274 qw( plandata setup recur ) ),
1275 'plan IS NULL', "plan = '' ",
1279 foreach my $part_pkg (@part_pkg) {
1281 unless ( $part_pkg->plan ) {
1282 $part_pkg->plan('flat');
1285 if ( length($part_pkg->option('setup_fee')) == 0
1286 && $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1288 my $opt = new FS::part_pkg_option {
1289 'pkgpart' => $part_pkg->pkgpart,
1290 'optionname' => 'setup_fee',
1291 'optionvalue' => $1,
1293 my $error = $opt->insert;
1294 die $error if $error;
1298 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1299 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1301 $part_pkg->setup('');
1303 if ( length($part_pkg->option('recur_fee')) == 0
1304 && $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1306 my $opt = new FS::part_pkg_option {
1307 'pkgpart' => $part_pkg->pkgpart,
1308 'optionname' => 'recur_fee',
1309 'optionvalue' => $1,
1311 my $error = $opt->insert;
1312 die $error if $error;
1316 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1317 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1319 $part_pkg->recur('');
1321 $part_pkg->replace; #this should take care of plandata, right?
1325 # now upgrade to the explicit custom flag
1327 @part_pkg = qsearch({
1328 'table' => 'part_pkg',
1329 'hashref' => { disabled => 'Y', custom => '' },
1330 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1333 foreach my $part_pkg (@part_pkg) {
1334 my $new = new FS::part_pkg { $part_pkg->hash };
1336 my $comment = $part_pkg->comment;
1337 $comment =~ s/^\(CUSTOM\) //;
1338 $comment = '(none)' unless $comment =~ /\S/;
1339 $new->comment($comment);
1341 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1342 my $primary = $part_pkg->svcpart;
1343 my $options = { $part_pkg->options };
1345 my $error = $new->replace( $part_pkg,
1346 'pkg_svc' => $pkg_svc,
1347 'primary_svc' => $primary,
1348 'options' => $options,
1350 die $error if $error;
1353 my @part_pkg_option = qsearch('part_pkg_option',
1354 { 'optionname' => 'unused_credit',
1357 foreach my $old_opt (@part_pkg_option) {
1358 my $pkgpart = $old_opt->pkgpart;
1359 my $error = $old_opt->delete;
1360 die $error if $error;
1362 foreach (qw(unused_credit_cancel unused_credit_change)) {
1363 my $new_opt = new FS::part_pkg_option {
1364 'pkgpart' => $pkgpart,
1368 $error = $new_opt->insert;
1369 die $error if $error;
1374 =item curuser_pkgs_sql
1376 Returns an SQL fragment for searching for packages the current user can
1377 use, either via part_pkg.agentnum directly, or via agent type (see
1382 sub curuser_pkgs_sql {
1385 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1389 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1391 Returns an SQL fragment for searching for packages the provided agent or agents
1392 can use, either via part_pkg.agentnum directly, or via agent type (see
1397 sub agent_pkgs_sql {
1398 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1399 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1401 $class->_pkgs_sql(@agentnums); #is this why
1406 my( $class, @agentnums ) = @_;
1407 my $agentnums = join(',', @agentnums);
1411 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1412 OR ( agentnum IS NULL
1413 AND EXISTS ( SELECT 1
1415 LEFT JOIN agent_type USING ( typenum )
1416 LEFT JOIN agent AS typeagent USING ( typenum )
1417 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1418 AND typeagent.agentnum IN ($agentnums)
1436 #false laziness w/part_export & cdr
1438 foreach my $INC ( @INC ) {
1439 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1440 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1441 warn "attempting to load plan info from $file\n" if $DEBUG;
1442 $file =~ /\/(\w+)\.pm$/ or do {
1443 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1447 my $info = eval "use FS::part_pkg::$mod; ".
1448 "\\%FS::part_pkg::$mod\::info;";
1450 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1453 unless ( keys %$info ) {
1454 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1457 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1458 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1459 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1462 $info{$mod} = $info;
1463 $info->{'weight'} ||= 0; # quiet warnings
1467 # copy one level deep to allow replacement of fields and fieldorder
1468 tie %plans, 'Tie::IxHash',
1469 map { my %infohash = %{ $info{$_} };
1471 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1474 # inheritance of plan options
1475 foreach my $name (keys(%info)) {
1476 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1477 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1478 delete $plans{$name};
1481 my $parents = $info{$name}->{'inherit_fields'} || [];
1482 my (%fields, %field_exists, @fieldorder);
1483 foreach my $parent ($name, @$parents) {
1484 %fields = ( # avoid replacing existing fields
1485 %{ $info{$parent}->{'fields'} || {} },
1488 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1490 next if $field_exists{$_};
1491 $field_exists{$_} = 1;
1492 # allow inheritors to remove inherited fields from the fieldorder
1493 push @fieldorder, $_ if !exists($fields{$_}->{'disabled'});
1496 $plans{$name}->{'fields'} = \%fields;
1497 $plans{$name}->{'fieldorder'} = \@fieldorder;
1507 =head1 NEW PLAN CLASSES
1509 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1510 found in eg/plan_template.pm. Until then, it is suggested that you use the
1511 other modules in FS/FS/part_pkg/ as a guide.
1515 The delete method is unimplemented.
1517 setup and recur semantics are not yet defined (and are implemented in
1518 FS::cust_bill. hmm.). now they're deprecated and need to go.
1522 part_pkg_taxrate is Pg specific
1524 replace should be smarter about managing the related tables (options, pkg_svc)
1528 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1529 schema.html from the base documentation.