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>)
109 Creates a new package definition. To add the package definition to
110 the database, see L<"insert">.
114 sub table { 'part_pkg'; }
118 An alternate constructor. Creates a new package definition by duplicating
119 an existing definition. A new pkgpart is assigned and the custom flag is
120 set to Y. To add the package definition to the database, see L<"insert">.
126 my $class = ref($self);
127 my %hash = $self->hash;
128 $hash{'pkgpart'} = '';
129 $hash{'custom'} = 'Y';
130 #new FS::part_pkg ( \%hash ); # ?
131 new $class ( \%hash ); # ?
134 =item insert [ , OPTION => VALUE ... ]
136 Adds this package definition to the database. If there is an error,
137 returns the error, otherwise returns false.
139 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
140 I<custnum_ref> and I<options>.
142 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
143 values, appropriate FS::pkg_svc records will be inserted.
145 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
146 FS::pkg_svc record will be updated.
148 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
149 record itself), the object will be updated to point to this package definition.
151 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
152 the scalar will be updated with the custnum value from the cust_pkg record.
154 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
155 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
156 records will be inserted.
158 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
159 records will be inserted.
166 warn "FS::part_pkg::insert called on $self with options ".
167 join(', ', map "$_=>$options{$_}", keys %options)
170 local $SIG{HUP} = 'IGNORE';
171 local $SIG{INT} = 'IGNORE';
172 local $SIG{QUIT} = 'IGNORE';
173 local $SIG{TERM} = 'IGNORE';
174 local $SIG{TSTP} = 'IGNORE';
175 local $SIG{PIPE} = 'IGNORE';
177 my $oldAutoCommit = $FS::UID::AutoCommit;
178 local $FS::UID::AutoCommit = 0;
181 warn " inserting part_pkg record" if $DEBUG;
182 my $error = $self->SUPER::insert( $options{options} );
184 $dbh->rollback if $oldAutoCommit;
188 my $conf = new FS::Conf;
189 if ( $conf->exists('agent_defaultpkg') ) {
190 warn " agent_defaultpkg set; allowing all agents to purchase package"
192 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
193 my $type_pkgs = new FS::type_pkgs({
194 'typenum' => $agent_type->typenum,
195 'pkgpart' => $self->pkgpart,
197 my $error = $type_pkgs->insert;
199 $dbh->rollback if $oldAutoCommit;
205 warn " inserting part_pkg_taxoverride records" if $DEBUG;
206 my %overrides = %{ $options{'tax_overrides'} || {} };
207 foreach my $usage_class ( keys %overrides ) {
209 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
210 ? $overrides{$usage_class}
212 my @overrides = (grep "$_", split(',', $override) );
213 my $error = $self->process_m2m (
214 'link_table' => 'part_pkg_taxoverride',
215 'target_table' => 'tax_class',
216 'hashref' => { 'usage_class' => $usage_class },
217 'params' => \@overrides,
220 $dbh->rollback if $oldAutoCommit;
225 unless ( $skip_pkg_svc_hack ) {
227 warn " inserting pkg_svc records" if $DEBUG;
228 my $pkg_svc = $options{'pkg_svc'} || {};
229 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
230 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
232 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
236 my $pkg_svc = new FS::pkg_svc( {
237 'pkgpart' => $self->pkgpart,
238 'svcpart' => $part_svc->svcpart,
239 'quantity' => $quantity,
240 'primary_svc' => $primary_svc,
242 my $error = $pkg_svc->insert;
244 $dbh->rollback if $oldAutoCommit;
251 if ( $options{'cust_pkg'} ) {
252 warn " updating cust_pkg record " if $DEBUG;
254 ref($options{'cust_pkg'})
255 ? $options{'cust_pkg'}
256 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
257 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
258 if $options{'custnum_ref'};
259 my %hash = $old_cust_pkg->hash;
260 $hash{'pkgpart'} = $self->pkgpart,
261 my $new_cust_pkg = new FS::cust_pkg \%hash;
262 local($FS::cust_pkg::disable_agentcheck) = 1;
263 my $error = $new_cust_pkg->replace($old_cust_pkg);
265 $dbh->rollback if $oldAutoCommit;
266 return "Error modifying cust_pkg record: $error";
270 warn " commiting transaction" if $DEBUG;
271 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
278 Currently unimplemented.
283 return "Can't (yet?) delete package definitions.";
284 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
287 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
289 Replaces OLD_RECORD with this one in the database. If there is an error,
290 returns the error, otherwise returns false.
292 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
294 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
295 values, the appropriate FS::pkg_svc records will be replaced.
297 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
298 FS::pkg_svc record will be updated.
300 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
308 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
313 ( ref($_[0]) eq 'HASH' )
317 $options->{options} = {} unless defined($options->{options});
319 warn "FS::part_pkg::replace called on $new to replace $old with options".
320 join(', ', map "$_ => ". $options->{$_}, keys %$options)
323 local $SIG{HUP} = 'IGNORE';
324 local $SIG{INT} = 'IGNORE';
325 local $SIG{QUIT} = 'IGNORE';
326 local $SIG{TERM} = 'IGNORE';
327 local $SIG{TSTP} = 'IGNORE';
328 local $SIG{PIPE} = 'IGNORE';
330 my $oldAutoCommit = $FS::UID::AutoCommit;
331 local $FS::UID::AutoCommit = 0;
334 #plandata shit stays in replace for upgrades until after 2.0 (or edit
336 warn " saving legacy plandata" if $DEBUG;
337 my $plandata = $new->get('plandata');
338 $new->set('plandata', '');
340 warn " deleting old part_pkg_option records" if $DEBUG;
341 foreach my $part_pkg_option ( $old->part_pkg_option ) {
342 my $error = $part_pkg_option->delete;
344 $dbh->rollback if $oldAutoCommit;
349 warn " replacing part_pkg record" if $DEBUG;
350 my $error = $new->SUPER::replace($old, $options->{options} );
352 $dbh->rollback if $oldAutoCommit;
356 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
357 foreach my $part_pkg_option (
358 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
359 return "illegal plandata: $plandata";
361 new FS::part_pkg_option {
362 'pkgpart' => $new->pkgpart,
367 split("\n", $plandata)
369 my $error = $part_pkg_option->insert;
371 $dbh->rollback if $oldAutoCommit;
376 warn " replacing pkg_svc records" if $DEBUG;
377 my $pkg_svc = $options->{'pkg_svc'} || {};
378 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
379 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
381 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
382 && $options->{'primary_svc'} == $part_svc->svcpart
388 my $old_pkg_svc = qsearchs('pkg_svc', {
389 'pkgpart' => $old->pkgpart,
390 'svcpart' => $part_svc->svcpart,
392 my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
393 my $old_primary_svc =
394 ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
395 ? $old_pkg_svc->primary_svc
397 next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
399 my $new_pkg_svc = new FS::pkg_svc( {
400 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
401 'pkgpart' => $new->pkgpart,
402 'svcpart' => $part_svc->svcpart,
403 'quantity' => $quantity,
404 'primary_svc' => $primary_svc,
406 my $error = $old_pkg_svc
407 ? $new_pkg_svc->replace($old_pkg_svc)
408 : $new_pkg_svc->insert;
410 $dbh->rollback if $oldAutoCommit;
415 warn " commiting transaction" if $DEBUG;
416 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
422 Checks all fields to make sure this is a valid package definition. If
423 there is an error, returns the error, otherwise returns false. Called by the
424 insert and replace methods.
430 warn "FS::part_pkg::check called on $self" if $DEBUG;
432 for (qw(setup recur plandata)) {
433 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
434 return "Use of $_ field is deprecated; set a plan and options: ".
436 if length($self->get($_));
440 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
441 my $error = $self->ut_number('freq');
442 return $error if $error;
444 $self->freq =~ /^(\d+[hdw]?)$/
445 or return "Illegal or empty freq: ". $self->freq;
449 my @null_agentnum_right = ( 'Edit global package definitions' );
450 push @null_agentnum_right, 'One-time charge'
451 if $self->freq =~ /^0/;
452 push @null_agentnum_right, 'Customize customer package'
453 if $self->disabled eq 'Y'; #good enough
455 my $error = $self->ut_numbern('pkgpart')
456 || $self->ut_text('pkg')
457 || $self->ut_text('comment')
458 || $self->ut_textn('promo_code')
459 || $self->ut_alphan('plan')
460 || $self->ut_enum('setuptax', [ '', 'Y' ] )
461 || $self->ut_enum('recurtax', [ '', 'Y' ] )
462 || $self->ut_textn('taxclass')
463 || $self->ut_enum('disabled', [ '', 'Y' ] )
464 || $self->ut_enum('custom', [ '', 'Y' ] )
465 || $self->ut_enum('no_auto', [ '', 'Y' ])
466 #|| $self->ut_moneyn('setup_cost')
467 #|| $self->ut_moneyn('recur_cost')
468 || $self->ut_floatn('setup_cost')
469 || $self->ut_floatn('recur_cost')
470 || $self->ut_floatn('pay_weight')
471 || $self->ut_floatn('credit_weight')
472 || $self->ut_numbern('taxproductnum')
473 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
474 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
475 || $self->ut_foreign_keyn('taxproductnum',
476 'part_pkg_taxproduct',
480 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
481 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
483 || $self->SUPER::check
485 return $error if $error;
487 return 'Unknown plan '. $self->plan
488 unless exists($plans{$self->plan});
490 my $conf = new FS::Conf;
491 return 'Taxclass is required'
492 if ! $self->taxclass && $conf->exists('require_taxclasses');
497 =item pkg_comment [ OPTION => VALUE... ]
499 Returns an (internal) string representing this package. Currently,
500 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
501 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
504 If the option nopkgpart is true then the "pkgpart: ' is omitted.
512 #$self->pkg. ' - '. $self->comment;
513 #$self->pkg. ' ('. $self->comment. ')';
514 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
515 $pre. $self->pkg. ' - '. $self->custom_comment;
520 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment;
525 Returns the package class, as an FS::pkg_class object, or the empty string
526 if there is no package class.
532 if ( $self->classnum ) {
533 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
539 =item addon_pkg_class
541 Returns the add-on package class, as an FS::pkg_class object, or the empty
542 string if there is no add-on package class.
546 sub addon_pkg_class {
548 if ( $self->addon_classnum ) {
549 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
557 Returns the package category name, or the empty string if there is no package
564 my $pkg_class = $self->pkg_class;
566 ? $pkg_class->categoryname
572 Returns the package class name, or the empty string if there is no package
579 my $pkg_class = $self->pkg_class;
581 ? $pkg_class->classname
585 =item addon_classname
587 Returns the add-on package class name, or the empty string if there is no
588 add-on package class.
592 sub addon_classname {
594 my $pkg_class = $self->addon_pkg_class;
596 ? $pkg_class->classname
602 Returns the associated agent for this event, if any, as an FS::agent object.
608 qsearchs('agent', { 'agentnum' => $self->agentnum } );
611 =item pkg_svc [ HASHREF | OPTION => VALUE ]
613 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
614 definition (with non-zero quantity).
616 One option is available, I<disable_linked>. If set true it will return the
617 services for this package definition alone, omitting services from any add-on
624 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
631 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
637 # #sort { $b->primary cmp $a->primary }
638 # grep { $_->quantity }
639 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
641 my $opt = ref($_[0]) ? $_[0] : { @_ };
642 my %pkg_svc = map { $_->svcpart => $_ }
643 grep { $_->quantity }
644 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
646 unless ( $opt->{disable_linked} ) {
647 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
648 my @pkg_svc = grep { $_->quantity }
649 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
650 foreach my $pkg_svc ( @pkg_svc ) {
651 if ( $pkg_svc{$pkg_svc->svcpart} ) {
652 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
653 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
655 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
665 =item svcpart [ SVCDB ]
667 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
668 associated with this package definition (see L<FS::pkg_svc>). Returns
669 false if there not a primary service definition or exactly one service
670 definition with quantity 1, or if SVCDB is specified and does not match the
671 svcdb of the service definition. SVCDB can be specified as a scalar table
672 name, such as 'svc_acct', or as an arrayref of possible table names.
677 my $pkg_svc = shift->_primary_pkg_svc(@_);
678 $pkg_svc ? $pkg_svc->svcpart : '';
681 =item part_svc [ SVCDB ]
683 Like the B<svcpart> method, but returns the FS::part_svc object (see
689 my $pkg_svc = shift->_primary_pkg_svc(@_);
690 $pkg_svc ? $pkg_svc->part_svc : '';
693 sub _primary_pkg_svc {
696 my $svcdb = scalar(@_) ? shift : [];
697 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
698 my %svcdb = map { $_=>1 } @$svcdb;
701 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
704 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
705 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
707 return '' if scalar(@pkg_svc) != 1;
711 =item svcpart_unique_svcdb SVCDB
713 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
714 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
715 false if there not a primary service definition for SVCDB or there are multiple
716 service definitions for SVCDB.
720 sub svcpart_unique_svcdb {
721 my( $self, $svcdb ) = @_;
722 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
723 return '' if scalar(@svcdb_pkg_svc) != 1;
724 $svcdb_pkg_svc[0]->svcpart;
729 Returns a list of the acceptable payment types for this package. Eventually
730 this should come out of a database table and be editable, but currently has the
731 following logic instead:
733 If the package is free, the single item B<BILL> is
734 returned, otherwise, the single item B<CARD> is returned.
736 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
742 if ( $self->is_free ) {
751 Returns true if this package is free.
757 unless ( $self->plan ) {
758 $self->setup =~ /^\s*0+(\.0*)?\s*$/
759 && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
760 } elsif ( $self->can('is_free_options') ) {
761 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
762 map { $self->option($_) }
763 $self->is_free_options;
765 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
766 "provides neither is_free_options nor is_free method; returning false";
771 sub can_discount { 0; }
774 #method, class method or sub? #my $self = shift;
776 tie my %freq, 'Tie::IxHash',
777 '0' => '(no recurring fee)',
780 '2d' => 'every two days',
781 '3d' => 'every three days',
783 '2w' => 'biweekly (every 2 weeks)',
785 '45d' => 'every 45 days',
786 '2' => 'bimonthly (every 2 months)',
787 '3' => 'quarterly (every 3 months)',
788 '4' => 'every 4 months',
789 '137d' => 'every 4 1/2 months (137 days)',
790 '6' => 'semiannually (every 6 months)',
792 '13' => 'every 13 months (annually +1 month)',
793 '24' => 'biannually (every 2 years)',
794 '36' => 'triannually (every 3 years)',
795 '48' => '(every 4 years)',
796 '60' => '(every 5 years)',
797 '120' => '(every 10 years)',
806 Returns an english representation of the I<freq> field, such as "monthly",
807 "weekly", "semi-annually", etc.
813 my $freq = $self->freq;
815 #my $freqs_href = $self->freqs_href;
816 my $freqs_href = freqs_href();
818 if ( exists($freqs_href->{$freq}) ) {
819 $freqs_href->{$freq};
821 my $interval = 'month';
822 if ( $freq =~ /^(\d+)([hdw])$/ ) {
823 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
824 $interval = $interval{$2};
829 "every $freq ${interval}s";
834 =item add_freq TIMESTAMP
836 Adds the frequency of this package to the provided timestamp and returns
837 the resulting timestamp, or -1 if the frequency of this package could not be
838 parsed (shouldn't happen).
843 my( $self, $date ) = @_;
844 my $freq = $self->freq;
846 #change this bit to use Date::Manip? CAREFUL with timezones (see
847 # mailing list archive)
848 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
850 if ( $self->freq =~ /^\d+$/ ) {
852 until ( $mon < 12 ) { $mon -= 12; $year++; }
853 } elsif ( $self->freq =~ /^(\d+)w$/ ) {
856 } elsif ( $self->freq =~ /^(\d+)d$/ ) {
859 } elsif ( $self->freq =~ /^(\d+)h$/ ) {
866 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
871 For backwards compatibility, returns the plandata field as well as all options
872 from FS::part_pkg_option.
878 carp "plandata is deprecated";
880 $self->SUPER::plandata(@_);
882 my $plandata = $self->get('plandata');
883 my %options = $self->options;
884 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
889 =item part_pkg_option
891 Returns all options as FS::part_pkg_option objects (see
892 L<FS::part_pkg_option>).
896 sub part_pkg_option {
898 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
903 Returns a list of option names and values suitable for assigning to a hash.
909 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
912 =item option OPTIONNAME [ QUIET ]
914 Returns the option value for the given name, or the empty string. If a true
915 value is passed as the second argument, warnings about missing the option
921 my( $self, $opt, $ornull ) = @_;
922 my $part_pkg_option =
923 qsearchs('part_pkg_option', {
924 pkgpart => $self->pkgpart,
927 return $part_pkg_option->optionvalue if $part_pkg_option;
928 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
929 split("\n", $self->get('plandata') );
930 return $plandata{$opt} if exists $plandata{$opt};
931 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
932 "not found in options or plandata!\n"
937 =item bill_part_pkg_link
939 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
943 sub bill_part_pkg_link {
944 shift->_part_pkg_link('bill', @_);
947 =item svc_part_pkg_link
949 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
953 sub svc_part_pkg_link {
954 shift->_part_pkg_link('svc', @_);
958 my( $self, $type ) = @_;
959 qsearch({ table => 'part_pkg_link',
960 hashref => { 'src_pkgpart' => $self->pkgpart,
961 'link_type' => $type,
963 order_by => "ORDER BY hidden",
967 sub self_and_bill_linked {
968 shift->_self_and_linked('bill', @_);
971 sub _self_and_linked {
972 my( $self, $type, $hidden ) = @_;
976 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
977 $self->_part_pkg_link($type) ) )
979 $_->hidden($hidden) if $hidden;
986 =item part_pkg_taxoverride [ CLASS ]
988 Returns all associated FS::part_pkg_taxoverride objects (see
989 L<FS::part_pkg_taxoverride>). Limits the returned set to those
990 of class CLASS if defined. Class may be one of 'setup', 'recur',
991 the empty string (default), or a usage class number (see L<FS::usage_class>).
992 When a class is specified, the empty string class (default) is returned
993 if no more specific values exist.
997 sub part_pkg_taxoverride {
1001 my $hashref = { 'pkgpart' => $self->pkgpart };
1002 $hashref->{'usage_class'} = $class if defined($class);
1003 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1005 unless ( scalar(@overrides) || !defined($class) || !$class ){
1006 $hashref->{'usage_class'} = '';
1007 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1013 =item has_taxproduct
1015 Returns true if this package has any taxproduct associated with it.
1019 sub has_taxproduct {
1022 $self->taxproductnum ||
1023 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1024 keys %{ {$self->options} }
1030 =item taxproduct [ CLASS ]
1032 Returns the associated tax product for this package definition (see
1033 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1034 the usage classnum (see L<FS::usage_class>). Returns the default
1035 tax product for this record if the more specific CLASS value does
1044 my $part_pkg_taxproduct;
1046 my $taxproductnum = $self->taxproductnum;
1048 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1049 $taxproductnum = $class_taxproductnum
1050 if $class_taxproductnum
1053 $part_pkg_taxproduct =
1054 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1056 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1057 $taxproductnum = $self->taxproductnum;
1058 $part_pkg_taxproduct =
1059 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1062 $part_pkg_taxproduct;
1065 =item taxproduct_description [ CLASS ]
1067 Returns the description of the associated tax product for this package
1068 definition (see L<FS::part_pkg_taxproduct>).
1072 sub taxproduct_description {
1074 my $part_pkg_taxproduct = $self->taxproduct(@_);
1075 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1078 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1080 Returns the package to taxrate m2m records for this package in the location
1081 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1082 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1083 (see L<FS::usage_class>).
1087 sub _expand_cch_taxproductnum {
1090 my $part_pkg_taxproduct = $self->taxproduct($class);
1092 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1093 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1096 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1097 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1098 OR taxproduct = '$a:$b:$c:'
1099 OR taxproduct = '$a:$b:".":$d'
1100 OR taxproduct = '$a:$b:".":' )";
1101 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1102 'hashref' => { 'data_vendor'=>'cch' },
1103 'extra_sql' => $extra_sql,
1108 sub part_pkg_taxrate {
1110 my ($data_vendor, $geocode, $class) = @_;
1113 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1114 dbh->quote($data_vendor);
1116 # CCH oddness in m2m
1117 $extra_sql .= ' AND ('.
1118 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1122 # much more CCH oddness in m2m -- this is kludgy
1123 my @tpnums = $self->_expand_cch_taxproductnum($class);
1124 if (scalar(@tpnums)) {
1125 $extra_sql .= ' AND ('.
1126 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1129 $extra_sql .= ' AND ( 0 = 1 )';
1132 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1133 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1134 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1136 # should qsearch preface columns with the table to facilitate joins?
1137 qsearch( { 'table' => 'part_pkg_taxrate',
1138 'select' => $select,
1139 'hashref' => { # 'data_vendor' => $data_vendor,
1140 # 'taxproductnum' => $self->taxproductnum,
1142 'addl_from' => $addl_from,
1143 'extra_sql' => $extra_sql,
1144 'order_by' => $order_by,
1150 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1151 PLAN is the object's I<plan> field. There should be better docs
1152 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1158 my $plan = $self->plan;
1160 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1164 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1165 my $class = ref($self). "::$plan";
1166 warn "reblessing $self into $class" if $DEBUG;
1169 bless($self, $class) unless $@;
1173 #fallbacks that eval the setup and recur fields, for backwards compat
1177 warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1178 $self->_calc_eval('setup', @_);
1183 warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1184 $self->_calc_eval('recur', @_);
1187 use vars qw( $sdate @details );
1189 #my( $self, $field, $cust_pkg ) = @_;
1190 my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1192 *details = $detailsref;
1193 $self->$field() =~ /^(.*)$/
1194 or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1195 $self->$field(). "\n";
1197 return 0 if $prog =~ /^\s*$/;
1198 my $value = eval $prog;
1203 #fallback that return 0 for old legacy packages with no plan
1205 sub calc_remain { 0; }
1206 sub calc_cancel { 0; }
1207 sub calc_units { 0; }
1209 #fallback for everything except bulk.pm
1210 sub hide_svc_detail { 0; }
1212 =item recur_cost_permonth CUST_PKG
1214 recur_cost divided by freq (only supported for monthly and longer frequencies)
1218 sub recur_cost_permonth {
1219 my($self, $cust_pkg) = @_;
1220 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1221 sprintf('%.2f', $self->recur_cost / $self->freq );
1224 =item format OPTION DATA
1226 Returns data formatted according to the function 'format' described
1227 in the plan info. Returns DATA if no such function exists.
1232 my ($self, $option, $data) = (shift, shift, shift);
1233 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1234 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1240 =item parse OPTION DATA
1242 Returns data parsed according to the function 'parse' described
1243 in the plan info. Returns DATA if no such function exists.
1248 my ($self, $option, $data) = (shift, shift, shift);
1249 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1250 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1260 =head1 CLASS METHODS
1268 # Used by FS::Upgrade to migrate to a new database.
1270 sub _upgrade_data { # class method
1271 my($class, %opts) = @_;
1273 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1275 my @part_pkg = qsearch({
1276 'table' => 'part_pkg',
1277 'extra_sql' => "WHERE ". join(' OR ',
1278 ( map "($_ IS NOT NULL AND $_ != '' )",
1279 qw( plandata setup recur ) ),
1280 'plan IS NULL', "plan = '' ",
1284 foreach my $part_pkg (@part_pkg) {
1286 unless ( $part_pkg->plan ) {
1287 $part_pkg->plan('flat');
1290 if ( length($part_pkg->option('setup_fee')) == 0
1291 && $part_pkg->setup =~ /^\s*([\d\.]+)\s*$/ ) {
1293 my $opt = new FS::part_pkg_option {
1294 'pkgpart' => $part_pkg->pkgpart,
1295 'optionname' => 'setup_fee',
1296 'optionvalue' => $1,
1298 my $error = $opt->insert;
1299 die $error if $error;
1303 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1304 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1306 $part_pkg->setup('');
1308 if ( length($part_pkg->option('recur_fee')) == 0
1309 && $part_pkg->recur =~ /^\s*([\d\.]+)\s*$/ ) {
1311 my $opt = new FS::part_pkg_option {
1312 'pkgpart' => $part_pkg->pkgpart,
1313 'optionname' => 'recur_fee',
1314 'optionvalue' => $1,
1316 my $error = $opt->insert;
1317 die $error if $error;
1321 # die "Can't parse part_pkg.setup for fee; convert pkgnum ".
1322 # $part_pkg->pkgnum. " manually: ". $part_pkg->setup. "\n";
1324 $part_pkg->recur('');
1326 $part_pkg->replace; #this should take care of plandata, right?
1330 # now upgrade to the explicit custom flag
1332 @part_pkg = qsearch({
1333 'table' => 'part_pkg',
1334 'hashref' => { disabled => 'Y', custom => '' },
1335 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1338 foreach my $part_pkg (@part_pkg) {
1339 my $new = new FS::part_pkg { $part_pkg->hash };
1341 my $comment = $part_pkg->comment;
1342 $comment =~ s/^\(CUSTOM\) //;
1343 $comment = '(none)' unless $comment =~ /\S/;
1344 $new->comment($comment);
1346 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1347 my $primary = $part_pkg->svcpart;
1348 my $options = { $part_pkg->options };
1350 my $error = $new->replace( $part_pkg,
1351 'pkg_svc' => $pkg_svc,
1352 'primary_svc' => $primary,
1353 'options' => $options,
1355 die $error if $error;
1360 =item curuser_pkgs_sql
1362 Returns an SQL fragment for searching for packages the current user can
1363 use, either via part_pkg.agentnum directly, or via agent type (see
1368 sub curuser_pkgs_sql {
1371 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1375 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1377 Returns an SQL fragment for searching for packages the provided agent or agents
1378 can use, either via part_pkg.agentnum directly, or via agent type (see
1383 sub agent_pkgs_sql {
1384 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1385 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1387 $class->_pkgs_sql(@agentnums); #is this why
1392 my( $class, @agentnums ) = @_;
1393 my $agentnums = join(',', @agentnums);
1397 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1398 OR ( agentnum IS NULL
1399 AND EXISTS ( SELECT 1
1401 LEFT JOIN agent_type USING ( typenum )
1402 LEFT JOIN agent AS typeagent USING ( typenum )
1403 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1404 AND typeagent.agentnum IN ($agentnums)
1422 #false laziness w/part_export & cdr
1424 foreach my $INC ( @INC ) {
1425 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1426 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1427 warn "attempting to load plan info from $file\n" if $DEBUG;
1428 $file =~ /\/(\w+)\.pm$/ or do {
1429 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1433 my $info = eval "use FS::part_pkg::$mod; ".
1434 "\\%FS::part_pkg::$mod\::info;";
1436 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1439 unless ( keys %$info ) {
1440 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1443 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1444 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1445 warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1448 $info{$mod} = $info;
1452 tie %plans, 'Tie::IxHash',
1453 map { $_ => $info{$_} }
1454 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1464 =head1 NEW PLAN CLASSES
1466 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1467 found in eg/plan_template.pm. Until then, it is suggested that you use the
1468 other modules in FS/FS/part_pkg/ as a guide.
1472 The delete method is unimplemented.
1474 setup and recur semantics are not yet defined (and are implemented in
1475 FS::cust_bill. hmm.). now they're deprecated and need to go.
1479 part_pkg_taxrate is Pg specific
1481 replace should be smarter about managing the related tables (options, pkg_svc)
1485 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1486 schema.html from the base documentation.