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 ) {
208 my @overrides = (grep "$_", split (',', $overrides{$usage_class}) );
209 my $error = $self->process_m2m (
210 'link_table' => 'part_pkg_taxoverride',
211 'target_table' => 'tax_class',
212 'hashref' => { 'usage_class' => $usage_class },
213 'params' => \@overrides,
216 $dbh->rollback if $oldAutoCommit;
221 unless ( $skip_pkg_svc_hack ) {
223 warn " inserting pkg_svc records" if $DEBUG;
224 my $pkg_svc = $options{'pkg_svc'} || {};
225 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
226 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
228 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
232 my $pkg_svc = new FS::pkg_svc( {
233 'pkgpart' => $self->pkgpart,
234 'svcpart' => $part_svc->svcpart,
235 'quantity' => $quantity,
236 'primary_svc' => $primary_svc,
238 my $error = $pkg_svc->insert;
240 $dbh->rollback if $oldAutoCommit;
247 if ( $options{'cust_pkg'} ) {
248 warn " updating cust_pkg record " if $DEBUG;
250 ref($options{'cust_pkg'})
251 ? $options{'cust_pkg'}
252 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
253 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
254 if $options{'custnum_ref'};
255 my %hash = $old_cust_pkg->hash;
256 $hash{'pkgpart'} = $self->pkgpart,
257 my $new_cust_pkg = new FS::cust_pkg \%hash;
258 local($FS::cust_pkg::disable_agentcheck) = 1;
259 my $error = $new_cust_pkg->replace($old_cust_pkg);
261 $dbh->rollback if $oldAutoCommit;
262 return "Error modifying cust_pkg record: $error";
266 warn " commiting transaction" if $DEBUG;
267 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
274 Currently unimplemented.
279 return "Can't (yet?) delete package definitions.";
280 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
283 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
285 Replaces OLD_RECORD with this one in the database. If there is an error,
286 returns the error, otherwise returns false.
288 Currently available options are: I<pkg_svc>, I<primary_svc> and I<options>
290 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
291 values, the appropriate FS::pkg_svc records will be replaced.
293 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
294 FS::pkg_svc record will be updated.
296 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
304 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
309 ( ref($_[0]) eq 'HASH' )
313 $options->{options} = {} unless defined($options->{options});
315 warn "FS::part_pkg::replace called on $new to replace $old with options".
316 join(', ', map "$_ => ". $options->{$_}, keys %$options)
319 local $SIG{HUP} = 'IGNORE';
320 local $SIG{INT} = 'IGNORE';
321 local $SIG{QUIT} = 'IGNORE';
322 local $SIG{TERM} = 'IGNORE';
323 local $SIG{TSTP} = 'IGNORE';
324 local $SIG{PIPE} = 'IGNORE';
326 my $oldAutoCommit = $FS::UID::AutoCommit;
327 local $FS::UID::AutoCommit = 0;
330 #plandata shit stays in replace for upgrades until after 2.0 (or edit
332 warn " saving legacy plandata" if $DEBUG;
333 my $plandata = $new->get('plandata');
334 $new->set('plandata', '');
336 warn " deleting old part_pkg_option records" if $DEBUG;
337 foreach my $part_pkg_option ( $old->part_pkg_option ) {
338 my $error = $part_pkg_option->delete;
340 $dbh->rollback if $oldAutoCommit;
345 warn " replacing part_pkg record" if $DEBUG;
346 my $error = $new->SUPER::replace($old, $options->{options} );
348 $dbh->rollback if $oldAutoCommit;
352 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
353 foreach my $part_pkg_option (
354 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
355 return "illegal plandata: $plandata";
357 new FS::part_pkg_option {
358 'pkgpart' => $new->pkgpart,
363 split("\n", $plandata)
365 my $error = $part_pkg_option->insert;
367 $dbh->rollback if $oldAutoCommit;
372 warn " replacing pkg_svc records" if $DEBUG;
373 my $pkg_svc = $options->{'pkg_svc'} || {};
374 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
375 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
377 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
378 && $options->{'primary_svc'} == $part_svc->svcpart
384 my $old_pkg_svc = qsearchs('pkg_svc', {
385 'pkgpart' => $old->pkgpart,
386 'svcpart' => $part_svc->svcpart,
388 my $old_quantity = $old_pkg_svc ? $old_pkg_svc->quantity : 0;
389 my $old_primary_svc =
390 ( $old_pkg_svc && $old_pkg_svc->dbdef_table->column('primary_svc') )
391 ? $old_pkg_svc->primary_svc
393 next unless $old_quantity != $quantity || $old_primary_svc ne $primary_svc;
395 my $new_pkg_svc = new FS::pkg_svc( {
396 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
397 'pkgpart' => $new->pkgpart,
398 'svcpart' => $part_svc->svcpart,
399 'quantity' => $quantity,
400 'primary_svc' => $primary_svc,
402 my $error = $old_pkg_svc
403 ? $new_pkg_svc->replace($old_pkg_svc)
404 : $new_pkg_svc->insert;
406 $dbh->rollback if $oldAutoCommit;
411 warn " commiting transaction" if $DEBUG;
412 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
418 Checks all fields to make sure this is a valid package definition. If
419 there is an error, returns the error, otherwise returns false. Called by the
420 insert and replace methods.
426 warn "FS::part_pkg::check called on $self" if $DEBUG;
428 for (qw(setup recur plandata)) {
429 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
430 return "Use of $_ field is deprecated; set a plan and options: ".
432 if length($self->get($_));
436 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
437 my $error = $self->ut_number('freq');
438 return $error if $error;
440 $self->freq =~ /^(\d+[hdw]?)$/
441 or return "Illegal or empty freq: ". $self->freq;
445 my @null_agentnum_right = ( 'Edit global package definitions' );
446 push @null_agentnum_right, 'One-time charge'
447 if $self->freq =~ /^0/;
448 push @null_agentnum_right, 'Customize customer package'
449 if $self->disabled eq 'Y'; #good enough
451 my $error = $self->ut_numbern('pkgpart')
452 || $self->ut_text('pkg')
453 || $self->ut_text('comment')
454 || $self->ut_textn('promo_code')
455 || $self->ut_alphan('plan')
456 || $self->ut_enum('setuptax', [ '', 'Y' ] )
457 || $self->ut_enum('recurtax', [ '', 'Y' ] )
458 || $self->ut_textn('taxclass')
459 || $self->ut_enum('disabled', [ '', 'Y' ] )
460 || $self->ut_enum('custom', [ '', 'Y' ] )
461 #|| $self->ut_moneyn('setup_cost')
462 #|| $self->ut_moneyn('recur_cost')
463 || $self->ut_floatn('setup_cost')
464 || $self->ut_floatn('recur_cost')
465 || $self->ut_floatn('pay_weight')
466 || $self->ut_floatn('credit_weight')
467 || $self->ut_numbern('taxproductnum')
468 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
469 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
470 || $self->ut_foreign_keyn('taxproductnum',
471 'part_pkg_taxproduct',
475 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
476 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
478 || $self->SUPER::check
480 return $error if $error;
482 return 'Unknown plan '. $self->plan
483 unless exists($plans{$self->plan});
485 my $conf = new FS::Conf;
486 return 'Taxclass is required'
487 if ! $self->taxclass && $conf->exists('require_taxclasses');
492 =item pkg_comment [ OPTION => VALUE... ]
494 Returns an (internal) string representing this package. Currently,
495 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
496 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
499 If the option nopkgpart is true then the "pkgpart: ' is omitted.
507 #$self->pkg. ' - '. $self->comment;
508 #$self->pkg. ' ('. $self->comment. ')';
509 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
510 $pre. $self->pkg. ' - '. $self->custom_comment;
515 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment;
520 Returns the package class, as an FS::pkg_class object, or the empty string
521 if there is no package class.
527 if ( $self->classnum ) {
528 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
534 =item addon_pkg_class
536 Returns the add-on package class, as an FS::pkg_class object, or the empty
537 string if there is no add-on package class.
541 sub addon_pkg_class {
543 if ( $self->addon_classnum ) {
544 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
552 Returns the package category name, or the empty string if there is no package
559 my $pkg_class = $self->pkg_class;
561 ? $pkg_class->categoryname
567 Returns the package class name, or the empty string if there is no package
574 my $pkg_class = $self->pkg_class;
576 ? $pkg_class->classname
580 =item addon_classname
582 Returns the add-on package class name, or the empty string if there is no
583 add-on package class.
587 sub addon_classname {
589 my $pkg_class = $self->addon_pkg_class;
591 ? $pkg_class->classname
597 Returns the associated agent for this event, if any, as an FS::agent object.
603 qsearchs('agent', { 'agentnum' => $self->agentnum } );
606 =item pkg_svc [ HASHREF | OPTION => VALUE ]
608 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
609 definition (with non-zero quantity).
611 One option is available, I<disable_linked>. If set true it will return the
612 services for this package definition alone, omitting services from any add-on
619 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
626 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
632 # #sort { $b->primary cmp $a->primary }
633 # grep { $_->quantity }
634 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
636 my $opt = ref($_[0]) ? $_[0] : { @_ };
637 my %pkg_svc = map { $_->svcpart => $_ }
638 grep { $_->quantity }
639 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
641 unless ( $opt->{disable_linked} ) {
642 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
643 my @pkg_svc = grep { $_->quantity }
644 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
645 foreach my $pkg_svc ( @pkg_svc ) {
646 if ( $pkg_svc{$pkg_svc->svcpart} ) {
647 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
648 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
650 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
660 =item svcpart [ SVCDB ]
662 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
663 associated with this package definition (see L<FS::pkg_svc>). Returns
664 false if there not a primary service definition or exactly one service
665 definition with quantity 1, or if SVCDB is specified and does not match the
666 svcdb of the service definition. SVCDB can be specified as a scalar table
667 name, such as 'svc_acct', or as an arrayref of possible table names.
672 my $pkg_svc = shift->_primary_pkg_svc(@_);
673 $pkg_svc ? $pkg_svc->svcpart : '';
676 =item part_svc [ SVCDB ]
678 Like the B<svcpart> method, but returns the FS::part_svc object (see
684 my $pkg_svc = shift->_primary_pkg_svc(@_);
685 $pkg_svc ? $pkg_svc->part_svc : '';
688 sub _primary_pkg_svc {
691 my $svcdb = scalar(@_) ? shift : [];
692 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
693 my %svcdb = map { $_=>1 } @$svcdb;
696 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
699 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
700 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
702 return '' if scalar(@pkg_svc) != 1;
706 =item svcpart_unique_svcdb SVCDB
708 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
709 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
710 false if there not a primary service definition for SVCDB or there are multiple
711 service definitions for SVCDB.
715 sub svcpart_unique_svcdb {
716 my( $self, $svcdb ) = @_;
717 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
718 return '' if scalar(@svcdb_pkg_svc) != 1;
719 $svcdb_pkg_svc[0]->svcpart;
724 Returns a list of the acceptable payment types for this package. Eventually
725 this should come out of a database table and be editable, but currently has the
726 following logic instead:
728 If the package is free, the single item B<BILL> is
729 returned, otherwise, the single item B<CARD> is returned.
731 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
737 if ( $self->is_free ) {
746 Returns true if this package is free.
752 unless ( $self->plan ) {
753 $self->setup =~ /^\s*0+(\.0*)?\s*$/
754 && $self->recur =~ /^\s*0+(\.0*)?\s*$/;
755 } elsif ( $self->can('is_free_options') ) {
756 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
757 map { $self->option($_) }
758 $self->is_free_options;
760 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
761 "provides neither is_free_options nor is_free method; returning false";
768 #method, class method or sub? #my $self = shift;
770 tie my %freq, 'Tie::IxHash',
771 '0' => '(no recurring fee)',
774 '2d' => 'every two days',
775 '3d' => 'every three days',
777 '2w' => 'biweekly (every 2 weeks)',
779 '45d' => 'every 45 days',
780 '2' => 'bimonthly (every 2 months)',
781 '3' => 'quarterly (every 3 months)',
782 '4' => 'every 4 months',
783 '137d' => 'every 4 1/2 months (137 days)',
784 '6' => 'semiannually (every 6 months)',
786 '13' => 'every 13 months (annually +1 month)',
787 '24' => 'biannually (every 2 years)',
788 '36' => 'triannually (every 3 years)',
789 '48' => '(every 4 years)',
790 '60' => '(every 5 years)',
791 '120' => '(every 10 years)',
800 Returns an english representation of the I<freq> field, such as "monthly",
801 "weekly", "semi-annually", etc.
807 my $freq = $self->freq;
809 #my $freqs_href = $self->freqs_href;
810 my $freqs_href = freqs_href();
812 if ( exists($freqs_href->{$freq}) ) {
813 $freqs_href->{$freq};
815 my $interval = 'month';
816 if ( $freq =~ /^(\d+)([hdw])$/ ) {
817 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
818 $interval = $interval{$2};
823 "every $freq ${interval}s";
828 =item add_freq TIMESTAMP
830 Adds the frequency of this package to the provided timestamp and returns
831 the resulting timestamp, or -1 if the frequency of this package could not be
832 parsed (shouldn't happen).
837 my( $self, $date ) = @_;
838 my $freq = $self->freq;
840 #change this bit to use Date::Manip? CAREFUL with timezones (see
841 # mailing list archive)
842 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
844 if ( $self->freq =~ /^\d+$/ ) {
846 until ( $mon < 12 ) { $mon -= 12; $year++; }
847 } elsif ( $self->freq =~ /^(\d+)w$/ ) {
850 } elsif ( $self->freq =~ /^(\d+)d$/ ) {
853 } elsif ( $self->freq =~ /^(\d+)h$/ ) {
860 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
865 For backwards compatibility, returns the plandata field as well as all options
866 from FS::part_pkg_option.
872 carp "plandata is deprecated";
874 $self->SUPER::plandata(@_);
876 my $plandata = $self->get('plandata');
877 my %options = $self->options;
878 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
883 =item part_pkg_option
885 Returns all options as FS::part_pkg_option objects (see
886 L<FS::part_pkg_option>).
890 sub part_pkg_option {
892 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
897 Returns a list of option names and values suitable for assigning to a hash.
903 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
906 =item option OPTIONNAME
908 Returns the option value for the given name, or the empty string.
913 my( $self, $opt, $ornull ) = @_;
914 my $part_pkg_option =
915 qsearchs('part_pkg_option', {
916 pkgpart => $self->pkgpart,
919 return $part_pkg_option->optionvalue if $part_pkg_option;
920 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
921 split("\n", $self->get('plandata') );
922 return $plandata{$opt} if exists $plandata{$opt};
923 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
924 "not found in options or plandata!\n"
929 =item bill_part_pkg_link
931 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
935 sub bill_part_pkg_link {
936 shift->_part_pkg_link('bill', @_);
939 =item svc_part_pkg_link
941 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
945 sub svc_part_pkg_link {
946 shift->_part_pkg_link('svc', @_);
950 my( $self, $type ) = @_;
951 qsearch({ table => 'part_pkg_link',
952 hashref => { 'src_pkgpart' => $self->pkgpart,
953 'link_type' => $type,
955 order_by => "ORDER BY hidden",
959 sub self_and_bill_linked {
960 shift->_self_and_linked('bill', @_);
963 sub _self_and_linked {
964 my( $self, $type, $hidden ) = @_;
968 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
969 $self->_part_pkg_link($type) ) )
971 $_->hidden($hidden) if $hidden;
978 =item part_pkg_taxoverride [ CLASS ]
980 Returns all associated FS::part_pkg_taxoverride objects (see
981 L<FS::part_pkg_taxoverride>). Limits the returned set to those
982 of class CLASS if defined. Class may be one of 'setup', 'recur',
983 the empty string (default), or a usage class number (see L<FS::usage_class>).
984 When a class is specified, the empty string class (default) is returned
985 if no more specific values exist.
989 sub part_pkg_taxoverride {
993 my $hashref = { 'pkgpart' => $self->pkgpart };
994 $hashref->{'usage_class'} = $class if defined($class);
995 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
997 unless ( scalar(@overrides) || !defined($class) || !$class ){
998 $hashref->{'usage_class'} = '';
999 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1005 =item has_taxproduct
1007 Returns true if this package has any taxproduct associated with it.
1011 sub has_taxproduct {
1014 $self->taxproductnum ||
1015 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1016 keys %{ {$self->options} }
1022 =item taxproduct [ CLASS ]
1024 Returns the associated tax product for this package definition (see
1025 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1026 the usage classnum (see L<FS::usage_class>). Returns the default
1027 tax product for this record if the more specific CLASS value does
1036 my $part_pkg_taxproduct;
1038 my $taxproductnum = $self->taxproductnum;
1040 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1041 $taxproductnum = $class_taxproductnum
1042 if $class_taxproductnum
1045 $part_pkg_taxproduct =
1046 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1048 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1049 $taxproductnum = $self->taxproductnum;
1050 $part_pkg_taxproduct =
1051 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1054 $part_pkg_taxproduct;
1057 =item taxproduct_description [ CLASS ]
1059 Returns the description of the associated tax product for this package
1060 definition (see L<FS::part_pkg_taxproduct>).
1064 sub taxproduct_description {
1066 my $part_pkg_taxproduct = $self->taxproduct(@_);
1067 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1070 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1072 Returns the package to taxrate m2m records for this package in the location
1073 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1074 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1075 (see L<FS::usage_class>).
1079 sub _expand_cch_taxproductnum {
1082 my $part_pkg_taxproduct = $self->taxproduct($class);
1084 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1085 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1088 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1089 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1090 OR taxproduct = '$a:$b:$c:'
1091 OR taxproduct = '$a:$b:".":$d'
1092 OR taxproduct = '$a:$b:".":' )";
1093 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1094 'hashref' => { 'data_vendor'=>'cch' },
1095 'extra_sql' => $extra_sql,
1100 sub part_pkg_taxrate {
1102 my ($data_vendor, $geocode, $class) = @_;
1105 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1106 dbh->quote($data_vendor);
1108 # CCH oddness in m2m
1109 $extra_sql .= ' AND ('.
1110 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1114 # much more CCH oddness in m2m -- this is kludgy
1115 my @tpnums = $self->_expand_cch_taxproductnum($class);
1116 if (scalar(@tpnums)) {
1117 $extra_sql .= ' AND ('.
1118 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1121 $extra_sql .= ' AND ( 0 = 1 )';
1124 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1125 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1126 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1128 # should qsearch preface columns with the table to facilitate joins?
1129 qsearch( { 'table' => 'part_pkg_taxrate',
1130 'select' => $select,
1131 'hashref' => { # 'data_vendor' => $data_vendor,
1132 # 'taxproductnum' => $self->taxproductnum,
1134 'addl_from' => $addl_from,
1135 'extra_sql' => $extra_sql,
1136 'order_by' => $order_by,
1142 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1143 PLAN is the object's I<plan> field. There should be better docs
1144 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1150 my $plan = $self->plan;
1152 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1156 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1157 my $class = ref($self). "::$plan";
1158 warn "reblessing $self into $class" if $DEBUG;
1161 bless($self, $class) unless $@;
1165 #fallbacks that eval the setup and recur fields, for backwards compat
1169 warn 'no price plan class for '. $self->plan. ", eval-ing setup\n";
1170 $self->_calc_eval('setup', @_);
1175 warn 'no price plan class for '. $self->plan. ", eval-ing recur\n";
1176 $self->_calc_eval('recur', @_);
1179 use vars qw( $sdate @details );
1181 #my( $self, $field, $cust_pkg ) = @_;
1182 my( $self, $field, $cust_pkg, $sdateref, $detailsref ) = @_;
1184 *details = $detailsref;
1185 $self->$field() =~ /^(.*)$/
1186 or die "Illegal $field (pkgpart ". $self->pkgpart. '): '.
1187 $self->$field(). "\n";
1189 return 0 if $prog =~ /^\s*$/;
1190 my $value = eval $prog;
1195 #fallback that return 0 for old legacy packages with no plan
1197 sub calc_remain { 0; }
1198 sub calc_cancel { 0; }
1199 sub calc_units { 0; }
1201 #fallback for everything except bulk.pm
1202 sub hide_svc_detail { 0; }
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
1379 0 < ( SELECT COUNT(*)
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)
1401 #false laziness w/part_export & cdr
1403 foreach my $INC ( @INC ) {
1404 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1405 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1406 warn "attempting to load plan info from $file\n" if $DEBUG;
1407 $file =~ /\/(\w+)\.pm$/ or do {
1408 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1412 my $info = eval "use FS::part_pkg::$mod; ".
1413 "\\%FS::part_pkg::$mod\::info;";
1415 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1418 unless ( keys %$info ) {
1419 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1422 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1423 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1424 warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1427 $info{$mod} = $info;
1431 tie %plans, 'Tie::IxHash',
1432 map { $_ => $info{$_} }
1433 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1443 =head1 NEW PLAN CLASSES
1445 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1446 found in eg/plan_template.pm. Until then, it is suggested that you use the
1447 other modules in FS/FS/part_pkg/ as a guide.
1451 The delete method is unimplemented.
1453 setup and recur semantics are not yet defined (and are implemented in
1454 FS::cust_bill. hmm.). now they're deprecated and need to go.
1458 part_pkg_taxrate is Pg specific
1460 replace should be smarter about managing the related tables (options, pkg_svc)
1464 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
1465 schema.html from the base documentation.