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_taxoverride;
20 use FS::part_pkg_taxproduct;
21 use FS::part_pkg_link;
23 @ISA = qw( FS::m2m_Common FS::option_Common );
26 $skip_pkg_svc_hack = 0;
30 FS::part_pkg - Object methods for part_pkg objects
36 $record = new FS::part_pkg \%hash
37 $record = new FS::part_pkg { 'column' => 'value' };
39 $custom_record = $template_record->clone;
41 $error = $record->insert;
43 $error = $new_record->replace($old_record);
45 $error = $record->delete;
47 $error = $record->check;
49 @pkg_svc = $record->pkg_svc;
51 $svcnum = $record->svcpart;
52 $svcnum = $record->svcpart( 'svc_acct' );
56 An FS::part_pkg object represents a package definition. FS::part_pkg
57 inherits from FS::Record. The following fields are currently supported:
61 =item pkgpart - primary key (assigned automatically for new package definitions)
63 =item pkg - Text name of this package definition (customer-viewable)
65 =item comment - Text name of this package definition (non-customer-viewable)
67 =item classnum - Optional package class (see L<FS::pkg_class>)
69 =item promo_code - Promotional code
71 =item setup - Setup fee expression (deprecated)
73 =item freq - Frequency of recurring fee
75 =item recur - Recurring fee expression (deprecated)
77 =item setuptax - Setup fee tax exempt flag, empty or `Y'
79 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
81 =item taxclass - Tax class
83 =item plan - Price plan
85 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
87 =item disabled - Disabled flag, empty or `Y'
89 =item custom - Custom flag, empty or `Y'
91 =item setup_cost - for cost tracking
93 =item recur_cost - for cost tracking
95 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
97 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
99 =item agentnum - Optional agentnum (see L<FS::agent>)
101 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
111 Creates a new package definition. To add the package definition to
112 the database, see L<"insert">.
116 sub table { 'part_pkg'; }
120 An alternate constructor. Creates a new package definition by duplicating
121 an existing definition. A new pkgpart is assigned and the custom flag is
122 set to Y. To add the package definition to the database, see L<"insert">.
128 my $class = ref($self);
129 my %hash = $self->hash;
130 $hash{'pkgpart'} = '';
131 $hash{'custom'} = 'Y';
132 #new FS::part_pkg ( \%hash ); # ?
133 new $class ( \%hash ); # ?
136 =item insert [ , OPTION => VALUE ... ]
138 Adds this package definition to the database. If there is an error,
139 returns the error, otherwise returns false.
141 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
142 I<custnum_ref> and I<options>.
144 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
145 values, appropriate FS::pkg_svc records will be inserted.
147 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
148 FS::pkg_svc record will be updated.
150 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
151 record itself), the object will be updated to point to this package definition.
153 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
154 the scalar will be updated with the custnum value from the cust_pkg record.
156 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
157 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
158 records will be inserted.
160 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
161 records will be inserted.
168 warn "FS::part_pkg::insert called on $self with options ".
169 join(', ', map "$_=>$options{$_}", keys %options)
172 local $SIG{HUP} = 'IGNORE';
173 local $SIG{INT} = 'IGNORE';
174 local $SIG{QUIT} = 'IGNORE';
175 local $SIG{TERM} = 'IGNORE';
176 local $SIG{TSTP} = 'IGNORE';
177 local $SIG{PIPE} = 'IGNORE';
179 my $oldAutoCommit = $FS::UID::AutoCommit;
180 local $FS::UID::AutoCommit = 0;
183 warn " inserting part_pkg record" if $DEBUG;
184 my $error = $self->SUPER::insert( $options{options} );
186 $dbh->rollback if $oldAutoCommit;
190 my $conf = new FS::Conf;
191 if ( $conf->exists('agent_defaultpkg') ) {
192 warn " agent_defaultpkg set; allowing all agents to purchase package"
194 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
195 my $type_pkgs = new FS::type_pkgs({
196 'typenum' => $agent_type->typenum,
197 'pkgpart' => $self->pkgpart,
199 my $error = $type_pkgs->insert;
201 $dbh->rollback if $oldAutoCommit;
207 warn " inserting part_pkg_taxoverride records" if $DEBUG;
208 my %overrides = %{ $options{'tax_overrides'} || {} };
209 foreach my $usage_class ( keys %overrides ) {
211 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
212 ? $overrides{$usage_class}
214 my @overrides = (grep "$_", split(',', $override) );
215 my $error = $self->process_m2m (
216 'link_table' => 'part_pkg_taxoverride',
217 'target_table' => 'tax_class',
218 'hashref' => { 'usage_class' => $usage_class },
219 'params' => \@overrides,
222 $dbh->rollback if $oldAutoCommit;
227 unless ( $skip_pkg_svc_hack ) {
229 warn " inserting pkg_svc records" if $DEBUG;
230 my $pkg_svc = $options{'pkg_svc'} || {};
231 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
232 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
234 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
238 my $pkg_svc = new FS::pkg_svc( {
239 'pkgpart' => $self->pkgpart,
240 'svcpart' => $part_svc->svcpart,
241 'quantity' => $quantity,
242 'primary_svc' => $primary_svc,
244 my $error = $pkg_svc->insert;
246 $dbh->rollback if $oldAutoCommit;
253 if ( $options{'cust_pkg'} ) {
254 warn " updating cust_pkg record " if $DEBUG;
256 ref($options{'cust_pkg'})
257 ? $options{'cust_pkg'}
258 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
259 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
260 if $options{'custnum_ref'};
261 my %hash = $old_cust_pkg->hash;
262 $hash{'pkgpart'} = $self->pkgpart,
263 my $new_cust_pkg = new FS::cust_pkg \%hash;
264 local($FS::cust_pkg::disable_agentcheck) = 1;
265 my $error = $new_cust_pkg->replace($old_cust_pkg);
267 $dbh->rollback if $oldAutoCommit;
268 return "Error modifying cust_pkg record: $error";
272 warn " commiting transaction" if $DEBUG;
273 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
280 Currently unimplemented.
285 return "Can't (yet?) delete package definitions.";
286 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
289 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
291 Replaces OLD_RECORD with this one in the database. If there is an error,
292 returns the error, otherwise returns false.
294 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
296 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
297 values, the appropriate FS::pkg_svc records will be replaced.
299 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
300 FS::pkg_svc record will be updated.
302 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
310 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
315 ( ref($_[0]) eq 'HASH' )
319 $options->{options} = {} unless defined($options->{options});
321 warn "FS::part_pkg::replace called on $new to replace $old with options".
322 join(', ', map "$_ => ". $options->{$_}, keys %$options)
325 local $SIG{HUP} = 'IGNORE';
326 local $SIG{INT} = 'IGNORE';
327 local $SIG{QUIT} = 'IGNORE';
328 local $SIG{TERM} = 'IGNORE';
329 local $SIG{TSTP} = 'IGNORE';
330 local $SIG{PIPE} = 'IGNORE';
332 my $oldAutoCommit = $FS::UID::AutoCommit;
333 local $FS::UID::AutoCommit = 0;
336 #plandata shit stays in replace for upgrades until after 2.0 (or edit
338 warn " saving legacy plandata" if $DEBUG;
339 my $plandata = $new->get('plandata');
340 $new->set('plandata', '');
342 warn " deleting old part_pkg_option records" if $DEBUG;
343 foreach my $part_pkg_option ( $old->part_pkg_option ) {
344 my $error = $part_pkg_option->delete;
346 $dbh->rollback if $oldAutoCommit;
351 warn " replacing part_pkg record" if $DEBUG;
352 my $error = $new->SUPER::replace($old, $options->{options} );
354 $dbh->rollback if $oldAutoCommit;
358 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
359 foreach my $part_pkg_option (
360 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
361 return "illegal plandata: $plandata";
363 new FS::part_pkg_option {
364 'pkgpart' => $new->pkgpart,
369 split("\n", $plandata)
371 my $error = $part_pkg_option->insert;
373 $dbh->rollback if $oldAutoCommit;
378 warn " replacing pkg_svc records" if $DEBUG;
379 my $pkg_svc = $options->{'pkg_svc'} || {};
380 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
381 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
383 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
384 && $options->{'primary_svc'} == $part_svc->svcpart
390 my $old_pkg_svc = qsearchs('pkg_svc', {
391 'pkgpart' => $old->pkgpart,
392 'svcpart' => $part_svc->svcpart,
394 my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
395 my $old_primary_svc =
396 ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
397 ? $old_pkg_svc->primary_svc
399 next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
401 my $new_pkg_svc = new FS::pkg_svc( {
402 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
403 'pkgpart' => $new->pkgpart,
404 'svcpart' => $part_svc->svcpart,
405 'quantity' => $quantity,
406 'primary_svc' => $primary_svc,
408 my $error = $old_pkg_svc
409 ? $new_pkg_svc->replace($old_pkg_svc)
410 : $new_pkg_svc->insert;
412 $dbh->rollback if $oldAutoCommit;
417 warn " commiting transaction" if $DEBUG;
418 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
424 Checks all fields to make sure this is a valid package definition. If
425 there is an error, returns the error, otherwise returns false. Called by the
426 insert and replace methods.
432 warn "FS::part_pkg::check called on $self" if $DEBUG;
434 for (qw(setup recur plandata)) {
435 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
436 return "Use of $_ field is deprecated; set a plan and options: ".
438 if length($self->get($_));
442 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
443 my $error = $self->ut_number('freq');
444 return $error if $error;
446 $self->freq =~ /^(\d+[hdw]?)$/
447 or return "Illegal or empty freq: ". $self->freq;
451 my @null_agentnum_right = ( 'Edit global package definitions' );
452 push @null_agentnum_right, 'One-time charge'
453 if $self->freq =~ /^0/;
454 push @null_agentnum_right, 'Customize customer package'
455 if $self->disabled eq 'Y'; #good enough
457 my $error = $self->ut_numbern('pkgpart')
458 || $self->ut_text('pkg')
459 || $self->ut_text('comment')
460 || $self->ut_textn('promo_code')
461 || $self->ut_alphan('plan')
462 || $self->ut_enum('setuptax', [ '', 'Y' ] )
463 || $self->ut_enum('recurtax', [ '', 'Y' ] )
464 || $self->ut_textn('taxclass')
465 || $self->ut_enum('disabled', [ '', 'Y' ] )
466 || $self->ut_enum('custom', [ '', 'Y' ] )
467 || $self->ut_enum('no_auto', [ '', 'Y' ])
468 #|| $self->ut_moneyn('setup_cost')
469 #|| $self->ut_moneyn('recur_cost')
470 || $self->ut_floatn('setup_cost')
471 || $self->ut_floatn('recur_cost')
472 || $self->ut_floatn('pay_weight')
473 || $self->ut_floatn('credit_weight')
474 || $self->ut_numbern('taxproductnum')
475 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
476 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
477 || $self->ut_foreign_keyn('taxproductnum',
478 'part_pkg_taxproduct',
482 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
483 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
485 || $self->ut_numbern('fcc_ds0s')
486 || $self->SUPER::check
488 return $error if $error;
490 return 'Unknown plan '. $self->plan
491 unless exists($plans{$self->plan});
493 my $conf = new FS::Conf;
494 return 'Taxclass is required'
495 if ! $self->taxclass && $conf->exists('require_taxclasses');
500 =item pkg_comment [ OPTION => VALUE... ]
502 Returns an (internal) string representing this package. Currently,
503 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
504 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
507 If the option nopkgpart is true then the "pkgpart: ' is omitted.
515 #$self->pkg. ' - '. $self->comment;
516 #$self->pkg. ' ('. $self->comment. ')';
517 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
518 $pre. $self->pkg. ' - '. $self->custom_comment;
523 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment;
528 Returns the package class, as an FS::pkg_class object, or the empty string
529 if there is no package class.
535 if ( $self->classnum ) {
536 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
542 =item addon_pkg_class
544 Returns the add-on package class, as an FS::pkg_class object, or the empty
545 string if there is no add-on package class.
549 sub addon_pkg_class {
551 if ( $self->addon_classnum ) {
552 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
560 Returns the package category name, or the empty string if there is no package
567 my $pkg_class = $self->pkg_class;
569 ? $pkg_class->categoryname
575 Returns the package class name, or the empty string if there is no package
582 my $pkg_class = $self->pkg_class;
584 ? $pkg_class->classname
588 =item addon_classname
590 Returns the add-on package class name, or the empty string if there is no
591 add-on package class.
595 sub addon_classname {
597 my $pkg_class = $self->addon_pkg_class;
599 ? $pkg_class->classname
605 Returns the associated agent for this event, if any, as an FS::agent object.
611 qsearchs('agent', { 'agentnum' => $self->agentnum } );
614 =item pkg_svc [ HASHREF | OPTION => VALUE ]
616 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
617 definition (with non-zero quantity).
619 One option is available, I<disable_linked>. If set true it will return the
620 services for this package definition alone, omitting services from any add-on
627 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
634 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
640 # #sort { $b->primary cmp $a->primary }
641 # grep { $_->quantity }
642 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
644 my $opt = ref($_[0]) ? $_[0] : { @_ };
645 my %pkg_svc = map { $_->svcpart => $_ }
646 grep { $_->quantity }
647 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
649 unless ( $opt->{disable_linked} ) {
650 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
651 my @pkg_svc = grep { $_->quantity }
652 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
653 foreach my $pkg_svc ( @pkg_svc ) {
654 if ( $pkg_svc{$pkg_svc->svcpart} ) {
655 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
656 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
658 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
668 =item svcpart [ SVCDB ]
670 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
671 associated with this package definition (see L<FS::pkg_svc>). Returns
672 false if there not a primary service definition or exactly one service
673 definition with quantity 1, or if SVCDB is specified and does not match the
674 svcdb of the service definition. SVCDB can be specified as a scalar table
675 name, such as 'svc_acct', or as an arrayref of possible table names.
680 my $pkg_svc = shift->_primary_pkg_svc(@_);
681 $pkg_svc ? $pkg_svc->svcpart : '';
684 =item part_svc [ SVCDB ]
686 Like the B<svcpart> method, but returns the FS::part_svc object (see
692 my $pkg_svc = shift->_primary_pkg_svc(@_);
693 $pkg_svc ? $pkg_svc->part_svc : '';
696 sub _primary_pkg_svc {
699 my $svcdb = scalar(@_) ? shift : [];
700 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
701 my %svcdb = map { $_=>1 } @$svcdb;
704 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
707 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
708 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
710 return '' if scalar(@pkg_svc) != 1;
714 =item svcpart_unique_svcdb SVCDB
716 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
717 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
718 false if there not a primary service definition for SVCDB or there are multiple
719 service definitions for SVCDB.
723 sub svcpart_unique_svcdb {
724 my( $self, $svcdb ) = @_;
725 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
726 return '' if scalar(@svcdb_pkg_svc) != 1;
727 $svcdb_pkg_svc[0]->svcpart;
732 Returns a list of the acceptable payment types for this package. Eventually
733 this should come out of a database table and be editable, but currently has the
734 following logic instead:
736 If the package is free, the single item B<BILL> is
737 returned, otherwise, the single item B<CARD> is returned.
739 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
745 if ( $self->is_free ) {
754 Returns true if this package is free.
760 unless ( $self->plan ) {
761 $self->setup =~ /^\s*0+(\.0*)?\s*$/
762 && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
763 } elsif ( $self->can('is_free_options') ) {
764 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
765 map { $self->option($_) }
766 $self->is_free_options;
768 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
769 "provides neither is_free_options nor is_free method; returning false";
774 sub can_discount { 0; }
777 # moved to FS::Misc to make this accessible to other packages
779 FS::Misc::pkg_freqs();
784 Returns an english representation of the I<freq> field, such as "monthly",
785 "weekly", "semi-annually", etc.
791 my $freq = $self->freq;
793 #my $freqs_href = $self->freqs_href;
794 my $freqs_href = freqs_href();
796 if ( exists($freqs_href->{$freq}) ) {
797 $freqs_href->{$freq};
799 my $interval = 'month';
800 if ( $freq =~ /^(\d+)([hdw])$/ ) {
801 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
802 $interval = $interval{$2};
807 "every $freq ${interval}s";
812 =item add_freq TIMESTAMP [ FREQ ]
814 Adds a billing period of some frequency to the provided timestamp and
815 returns the resulting timestamp, or -1 if the frequency could not be
816 parsed (shouldn't happen). By default, the frequency of this package
817 will be used; to override this, pass a different frequency as a second
823 my( $self, $date, $freq ) = @_;
824 $freq = $self->freq if !defined($freq);
826 #change this bit to use Date::Manip? CAREFUL with timezones (see
827 # mailing list archive)
828 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
830 if ( $freq =~ /^\d+$/ ) {
832 until ( $mon < 12 ) { $mon -= 12; $year++; }
833 } elsif ( $freq =~ /^(\d+)w$/ ) {
836 } elsif ( $freq =~ /^(\d+)d$/ ) {
839 } elsif ( $freq =~ /^(\d+)h$/ ) {
846 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
851 For backwards compatibility, returns the plandata field as well as all options
852 from FS::part_pkg_option.
858 carp "plandata is deprecated";
860 $self->SUPER::plandata(@_);
862 my $plandata = $self->get('plandata');
863 my %options = $self->options;
864 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
869 =item part_pkg_option
871 Returns all options as FS::part_pkg_option objects (see
872 L<FS::part_pkg_option>).
876 sub part_pkg_option {
878 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
883 Returns a list of option names and values suitable for assigning to a hash.
889 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
892 =item option OPTIONNAME [ QUIET ]
894 Returns the option value for the given name, or the empty string. If a true
895 value is passed as the second argument, warnings about missing the option
901 my( $self, $opt, $ornull ) = @_;
902 my $part_pkg_option =
903 qsearchs('part_pkg_option', {
904 pkgpart => $self->pkgpart,
907 return $part_pkg_option->optionvalue if $part_pkg_option;
908 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
909 split("\n", $self->get('plandata') );
910 return $plandata{$opt} if exists $plandata{$opt};
911 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
912 "not found in options or plandata!\n"
917 =item bill_part_pkg_link
919 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
923 sub bill_part_pkg_link {
924 shift->_part_pkg_link('bill', @_);
927 =item svc_part_pkg_link
929 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
933 sub svc_part_pkg_link {
934 shift->_part_pkg_link('svc', @_);
938 my( $self, $type ) = @_;
939 qsearch({ table => 'part_pkg_link',
940 hashref => { 'src_pkgpart' => $self->pkgpart,
941 'link_type' => $type,
943 order_by => "ORDER BY hidden",
947 sub self_and_bill_linked {
948 shift->_self_and_linked('bill', @_);
951 sub _self_and_linked {
952 my( $self, $type, $hidden ) = @_;
956 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
957 $self->_part_pkg_link($type) ) )
959 $_->hidden($hidden) if $hidden;
966 =item part_pkg_taxoverride [ CLASS ]
968 Returns all associated FS::part_pkg_taxoverride objects (see
969 L<FS::part_pkg_taxoverride>). Limits the returned set to those
970 of class CLASS if defined. Class may be one of 'setup', 'recur',
971 the empty string (default), or a usage class number (see L<FS::usage_class>).
972 When a class is specified, the empty string class (default) is returned
973 if no more specific values exist.
977 sub part_pkg_taxoverride {
981 my $hashref = { 'pkgpart' => $self->pkgpart };
982 $hashref->{'usage_class'} = $class if defined($class);
983 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
985 unless ( scalar(@overrides) || !defined($class) || !$class ){
986 $hashref->{'usage_class'} = '';
987 @overrides = qsearch('part_pkg_taxoverride', $hashref );
995 Returns true if this package has any taxproduct associated with it.
1002 $self->taxproductnum ||
1003 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1004 keys %{ {$self->options} }
1010 =item taxproduct [ CLASS ]
1012 Returns the associated tax product for this package definition (see
1013 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1014 the usage classnum (see L<FS::usage_class>). Returns the default
1015 tax product for this record if the more specific CLASS value does
1024 my $part_pkg_taxproduct;
1026 my $taxproductnum = $self->taxproductnum;
1028 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1029 $taxproductnum = $class_taxproductnum
1030 if $class_taxproductnum
1033 $part_pkg_taxproduct =
1034 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1036 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1037 $taxproductnum = $self->taxproductnum;
1038 $part_pkg_taxproduct =
1039 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1042 $part_pkg_taxproduct;
1045 =item taxproduct_description [ CLASS ]
1047 Returns the description of the associated tax product for this package
1048 definition (see L<FS::part_pkg_taxproduct>).
1052 sub taxproduct_description {
1054 my $part_pkg_taxproduct = $self->taxproduct(@_);
1055 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1058 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1060 Returns the package to taxrate m2m records for this package in the location
1061 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1062 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1063 (see L<FS::usage_class>).
1067 sub _expand_cch_taxproductnum {
1070 my $part_pkg_taxproduct = $self->taxproduct($class);
1072 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1073 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1076 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1077 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1078 OR taxproduct = '$a:$b:$c:'
1079 OR taxproduct = '$a:$b:".":$d'
1080 OR taxproduct = '$a:$b:".":' )";
1081 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1082 'hashref' => { 'data_vendor'=>'cch' },
1083 'extra_sql' => $extra_sql,
1088 sub part_pkg_taxrate {
1090 my ($data_vendor, $geocode, $class) = @_;
1093 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1094 dbh->quote($data_vendor);
1096 # CCH oddness in m2m
1097 $extra_sql .= ' AND ('.
1098 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1102 # much more CCH oddness in m2m -- this is kludgy
1103 my @tpnums = $self->_expand_cch_taxproductnum($class);
1104 if (scalar(@tpnums)) {
1105 $extra_sql .= ' AND ('.
1106 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1109 $extra_sql .= ' AND ( 0 = 1 )';
1112 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1113 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1114 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1116 # should qsearch preface columns with the table to facilitate joins?
1117 qsearch( { 'table' => 'part_pkg_taxrate',
1118 'select' => $select,
1119 'hashref' => { # 'data_vendor' => $data_vendor,
1120 # 'taxproductnum' => $self->taxproductnum,
1122 'addl_from' => $addl_from,
1123 'extra_sql' => $extra_sql,
1124 'order_by' => $order_by,
1130 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1131 PLAN is the object's I<plan> field. There should be better docs
1132 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1138 my $plan = $self->plan;
1140 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1144 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1145 my $class = ref($self). "::$plan";
1146 warn "reblessing $self into $class" if $DEBUG;
1149 bless($self, $class) unless $@;
1153 #fallbacks that eval the setup and recur fields, for backwards compat
1157 warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1158 $self->_calc_eval('setup', @_);
1163 warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1164 $self->_calc_eval('recur', @_);
1167 use vars qw( $sdate @details );
1169 #my( $self, $field, $cust_pkg ) = @_;
1170 my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1172 *details = $detailsref;
1173 $self->$field() =~ /^(.*)$/
1174 or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1175 $self->$field(). "\n";
1177 return 0 if $prog =~ /^\s*$/;
1178 my $value = eval $prog;
1183 #fallback that return 0 for old legacy packages with no plan
1185 sub calc_remain { 0; }
1186 sub calc_cancel { 0; }
1187 sub calc_units { 0; }
1189 #fallback for everything except bulk.pm
1190 sub hide_svc_detail { 0; }
1192 =item recur_cost_permonth CUST_PKG
1194 recur_cost divided by freq (only supported for monthly and longer frequencies)
1198 sub recur_cost_permonth {
1199 my($self, $cust_pkg) = @_;
1200 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1201 sprintf('%.2f', $self->recur_cost / $self->freq );
1204 =item format OPTION DATA
1206 Returns data formatted according to the function 'format' described
1207 in the plan info. Returns DATA if no such function exists.
1212 my ($self, $option, $data) = (shift, shift, shift);
1213 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1214 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1220 =item parse OPTION DATA
1222 Returns data parsed according to the function 'parse' described
1223 in the plan info. Returns DATA if no such function exists.
1228 my ($self, $option, $data) = (shift, shift, shift);
1229 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1230 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1240 =head1 CLASS METHODS
1248 # Used by FS::Upgrade to migrate to a new database.
1250 sub _upgrade_data { # class method
1251 my($class, %opts) = @_;
1253 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1255 my @part_pkg = qsearch({
1256 'table' => 'part_pkg',
1257 'extra_sql' => "WHERE ". join(' OR ',
1258 ( map "($_ IS NOT NULL AND $_ != '' )",
1259 qw( plandata setup recur ) ),
1260 'plan IS NULL', "plan = '' ",
1264 foreach my $part_pkg (@part_pkg) {
1266 unless ( $part_pkg->plan ) {
1267 $part_pkg->plan('flat');
1270 if ( length($part_pkg->option('setup_fee')) == 0
1271 && $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1273 my $opt = new FS::part_pkg_option {
1274 'pkgpart' => $part_pkg->pkgpart,
1275 'optionname' => 'setup_fee',
1276 'optionvalue' => $1,
1278 my $error = $opt->insert;
1279 die $error if $error;
1283 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1284 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1286 $part_pkg->setup('');
1288 if ( length($part_pkg->option('recur_fee')) == 0
1289 && $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1291 my $opt = new FS::part_pkg_option {
1292 'pkgpart' => $part_pkg->pkgpart,
1293 'optionname' => 'recur_fee',
1294 'optionvalue' => $1,
1296 my $error = $opt->insert;
1297 die $error if $error;
1301 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1302 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1304 $part_pkg->recur('');
1306 $part_pkg->replace; #this should take care of plandata, right?
1310 # now upgrade to the explicit custom flag
1312 @part_pkg = qsearch({
1313 'table' => 'part_pkg',
1314 'hashref' => { disabled => 'Y', custom => '' },
1315 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1318 foreach my $part_pkg (@part_pkg) {
1319 my $new = new FS::part_pkg { $part_pkg->hash };
1321 my $comment = $part_pkg->comment;
1322 $comment =~ s/^\(CUSTOM\) //;
1323 $comment = '(none)' unless $comment =~ /\S/;
1324 $new->comment($comment);
1326 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1327 my $primary = $part_pkg->svcpart;
1328 my $options = { $part_pkg->options };
1330 my $error = $new->replace( $part_pkg,
1331 'pkg_svc' => $pkg_svc,
1332 'primary_svc' => $primary,
1333 'options' => $options,
1335 die $error if $error;
1340 =item curuser_pkgs_sql
1342 Returns an SQL fragment for searching for packages the current user can
1343 use, either via part_pkg.agentnum directly, or via agent type (see
1348 sub curuser_pkgs_sql {
1351 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1355 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1357 Returns an SQL fragment for searching for packages the provided agent or agents
1358 can use, either via part_pkg.agentnum directly, or via agent type (see
1363 sub agent_pkgs_sql {
1364 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1365 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1367 $class->_pkgs_sql(@agentnums); #is this why
1372 my( $class, @agentnums ) = @_;
1373 my $agentnums = join(',', @agentnums);
1377 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1378 OR ( agentnum IS NULL
1379 AND EXISTS ( SELECT 1
1381 LEFT JOIN agent_type USING ( typenum )
1382 LEFT JOIN agent AS typeagent USING ( typenum )
1383 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1384 AND typeagent.agentnum IN ($agentnums)
1402 #false laziness w/part_export & cdr
1404 foreach my $INC ( @INC ) {
1405 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1406 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1407 warn "attempting to load plan info from $file\n" if $DEBUG;
1408 $file =~ /\/(\w+)\.pm$/ or do {
1409 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1413 my $info = eval "use FS::part_pkg::$mod; ".
1414 "\\%FS::part_pkg::$mod\::info;";
1416 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1419 unless ( keys %$info ) {
1420 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1423 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1424 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1425 warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1428 $info{$mod} = $info;
1432 tie %plans, 'Tie::IxHash',
1433 map { $_ => $info{$_} }
1434 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1444 =head1 NEW PLAN CLASSES
1446 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1447 found in eg/plan_template.pm. Until then, it is suggested that you use the
1448 other modules in FS/FS/part_pkg/ as a guide.
1452 The delete method is unimplemented.
1454 setup and recur semantics are not yet defined (and are implemented in
1455 FS::cust_bill. hmm.). now they're deprecated and need to go.
1459 part_pkg_taxrate is Pg specific
1461 replace should be smarter about managing the related tables (options, pkg_svc)
1465 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1466 schema.html from the base documentation.