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;
24 @ISA = qw( FS::m2m_Common FS::option_Common );
27 $skip_pkg_svc_hack = 0;
31 FS::part_pkg - Object methods for part_pkg objects
37 $record = new FS::part_pkg \%hash
38 $record = new FS::part_pkg { 'column' => 'value' };
40 $custom_record = $template_record->clone;
42 $error = $record->insert;
44 $error = $new_record->replace($old_record);
46 $error = $record->delete;
48 $error = $record->check;
50 @pkg_svc = $record->pkg_svc;
52 $svcnum = $record->svcpart;
53 $svcnum = $record->svcpart( 'svc_acct' );
57 An FS::part_pkg object represents a package definition. FS::part_pkg
58 inherits from FS::Record. The following fields are currently supported:
62 =item pkgpart - primary key (assigned automatically for new package definitions)
64 =item pkg - Text name of this package definition (customer-viewable)
66 =item comment - Text name of this package definition (non-customer-viewable)
68 =item classnum - Optional package class (see L<FS::pkg_class>)
70 =item promo_code - Promotional code
72 =item setup - Setup fee expression (deprecated)
74 =item freq - Frequency of recurring fee
76 =item recur - Recurring fee expression (deprecated)
78 =item setuptax - Setup fee tax exempt flag, empty or `Y'
80 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
82 =item taxclass - Tax class
84 =item plan - Price plan
86 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
88 =item disabled - Disabled flag, empty or `Y'
90 =item custom - Custom flag, empty or `Y'
92 =item setup_cost - for cost tracking
94 =item recur_cost - for cost tracking
96 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
98 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
100 =item agentnum - Optional agentnum (see L<FS::agent>)
102 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
112 Creates a new package definition. To add the package definition to
113 the database, see L<"insert">.
117 sub table { 'part_pkg'; }
121 An alternate constructor. Creates a new package definition by duplicating
122 an existing definition. A new pkgpart is assigned and the custom flag is
123 set to Y. To add the package definition to the database, see L<"insert">.
129 my $class = ref($self);
130 my %hash = $self->hash;
131 $hash{'pkgpart'} = '';
132 $hash{'custom'} = 'Y';
133 #new FS::part_pkg ( \%hash ); # ?
134 new $class ( \%hash ); # ?
137 =item insert [ , OPTION => VALUE ... ]
139 Adds this package definition to the database. If there is an error,
140 returns the error, otherwise returns false.
142 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
143 I<custnum_ref> and I<options>.
145 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
146 values, appropriate FS::pkg_svc records will be inserted.
148 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
149 FS::pkg_svc record will be updated.
151 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
152 record itself), the object will be updated to point to this package definition.
154 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
155 the scalar will be updated with the custnum value from the cust_pkg record.
157 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
158 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
159 records will be inserted.
161 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
162 records will be inserted.
169 warn "FS::part_pkg::insert called on $self with options ".
170 join(', ', map "$_=>$options{$_}", keys %options)
173 local $SIG{HUP} = 'IGNORE';
174 local $SIG{INT} = 'IGNORE';
175 local $SIG{QUIT} = 'IGNORE';
176 local $SIG{TERM} = 'IGNORE';
177 local $SIG{TSTP} = 'IGNORE';
178 local $SIG{PIPE} = 'IGNORE';
180 my $oldAutoCommit = $FS::UID::AutoCommit;
181 local $FS::UID::AutoCommit = 0;
184 warn " inserting part_pkg record" if $DEBUG;
185 my $error = $self->SUPER::insert( $options{options} );
187 $dbh->rollback if $oldAutoCommit;
191 my $conf = new FS::Conf;
192 if ( $conf->exists('agent_defaultpkg') ) {
193 warn " agent_defaultpkg set; allowing all agents to purchase package"
195 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
196 my $type_pkgs = new FS::type_pkgs({
197 'typenum' => $agent_type->typenum,
198 'pkgpart' => $self->pkgpart,
200 my $error = $type_pkgs->insert;
202 $dbh->rollback if $oldAutoCommit;
208 warn " inserting part_pkg_taxoverride records" if $DEBUG;
209 my %overrides = %{ $options{'tax_overrides'} || {} };
210 foreach my $usage_class ( keys %overrides ) {
212 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
213 ? $overrides{$usage_class}
215 my @overrides = (grep "$_", split(',', $override) );
216 my $error = $self->process_m2m (
217 'link_table' => 'part_pkg_taxoverride',
218 'target_table' => 'tax_class',
219 'hashref' => { 'usage_class' => $usage_class },
220 'params' => \@overrides,
223 $dbh->rollback if $oldAutoCommit;
228 unless ( $skip_pkg_svc_hack ) {
230 warn " inserting pkg_svc records" if $DEBUG;
231 my $pkg_svc = $options{'pkg_svc'} || {};
232 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
233 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
235 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
239 my $pkg_svc = new FS::pkg_svc( {
240 'pkgpart' => $self->pkgpart,
241 'svcpart' => $part_svc->svcpart,
242 'quantity' => $quantity,
243 'primary_svc' => $primary_svc,
245 my $error = $pkg_svc->insert;
247 $dbh->rollback if $oldAutoCommit;
254 if ( $options{'cust_pkg'} ) {
255 warn " updating cust_pkg record " if $DEBUG;
257 ref($options{'cust_pkg'})
258 ? $options{'cust_pkg'}
259 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
260 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
261 if $options{'custnum_ref'};
262 my %hash = $old_cust_pkg->hash;
263 $hash{'pkgpart'} = $self->pkgpart,
264 my $new_cust_pkg = new FS::cust_pkg \%hash;
265 local($FS::cust_pkg::disable_agentcheck) = 1;
266 my $error = $new_cust_pkg->replace($old_cust_pkg);
268 $dbh->rollback if $oldAutoCommit;
269 return "Error modifying cust_pkg record: $error";
273 warn " commiting transaction" if $DEBUG;
274 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
281 Currently unimplemented.
286 return "Can't (yet?) delete package definitions.";
287 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
290 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
292 Replaces OLD_RECORD with this one in the database. If there is an error,
293 returns the error, otherwise returns false.
295 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
297 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
298 values, the appropriate FS::pkg_svc records will be replaced.
300 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
301 FS::pkg_svc record will be updated.
303 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
311 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
316 ( ref($_[0]) eq 'HASH' )
320 $options->{options} = {} unless defined($options->{options});
322 warn "FS::part_pkg::replace called on $new to replace $old with options".
323 join(', ', map "$_ => ". $options->{$_}, keys %$options)
326 local $SIG{HUP} = 'IGNORE';
327 local $SIG{INT} = 'IGNORE';
328 local $SIG{QUIT} = 'IGNORE';
329 local $SIG{TERM} = 'IGNORE';
330 local $SIG{TSTP} = 'IGNORE';
331 local $SIG{PIPE} = 'IGNORE';
333 my $oldAutoCommit = $FS::UID::AutoCommit;
334 local $FS::UID::AutoCommit = 0;
337 #plandata shit stays in replace for upgrades until after 2.0 (or edit
339 warn " saving legacy plandata" if $DEBUG;
340 my $plandata = $new->get('plandata');
341 $new->set('plandata', '');
343 warn " deleting old part_pkg_option records" if $DEBUG;
344 foreach my $part_pkg_option ( $old->part_pkg_option ) {
345 my $error = $part_pkg_option->delete;
347 $dbh->rollback if $oldAutoCommit;
352 warn " replacing part_pkg record" if $DEBUG;
353 my $error = $new->SUPER::replace($old, $options->{options} );
355 $dbh->rollback if $oldAutoCommit;
359 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
360 foreach my $part_pkg_option (
361 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
362 return "illegal plandata: $plandata";
364 new FS::part_pkg_option {
365 'pkgpart' => $new->pkgpart,
370 split("\n", $plandata)
372 my $error = $part_pkg_option->insert;
374 $dbh->rollback if $oldAutoCommit;
379 warn " replacing pkg_svc records" if $DEBUG;
380 my $pkg_svc = $options->{'pkg_svc'} || {};
381 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
382 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
384 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
385 && $options->{'primary_svc'} == $part_svc->svcpart
391 my $old_pkg_svc = qsearchs('pkg_svc', {
392 'pkgpart' => $old->pkgpart,
393 'svcpart' => $part_svc->svcpart,
395 my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
396 my $old_primary_svc =
397 ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
398 ? $old_pkg_svc->primary_svc
400 next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
402 my $new_pkg_svc = new FS::pkg_svc( {
403 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
404 'pkgpart' => $new->pkgpart,
405 'svcpart' => $part_svc->svcpart,
406 'quantity' => $quantity,
407 'primary_svc' => $primary_svc,
409 my $error = $old_pkg_svc
410 ? $new_pkg_svc->replace($old_pkg_svc)
411 : $new_pkg_svc->insert;
413 $dbh->rollback if $oldAutoCommit;
418 warn " commiting transaction" if $DEBUG;
419 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
425 Checks all fields to make sure this is a valid package definition. If
426 there is an error, returns the error, otherwise returns false. Called by the
427 insert and replace methods.
433 warn "FS::part_pkg::check called on $self" if $DEBUG;
435 for (qw(setup recur plandata)) {
436 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
437 return "Use of $_ field is deprecated; set a plan and options: ".
439 if length($self->get($_));
443 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
444 my $error = $self->ut_number('freq');
445 return $error if $error;
447 $self->freq =~ /^(\d+[hdw]?)$/
448 or return "Illegal or empty freq: ". $self->freq;
452 my @null_agentnum_right = ( 'Edit global package definitions' );
453 push @null_agentnum_right, 'One-time charge'
454 if $self->freq =~ /^0/;
455 push @null_agentnum_right, 'Customize customer package'
456 if $self->disabled eq 'Y'; #good enough
458 my $error = $self->ut_numbern('pkgpart')
459 || $self->ut_text('pkg')
460 || $self->ut_text('comment')
461 || $self->ut_textn('promo_code')
462 || $self->ut_alphan('plan')
463 || $self->ut_enum('setuptax', [ '', 'Y' ] )
464 || $self->ut_enum('recurtax', [ '', 'Y' ] )
465 || $self->ut_textn('taxclass')
466 || $self->ut_enum('disabled', [ '', 'Y' ] )
467 || $self->ut_enum('custom', [ '', 'Y' ] )
468 || $self->ut_enum('no_auto', [ '', 'Y' ])
469 #|| $self->ut_moneyn('setup_cost')
470 #|| $self->ut_moneyn('recur_cost')
471 || $self->ut_floatn('setup_cost')
472 || $self->ut_floatn('recur_cost')
473 || $self->ut_floatn('pay_weight')
474 || $self->ut_floatn('credit_weight')
475 || $self->ut_numbern('taxproductnum')
476 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
477 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
478 || $self->ut_foreign_keyn('taxproductnum',
479 'part_pkg_taxproduct',
483 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
484 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
486 || $self->ut_numbern('fcc_ds0s')
487 || $self->SUPER::check
489 return $error if $error;
491 return 'Unknown plan '. $self->plan
492 unless exists($plans{$self->plan});
494 my $conf = new FS::Conf;
495 return 'Taxclass is required'
496 if ! $self->taxclass && $conf->exists('require_taxclasses');
501 =item pkg_comment [ OPTION => VALUE... ]
503 Returns an (internal) string representing this package. Currently,
504 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
505 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
508 If the option nopkgpart is true then the "pkgpart: ' is omitted.
516 #$self->pkg. ' - '. $self->comment;
517 #$self->pkg. ' ('. $self->comment. ')';
518 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
519 $pre. $self->pkg. ' - '. $self->custom_comment;
524 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment;
529 Returns the package class, as an FS::pkg_class object, or the empty string
530 if there is no package class.
536 if ( $self->classnum ) {
537 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
543 =item addon_pkg_class
545 Returns the add-on package class, as an FS::pkg_class object, or the empty
546 string if there is no add-on package class.
550 sub addon_pkg_class {
552 if ( $self->addon_classnum ) {
553 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
561 Returns the package category name, or the empty string if there is no package
568 my $pkg_class = $self->pkg_class;
570 ? $pkg_class->categoryname
576 Returns the package class name, or the empty string if there is no package
583 my $pkg_class = $self->pkg_class;
585 ? $pkg_class->classname
589 =item addon_classname
591 Returns the add-on package class name, or the empty string if there is no
592 add-on package class.
596 sub addon_classname {
598 my $pkg_class = $self->addon_pkg_class;
600 ? $pkg_class->classname
606 Returns the associated agent for this event, if any, as an FS::agent object.
612 qsearchs('agent', { 'agentnum' => $self->agentnum } );
615 =item pkg_svc [ HASHREF | OPTION => VALUE ]
617 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
618 definition (with non-zero quantity).
620 One option is available, I<disable_linked>. If set true it will return the
621 services for this package definition alone, omitting services from any add-on
628 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
635 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
641 # #sort { $b->primary cmp $a->primary }
642 # grep { $_->quantity }
643 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
645 my $opt = ref($_[0]) ? $_[0] : { @_ };
646 my %pkg_svc = map { $_->svcpart => $_ }
647 grep { $_->quantity }
648 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
650 unless ( $opt->{disable_linked} ) {
651 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
652 my @pkg_svc = grep { $_->quantity }
653 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
654 foreach my $pkg_svc ( @pkg_svc ) {
655 if ( $pkg_svc{$pkg_svc->svcpart} ) {
656 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
657 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
659 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
669 =item svcpart [ SVCDB ]
671 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
672 associated with this package definition (see L<FS::pkg_svc>). Returns
673 false if there not a primary service definition or exactly one service
674 definition with quantity 1, or if SVCDB is specified and does not match the
675 svcdb of the service definition. SVCDB can be specified as a scalar table
676 name, such as 'svc_acct', or as an arrayref of possible table names.
681 my $pkg_svc = shift->_primary_pkg_svc(@_);
682 $pkg_svc ? $pkg_svc->svcpart : '';
685 =item part_svc [ SVCDB ]
687 Like the B<svcpart> method, but returns the FS::part_svc object (see
693 my $pkg_svc = shift->_primary_pkg_svc(@_);
694 $pkg_svc ? $pkg_svc->part_svc : '';
697 sub _primary_pkg_svc {
700 my $svcdb = scalar(@_) ? shift : [];
701 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
702 my %svcdb = map { $_=>1 } @$svcdb;
705 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
708 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
709 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
711 return '' if scalar(@pkg_svc) != 1;
715 =item svcpart_unique_svcdb SVCDB
717 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
718 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
719 false if there not a primary service definition for SVCDB or there are multiple
720 service definitions for SVCDB.
724 sub svcpart_unique_svcdb {
725 my( $self, $svcdb ) = @_;
726 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
727 return '' if scalar(@svcdb_pkg_svc) != 1;
728 $svcdb_pkg_svc[0]->svcpart;
733 Returns a list of the acceptable payment types for this package. Eventually
734 this should come out of a database table and be editable, but currently has the
735 following logic instead:
737 If the package is free, the single item B<BILL> is
738 returned, otherwise, the single item B<CARD> is returned.
740 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
746 if ( $self->is_free ) {
755 Returns true if this package is free.
761 unless ( $self->plan ) {
762 $self->setup =~ /^\s*0+(\.0*)?\s*$/
763 && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
764 } elsif ( $self->can('is_free_options') ) {
765 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
766 map { $self->option($_) }
767 $self->is_free_options;
769 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
770 "provides neither is_free_options nor is_free method; returning false";
775 sub can_discount { 0; }
778 # moved to FS::Misc to make this accessible to other packages
780 FS::Misc::pkg_freqs();
785 Returns an english representation of the I<freq> field, such as "monthly",
786 "weekly", "semi-annually", etc.
792 my $freq = $self->freq;
794 #my $freqs_href = $self->freqs_href;
795 my $freqs_href = freqs_href();
797 if ( exists($freqs_href->{$freq}) ) {
798 $freqs_href->{$freq};
800 my $interval = 'month';
801 if ( $freq =~ /^(\d+)([hdw])$/ ) {
802 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
803 $interval = $interval{$2};
808 "every $freq ${interval}s";
813 =item add_freq TIMESTAMP [ FREQ ]
815 Adds a billing period of some frequency to the provided timestamp and
816 returns the resulting timestamp, or -1 if the frequency could not be
817 parsed (shouldn't happen). By default, the frequency of this package
818 will be used; to override this, pass a different frequency as a second
824 my( $self, $date, $freq ) = @_;
825 $freq = $self->freq if !defined($freq);
827 #change this bit to use Date::Manip? CAREFUL with timezones (see
828 # mailing list archive)
829 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
831 if ( $freq =~ /^\d+$/ ) {
833 until ( $mon < 12 ) { $mon -= 12; $year++; }
834 } elsif ( $freq =~ /^(\d+)w$/ ) {
837 } elsif ( $freq =~ /^(\d+)d$/ ) {
840 } elsif ( $freq =~ /^(\d+)h$/ ) {
847 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
852 For backwards compatibility, returns the plandata field as well as all options
853 from FS::part_pkg_option.
859 carp "plandata is deprecated";
861 $self->SUPER::plandata(@_);
863 my $plandata = $self->get('plandata');
864 my %options = $self->options;
865 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
870 =item part_pkg_option
872 Returns all options as FS::part_pkg_option objects (see
873 L<FS::part_pkg_option>).
877 sub part_pkg_option {
879 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
884 Returns a list of option names and values suitable for assigning to a hash.
890 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
893 =item option OPTIONNAME [ QUIET ]
895 Returns the option value for the given name, or the empty string. If a true
896 value is passed as the second argument, warnings about missing the option
902 my( $self, $opt, $ornull ) = @_;
903 my $part_pkg_option =
904 qsearchs('part_pkg_option', {
905 pkgpart => $self->pkgpart,
908 return $part_pkg_option->optionvalue if $part_pkg_option;
909 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
910 split("\n", $self->get('plandata') );
911 return $plandata{$opt} if exists $plandata{$opt};
912 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
913 "not found in options or plandata!\n"
918 =item bill_part_pkg_link
920 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
924 sub bill_part_pkg_link {
925 shift->_part_pkg_link('bill', @_);
928 =item svc_part_pkg_link
930 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
934 sub svc_part_pkg_link {
935 shift->_part_pkg_link('svc', @_);
939 my( $self, $type ) = @_;
940 qsearch({ table => 'part_pkg_link',
941 hashref => { 'src_pkgpart' => $self->pkgpart,
942 'link_type' => $type,
944 order_by => "ORDER BY hidden",
948 sub self_and_bill_linked {
949 shift->_self_and_linked('bill', @_);
952 sub _self_and_linked {
953 my( $self, $type, $hidden ) = @_;
957 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
958 $self->_part_pkg_link($type) ) )
960 $_->hidden($hidden) if $hidden;
967 =item part_pkg_taxoverride [ CLASS ]
969 Returns all associated FS::part_pkg_taxoverride objects (see
970 L<FS::part_pkg_taxoverride>). Limits the returned set to those
971 of class CLASS if defined. Class may be one of 'setup', 'recur',
972 the empty string (default), or a usage class number (see L<FS::usage_class>).
973 When a class is specified, the empty string class (default) is returned
974 if no more specific values exist.
978 sub part_pkg_taxoverride {
982 my $hashref = { 'pkgpart' => $self->pkgpart };
983 $hashref->{'usage_class'} = $class if defined($class);
984 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
986 unless ( scalar(@overrides) || !defined($class) || !$class ){
987 $hashref->{'usage_class'} = '';
988 @overrides = qsearch('part_pkg_taxoverride', $hashref );
996 Returns true if this package has any taxproduct associated with it.
1000 sub has_taxproduct {
1003 $self->taxproductnum ||
1004 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1005 keys %{ {$self->options} }
1011 =item taxproduct [ CLASS ]
1013 Returns the associated tax product for this package definition (see
1014 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1015 the usage classnum (see L<FS::usage_class>). Returns the default
1016 tax product for this record if the more specific CLASS value does
1025 my $part_pkg_taxproduct;
1027 my $taxproductnum = $self->taxproductnum;
1029 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1030 $taxproductnum = $class_taxproductnum
1031 if $class_taxproductnum
1034 $part_pkg_taxproduct =
1035 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1037 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1038 $taxproductnum = $self->taxproductnum;
1039 $part_pkg_taxproduct =
1040 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1043 $part_pkg_taxproduct;
1046 =item taxproduct_description [ CLASS ]
1048 Returns the description of the associated tax product for this package
1049 definition (see L<FS::part_pkg_taxproduct>).
1053 sub taxproduct_description {
1055 my $part_pkg_taxproduct = $self->taxproduct(@_);
1056 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1059 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1061 Returns the package to taxrate m2m records for this package in the location
1062 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1063 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1064 (see L<FS::usage_class>).
1068 sub _expand_cch_taxproductnum {
1071 my $part_pkg_taxproduct = $self->taxproduct($class);
1073 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1074 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1077 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1078 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1079 OR taxproduct = '$a:$b:$c:'
1080 OR taxproduct = '$a:$b:".":$d'
1081 OR taxproduct = '$a:$b:".":' )";
1082 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1083 'hashref' => { 'data_vendor'=>'cch' },
1084 'extra_sql' => $extra_sql,
1089 sub part_pkg_taxrate {
1091 my ($data_vendor, $geocode, $class) = @_;
1094 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1095 dbh->quote($data_vendor);
1097 # CCH oddness in m2m
1098 $extra_sql .= ' AND ('.
1099 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1103 # much more CCH oddness in m2m -- this is kludgy
1104 my @tpnums = $self->_expand_cch_taxproductnum($class);
1105 if (scalar(@tpnums)) {
1106 $extra_sql .= ' AND ('.
1107 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1110 $extra_sql .= ' AND ( 0 = 1 )';
1113 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1114 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1115 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1117 # should qsearch preface columns with the table to facilitate joins?
1118 qsearch( { 'table' => 'part_pkg_taxrate',
1119 'select' => $select,
1120 'hashref' => { # 'data_vendor' => $data_vendor,
1121 # 'taxproductnum' => $self->taxproductnum,
1123 'addl_from' => $addl_from,
1124 'extra_sql' => $extra_sql,
1125 'order_by' => $order_by,
1131 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1132 PLAN is the object's I<plan> field. There should be better docs
1133 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1139 my $plan = $self->plan;
1141 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1145 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1146 my $class = ref($self). "::$plan";
1147 warn "reblessing $self into $class" if $DEBUG;
1150 bless($self, $class) unless $@;
1154 #fallbacks that eval the setup and recur fields, for backwards compat
1158 warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1159 $self->_calc_eval('setup', @_);
1164 warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1165 $self->_calc_eval('recur', @_);
1168 use vars qw( $sdate @details );
1170 #my( $self, $field, $cust_pkg ) = @_;
1171 my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1173 *details = $detailsref;
1174 $self->$field() =~ /^(.*)$/
1175 or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1176 $self->$field(). "\n";
1178 return 0 if $prog =~ /^\s*$/;
1179 my $value = eval $prog;
1184 #fallback that return 0 for old legacy packages with no plan
1186 sub calc_remain { 0; }
1187 sub calc_cancel { 0; }
1188 sub calc_units { 0; }
1190 #fallback for everything except bulk.pm
1191 sub hide_svc_detail { 0; }
1193 =item recur_cost_permonth CUST_PKG
1195 recur_cost divided by freq (only supported for monthly and longer frequencies)
1199 sub recur_cost_permonth {
1200 my($self, $cust_pkg) = @_;
1201 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1202 sprintf('%.2f', $self->recur_cost / $self->freq );
1205 =item format OPTION DATA
1207 Returns data formatted according to the function 'format' described
1208 in the plan info. Returns DATA if no such function exists.
1213 my ($self, $option, $data) = (shift, shift, shift);
1214 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1215 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1221 =item parse OPTION DATA
1223 Returns data parsed according to the function 'parse' described
1224 in the plan info. Returns DATA if no such function exists.
1229 my ($self, $option, $data) = (shift, shift, shift);
1230 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1231 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1241 =head1 CLASS METHODS
1249 # Used by FS::Upgrade to migrate to a new database.
1251 sub _upgrade_data { # class method
1252 my($class, %opts) = @_;
1254 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1256 my @part_pkg = qsearch({
1257 'table' => 'part_pkg',
1258 'extra_sql' => "WHERE ". join(' OR ',
1259 ( map "($_ IS NOT NULL AND $_ != '' )",
1260 qw( plandata setup recur ) ),
1261 'plan IS NULL', "plan = '' ",
1265 foreach my $part_pkg (@part_pkg) {
1267 unless ( $part_pkg->plan ) {
1268 $part_pkg->plan('flat');
1271 if ( length($part_pkg->option('setup_fee')) == 0
1272 && $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1274 my $opt = new FS::part_pkg_option {
1275 'pkgpart' => $part_pkg->pkgpart,
1276 'optionname' => 'setup_fee',
1277 'optionvalue' => $1,
1279 my $error = $opt->insert;
1280 die $error if $error;
1284 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1285 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1287 $part_pkg->setup('');
1289 if ( length($part_pkg->option('recur_fee')) == 0
1290 && $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1292 my $opt = new FS::part_pkg_option {
1293 'pkgpart' => $part_pkg->pkgpart,
1294 'optionname' => 'recur_fee',
1295 'optionvalue' => $1,
1297 my $error = $opt->insert;
1298 die $error if $error;
1302 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1303 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1305 $part_pkg->recur('');
1307 $part_pkg->replace; #this should take care of plandata, right?
1311 # now upgrade to the explicit custom flag
1313 @part_pkg = qsearch({
1314 'table' => 'part_pkg',
1315 'hashref' => { disabled => 'Y', custom => '' },
1316 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1319 foreach my $part_pkg (@part_pkg) {
1320 my $new = new FS::part_pkg { $part_pkg->hash };
1322 my $comment = $part_pkg->comment;
1323 $comment =~ s/^\(CUSTOM\) //;
1324 $comment = '(none)' unless $comment =~ /\S/;
1325 $new->comment($comment);
1327 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1328 my $primary = $part_pkg->svcpart;
1329 my $options = { $part_pkg->options };
1331 my $error = $new->replace( $part_pkg,
1332 'pkg_svc' => $pkg_svc,
1333 'primary_svc' => $primary,
1334 'options' => $options,
1336 die $error if $error;
1341 =item curuser_pkgs_sql
1343 Returns an SQL fragment for searching for packages the current user can
1344 use, either via part_pkg.agentnum directly, or via agent type (see
1349 sub curuser_pkgs_sql {
1352 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1356 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1358 Returns an SQL fragment for searching for packages the provided agent or agents
1359 can use, either via part_pkg.agentnum directly, or via agent type (see
1364 sub agent_pkgs_sql {
1365 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1366 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1368 $class->_pkgs_sql(@agentnums); #is this why
1373 my( $class, @agentnums ) = @_;
1374 my $agentnums = join(',', @agentnums);
1378 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1379 OR ( agentnum IS NULL
1380 AND EXISTS ( SELECT 1
1382 LEFT JOIN agent_type USING ( typenum )
1383 LEFT JOIN agent AS typeagent USING ( typenum )
1384 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1385 AND typeagent.agentnum IN ($agentnums)
1403 #false laziness w/part_export & cdr
1405 foreach my $INC ( @INC ) {
1406 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1407 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1408 warn "attempting to load plan info from $file\n" if $DEBUG;
1409 $file =~ /\/(\w+)\.pm$/ or do {
1410 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1414 my $info = eval "use FS::part_pkg::$mod; ".
1415 "\\%FS::part_pkg::$mod\::info;";
1417 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1420 unless ( keys %$info ) {
1421 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1424 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1425 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1426 warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1429 $info{$mod} = $info;
1433 tie %plans, 'Tie::IxHash',
1434 map { $_ => $info{$_} }
1435 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1445 =head1 NEW PLAN CLASSES
1447 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1448 found in eg/plan_template.pm. Until then, it is suggested that you use the
1449 other modules in FS/FS/part_pkg/ as a guide.
1453 The delete method is unimplemented.
1455 setup and recur semantics are not yet defined (and are implemented in
1456 FS::cust_bill. hmm.). now they're deprecated and need to go.
1460 part_pkg_taxrate is Pg specific
1462 replace should be smarter about managing the related tables (options, pkg_svc)
1466 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1467 schema.html from the base documentation.