2 use base qw( FS::m2m_Common FS::o2m_Common FS::option_Common );
5 use vars qw( %plans $DEBUG $setup_hack $skip_pkg_svc_hack
6 $cache_enabled %cache_link %cache_pkg_svc
8 use Carp qw(carp cluck confess);
9 use Scalar::Util qw( blessed );
11 use Time::Local qw( timelocal timelocal_nocheck ); # eventually replace with DateTime
14 use FS::Record qw( qsearch qsearchs dbh dbdef );
15 use FS::Cursor; # for upgrade
21 use FS::part_pkg_option;
22 use FS::part_pkg_fcc_option;
25 use FS::part_pkg_msgcat;
26 use FS::part_pkg_taxrate;
27 use FS::part_pkg_taxoverride;
28 use FS::part_pkg_taxproduct;
29 use FS::part_pkg_link;
30 use FS::part_pkg_discount;
31 use FS::part_pkg_usage;
32 use FS::part_pkg_vendor;
37 $skip_pkg_svc_hack = 0;
45 FS::part_pkg - Object methods for part_pkg objects
51 $record = new FS::part_pkg \%hash
52 $record = new FS::part_pkg { 'column' => 'value' };
54 $custom_record = $template_record->clone;
56 $error = $record->insert;
58 $error = $new_record->replace($old_record);
60 $error = $record->delete;
62 $error = $record->check;
64 @pkg_svc = $record->pkg_svc;
66 $svcnum = $record->svcpart;
67 $svcnum = $record->svcpart( 'svc_acct' );
71 An FS::part_pkg object represents a package definition. FS::part_pkg
72 inherits from FS::Record. The following fields are currently supported:
76 =item pkgpart - primary key (assigned automatically for new package definitions)
78 =item pkg - Text name of this package definition (customer-viewable)
80 =item comment - Text name of this package definition (non-customer-viewable)
82 =item classnum - Optional package class (see L<FS::pkg_class>)
84 =item promo_code - Promotional code
86 =item setup - Setup fee expression (deprecated)
88 =item freq - Frequency of recurring fee
90 =item recur - Recurring fee expression (deprecated)
92 =item setuptax - Setup fee tax exempt flag, empty or `Y'
94 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
96 =item taxclass - Tax class
98 =item plan - Price plan
100 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
102 =item disabled - Disabled flag, empty or `Y'
104 =item custom - Custom flag, empty or `Y'
106 =item setup_cost - for cost tracking
108 =item recur_cost - for cost tracking
110 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
112 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
114 =item agentnum - Optional agentnum (see L<FS::agent>)
116 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
118 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
121 =item successor - Foreign key for the part_pkg that replaced this record.
122 If this record is not obsolete, will be null.
124 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
125 ancestor of this record. If this record is not a successor to another
126 part_pkg, will be equal to pkgpart.
128 =item delay_start - Number of days to delay package start, by default
130 =item start_on_hold - 'Y' to suspend this package immediately when it is
131 ordered. The package will not start billing or have a setup fee charged
132 until it is manually unsuspended.
142 Creates a new package definition. To add the package definition to
143 the database, see L<"insert">.
147 sub table { 'part_pkg'; }
151 An alternate constructor. Creates a new package definition by duplicating
152 an existing definition. A new pkgpart is assigned and the custom flag is
153 set to Y. To add the package definition to the database, see L<"insert">.
159 my $class = ref($self);
160 my %hash = $self->hash;
161 $hash{'pkgpart'} = '';
162 $hash{'custom'} = 'Y';
163 #new FS::part_pkg ( \%hash ); # ?
164 new $class ( \%hash ); # ?
167 =item insert [ , OPTION => VALUE ... ]
169 Adds this package definition to the database. If there is an error,
170 returns the error, otherwise returns false.
172 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
173 I<custnum_ref> and I<options>.
175 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
176 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
177 be set to a hashref of svcparts and flag values ('Y' or '') to set the
178 'hidden' field in these records, and I<provision_hold> can be set similarly
179 for the 'provision_hold' field in these records.
181 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
182 FS::pkg_svc record will be updated.
184 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
185 record itself), the object will be updated to point to this package definition.
187 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
188 the scalar will be updated with the custnum value from the cust_pkg record.
190 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
191 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
192 records will be inserted.
194 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
195 records will be inserted.
202 warn "FS::part_pkg::insert called on $self with options ".
203 join(', ', map "$_=>$options{$_}", keys %options)
206 local $SIG{HUP} = 'IGNORE';
207 local $SIG{INT} = 'IGNORE';
208 local $SIG{QUIT} = 'IGNORE';
209 local $SIG{TERM} = 'IGNORE';
210 local $SIG{TSTP} = 'IGNORE';
211 local $SIG{PIPE} = 'IGNORE';
213 my $oldAutoCommit = $FS::UID::AutoCommit;
214 local $FS::UID::AutoCommit = 0;
217 warn " inserting part_pkg record" if $DEBUG;
218 my $error = $self->SUPER::insert( $options{options} );
220 $dbh->rollback if $oldAutoCommit;
225 if ( $self->get('family_pkgpart') eq '' ) {
226 $self->set('family_pkgpart' => $self->pkgpart);
227 $error = $self->SUPER::replace;
229 $dbh->rollback if $oldAutoCommit;
234 warn " inserting part_pkg_taxoverride records" if $DEBUG;
235 my %overrides = %{ $options{'tax_overrides'} || {} };
236 foreach my $usage_class ( keys %overrides ) {
238 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
239 ? $overrides{$usage_class}
241 my @overrides = (grep "$_", split(',', $override) );
242 my $error = $self->process_m2m (
243 'link_table' => 'part_pkg_taxoverride',
244 'target_table' => 'tax_class',
245 'hashref' => { 'usage_class' => $usage_class },
246 'params' => \@overrides,
249 $dbh->rollback if $oldAutoCommit;
254 unless ( $skip_pkg_svc_hack ) {
256 warn " inserting pkg_svc records" if $DEBUG;
257 my $pkg_svc = $options{'pkg_svc'} || {};
258 my $hidden_svc = $options{'hidden_svc'} || {};
259 my $provision_hold = $options{'provision_hold'} || {};
260 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
261 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
263 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
267 my $pkg_svc = new FS::pkg_svc( {
268 'pkgpart' => $self->pkgpart,
269 'svcpart' => $part_svc->svcpart,
270 'quantity' => $quantity,
271 'primary_svc' => $primary_svc,
272 'hidden' => $hidden_svc->{$part_svc->svcpart},
273 'provision_hold' => $provision_hold->{$part_svc->svcpart},
275 my $error = $pkg_svc->insert;
277 $dbh->rollback if $oldAutoCommit;
284 if ( $options{'cust_pkg'} ) {
285 warn " updating cust_pkg record " if $DEBUG;
287 ref($options{'cust_pkg'})
288 ? $options{'cust_pkg'}
289 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
290 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
291 if $options{'custnum_ref'};
292 my %hash = $old_cust_pkg->hash;
293 $hash{'pkgpart'} = $self->pkgpart,
294 my $new_cust_pkg = new FS::cust_pkg \%hash;
295 local($FS::cust_pkg::disable_agentcheck) = 1;
296 my $error = $new_cust_pkg->replace($old_cust_pkg);
298 $dbh->rollback if $oldAutoCommit;
299 return "Error modifying cust_pkg record: $error";
303 if ( $options{'part_pkg_vendor'} ) {
304 while ( my ($exportnum, $vendor_pkg_id) =
305 each %{ $options{part_pkg_vendor} }
308 my $ppv = new FS::part_pkg_vendor( {
309 'pkgpart' => $self->pkgpart,
310 'exportnum' => $exportnum,
311 'vendor_pkg_id' => $vendor_pkg_id,
313 my $error = $ppv->insert;
315 $dbh->rollback if $oldAutoCommit;
316 return "Error inserting part_pkg_vendor record: $error";
321 if ( $options{fcc_options} ) {
322 warn " updating fcc options " if $DEBUG;
323 $self->set_fcc_options( $options{fcc_options} );
326 warn " committing transaction" if $DEBUG and $oldAutoCommit;
327 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
334 Currently unimplemented.
339 return "Can't (yet?) delete package definitions.";
340 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
343 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
345 Replaces OLD_RECORD with this one in the database. If there is an error,
346 returns the error, otherwise returns false.
348 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>,
349 I<provision_hold> and I<options>
351 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
352 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
353 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
354 'hidden' field in these records. I<provision_hold> can be set
355 to a hashref of svcparts and flag values ('Y' or '') to set the field
358 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
359 FS::pkg_svc record will be updated.
361 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
369 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
374 ( ref($_[0]) eq 'HASH' )
378 $options->{options} = { $old->options } unless defined($options->{options});
380 warn "FS::part_pkg::replace called on $new to replace $old with options".
381 join(', ', map "$_ => ". $options->{$_}, keys %$options)
384 local $SIG{HUP} = 'IGNORE';
385 local $SIG{INT} = 'IGNORE';
386 local $SIG{QUIT} = 'IGNORE';
387 local $SIG{TERM} = 'IGNORE';
388 local $SIG{TSTP} = 'IGNORE';
389 local $SIG{PIPE} = 'IGNORE';
391 my $oldAutoCommit = $FS::UID::AutoCommit;
392 local $FS::UID::AutoCommit = 0;
395 my $conf = new FS::Conf;
396 if ( $conf->exists('part_pkg-lineage') ) {
397 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
398 qw(setup_fee recur_fee) #others? config?
401 warn " superseding package" if $DEBUG;
403 my $error = $new->supersede($old, %$options);
405 $dbh->rollback if $oldAutoCommit;
409 warn " committing transaction" if $DEBUG and $oldAutoCommit;
410 $dbh->commit if $oldAutoCommit;
417 #plandata shit stays in replace for upgrades until after 2.0 (or edit
419 warn " saving legacy plandata" if $DEBUG;
420 my $plandata = $new->get('plandata');
421 $new->set('plandata', '');
423 warn " deleting old part_pkg_option records" if $DEBUG;
424 foreach my $part_pkg_option ( $old->part_pkg_option ) {
425 my $error = $part_pkg_option->delete;
427 $dbh->rollback if $oldAutoCommit;
432 warn " replacing part_pkg record" if $DEBUG;
433 my $error = $new->SUPER::replace($old, $options->{options} );
435 $dbh->rollback if $oldAutoCommit;
439 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
440 foreach my $part_pkg_option (
441 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
442 return "illegal plandata: $plandata";
444 new FS::part_pkg_option {
445 'pkgpart' => $new->pkgpart,
450 split("\n", $plandata)
452 my $error = $part_pkg_option->insert;
454 $dbh->rollback if $oldAutoCommit;
459 warn " replacing pkg_svc records" if $DEBUG;
460 my $pkg_svc = $options->{'pkg_svc'};
461 my $hidden_svc = $options->{'hidden_svc'} || {};
462 my $provision_hold = $options->{'provision_hold'} || {};
463 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
464 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
465 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
466 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
467 my $provision_hold = $provision_hold->{$part_svc->svcpart} || '';
469 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
470 && $options->{'primary_svc'} == $part_svc->svcpart
475 my $old_pkg_svc = qsearchs('pkg_svc', {
476 'pkgpart' => $old->pkgpart,
477 'svcpart' => $part_svc->svcpart,
480 my $old_quantity = 0;
481 my $old_primary_svc = '';
483 my $old_provision_hold = '';
484 if ( $old_pkg_svc ) {
485 $old_quantity = $old_pkg_svc->quantity;
486 $old_primary_svc = $old_pkg_svc->primary_svc
487 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
488 $old_hidden = $old_pkg_svc->hidden;
489 $old_provision_hold = $old_pkg_svc->provision_hold;
492 next unless $old_quantity != $quantity ||
493 $old_primary_svc ne $primary_svc ||
494 $old_hidden ne $hidden ||
495 $old_provision_hold ne $provision_hold;
497 my $new_pkg_svc = new FS::pkg_svc( {
498 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
499 'pkgpart' => $new->pkgpart,
500 'svcpart' => $part_svc->svcpart,
501 'quantity' => $quantity,
502 'primary_svc' => $primary_svc,
504 'provision_hold' => $provision_hold,
506 my $error = $old_pkg_svc
507 ? $new_pkg_svc->replace($old_pkg_svc)
508 : $new_pkg_svc->insert;
510 $dbh->rollback if $oldAutoCommit;
514 } #if $options->{pkg_svc}
516 my @part_pkg_vendor = $old->part_pkg_vendor;
517 my @current_exportnum = ();
518 if ( $options->{'part_pkg_vendor'} ) {
519 my($exportnum,$vendor_pkg_id);
520 while ( ($exportnum,$vendor_pkg_id)
521 = each %{$options->{'part_pkg_vendor'}} ) {
523 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
524 if($exportnum == $part_pkg_vendor->exportnum
525 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
526 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
527 my $error = $part_pkg_vendor->replace;
529 $dbh->rollback if $oldAutoCommit;
530 return "Error replacing part_pkg_vendor record: $error";
535 elsif($exportnum == $part_pkg_vendor->exportnum
536 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
541 unless ( $noinsert ) {
542 my $ppv = new FS::part_pkg_vendor( {
543 'pkgpart' => $new->pkgpart,
544 'exportnum' => $exportnum,
545 'vendor_pkg_id' => $vendor_pkg_id,
547 my $error = $ppv->insert;
549 $dbh->rollback if $oldAutoCommit;
550 return "Error inserting part_pkg_vendor record: $error";
553 push @current_exportnum, $exportnum;
556 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
557 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
558 my $error = $part_pkg_vendor->delete;
560 $dbh->rollback if $oldAutoCommit;
561 return "Error deleting part_pkg_vendor record: $error";
566 # propagate changes to certain core fields
567 if ( $conf->exists('part_pkg-lineage') ) {
568 warn " propagating changes to family" if $DEBUG;
569 my $error = $new->propagate($old);
571 $dbh->rollback if $oldAutoCommit;
576 if ( $options->{fcc_options} ) {
577 warn " updating fcc options " if $DEBUG;
578 $new->set_fcc_options( $options->{fcc_options} );
581 warn " committing transaction" if $DEBUG and $oldAutoCommit;
582 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
588 Checks all fields to make sure this is a valid package definition. If
589 there is an error, returns the error, otherwise returns false. Called by the
590 insert and replace methods.
596 warn "FS::part_pkg::check called on $self" if $DEBUG;
598 for (qw(setup recur plandata)) {
599 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
600 return "Use of $_ field is deprecated; set a plan and options: ".
602 if length($self->get($_));
606 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
607 my $error = $self->ut_number('freq');
608 return $error if $error;
610 $self->freq =~ /^(\d+[hdw]?)$/
611 or return "Illegal or empty freq: ". $self->freq;
615 my @null_agentnum_right = ( 'Edit global package definitions' );
616 push @null_agentnum_right, 'One-time charge'
617 if $self->freq =~ /^0/;
618 push @null_agentnum_right, 'Customize customer package'
619 if $self->disabled eq 'Y'; #good enough
621 my $error = $self->ut_numbern('pkgpart')
622 || $self->ut_text('pkg')
623 || $self->ut_textn('comment')
624 || $self->ut_textn('promo_code')
625 || $self->ut_alphan('plan')
626 || $self->ut_flag('setuptax')
627 || $self->ut_flag('recurtax')
628 || $self->ut_textn('taxclass')
629 || $self->ut_flag('disabled')
630 || $self->ut_flag('custom')
631 || $self->ut_flag('no_auto')
632 || $self->ut_flag('recur_show_zero')
633 || $self->ut_flag('setup_show_zero')
634 || $self->ut_flag('start_on_hold')
635 #|| $self->ut_moneyn('setup_cost')
636 #|| $self->ut_moneyn('recur_cost')
637 || $self->ut_floatn('setup_cost')
638 || $self->ut_floatn('recur_cost')
639 || $self->ut_floatn('pay_weight')
640 || $self->ut_floatn('credit_weight')
641 || $self->ut_numbern('taxproductnum')
642 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
643 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
644 || $self->ut_foreign_keyn('taxproductnum',
645 'part_pkg_taxproduct',
649 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
650 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
652 || $self->ut_numbern('fcc_ds0s')
653 || $self->ut_numbern('fcc_voip_class')
654 || $self->ut_numbern('delay_start')
655 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
656 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
657 || $self->ut_alphan('agent_pkgpartid')
658 || $self->SUPER::check
660 return $error if $error;
662 return 'Unknown plan '. $self->plan
663 unless exists($plans{$self->plan});
665 my $conf = new FS::Conf;
666 return 'Taxclass is required'
667 if ! $self->taxclass && $conf->exists('require_taxclasses');
674 For a passed I<$options> hashref, validates any options that
675 have 'validate' subroutines defined (I<$options> values might
676 be altered.) Returns error message, or empty string if valid.
678 Invoked by L</insert> and L</replace> via the equivalent
679 methods in L<FS::option_Common>.
684 my ($self,$options) = @_;
685 foreach my $option (keys %$options) {
686 if (exists $plans{ $self->plan }->{fields}->{$option}) {
687 if (exists($plans{$self->plan}->{fields}->{$option}->{'validate'})) {
688 # pass option name for use in error message
689 # pass a reference to the $options value, so it can be cleaned up
690 my $error = &{$plans{$self->plan}->{fields}->{$option}->{'validate'}}($option,\($options->{$option}));
691 return $error if $error;
693 } # else "option does not exist" error?
698 =item supersede OLD [, OPTION => VALUE ... ]
700 Inserts this package as a successor to the package OLD. All options are as
701 for C<insert>. After inserting, disables OLD and sets the new package as its
707 my ($new, $old, %options) = @_;
710 $new->set('pkgpart' => '');
711 $new->set('family_pkgpart' => $old->family_pkgpart);
712 warn " inserting successor package\n" if $DEBUG;
713 $error = $new->insert(%options);
714 return $error if $error;
716 warn " disabling superseded package\n" if $DEBUG;
717 $old->set('successor' => $new->pkgpart);
718 $old->set('disabled' => 'Y');
719 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
720 return $error if $error;
722 warn " propagating changes to family" if $DEBUG;
723 $new->propagate($old);
728 If any of certain fields have changed from OLD to this package, then,
729 for all packages in the same lineage as this one, sets those fields
730 to their values in this package.
734 my @propagate_fields = (
735 qw( pkg classnum setup_cost recur_cost taxclass
736 setuptax recurtax pay_weight credit_weight
744 map { $_ => $new->get($_) }
745 grep { $new->get($_) ne $old->get($_) }
749 my @part_pkg = qsearch('part_pkg', {
750 'family_pkgpart' => $new->family_pkgpart
753 foreach my $part_pkg ( @part_pkg ) {
754 my $pkgpart = $part_pkg->pkgpart;
755 next if $pkgpart == $new->pkgpart; # don't modify $new
756 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
757 foreach ( keys %fields ) {
758 $part_pkg->set($_, $fields{$_});
760 # SUPER::replace to avoid changing non-core fields
761 my $error = $part_pkg->SUPER::replace;
762 push @error, "pkgpart $pkgpart: $error"
768 =item set_fcc_options HASHREF
770 Sets the FCC options on this package definition to the values specified
775 sub set_fcc_options {
777 my $pkgpart = $self->pkgpart;
785 my %existing_num = map { $_->fccoptionname => $_->num }
786 qsearch('part_pkg_fcc_option', { pkgpart => $pkgpart });
788 local $FS::Record::nowarn_identical = 1;
789 # set up params for process_o2m
792 foreach my $name (keys %$options ) {
793 $params->{ "num$i" } = $existing_num{$name} || '';
794 $params->{ "num$i".'_fccoptionname' } = $name;
795 $params->{ "num$i".'_optionvalue' } = $options->{$name};
800 table => 'part_pkg_fcc_option',
801 fields => [qw( fccoptionname optionvalue )],
806 =item pkg_locale LOCALE
808 Returns a customer-viewable string representing this package for the given
809 locale, from the part_pkg_msgcat table. If the given locale is empty or no
810 localized string is found, returns the base pkg field.
815 my( $self, $locale ) = @_;
816 return $self->pkg unless $locale;
817 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
818 $part_pkg_msgcat->pkg;
821 =item part_pkg_msgcat LOCALE
823 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
827 sub part_pkg_msgcat {
828 my( $self, $locale ) = @_;
829 qsearchs( 'part_pkg_msgcat', {
830 pkgpart => $self->pkgpart,
835 =item pkg_comment [ OPTION => VALUE... ]
837 Returns an (internal) string representing this package. Currently,
838 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
839 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
842 If the option nopkgpart is true then the "pkgpart: ' is omitted.
850 #$self->pkg. ' - '. $self->comment;
851 #$self->pkg. ' ('. $self->comment. ')';
852 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
853 my $custom_comment = $self->custom_comment(%opt);
854 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
857 #without price info (so without hitting the DB again)
858 sub pkg_comment_only {
862 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
863 my $comment = $self->comment;
864 $pre. $self->pkg. ( $comment ? " - $comment" : '' );
867 sub price_info { # safety, in case a part_pkg hasn't defined price_info
873 my $price_info = $self->price_info(@_);
874 ( $self->custom ? '(CUSTOM) ' : '' ).
876 ( ( ($self->custom || $self->comment) && $price_info ) ? ' - ' : '' ).
882 $self->pkg. ' - '. ($self->price_info || 'No charge');
887 Returns the package class, as an FS::pkg_class object, or the empty string
888 if there is no package class.
894 if ( $self->classnum ) {
895 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
901 =item addon_pkg_class
903 Returns the add-on package class, as an FS::pkg_class object, or the empty
904 string if there is no add-on package class.
908 sub addon_pkg_class {
910 if ( $self->addon_classnum ) {
911 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
919 Returns the package category name, or the empty string if there is no package
926 my $pkg_class = $self->pkg_class;
928 ? $pkg_class->categoryname
934 Returns the package class name, or the empty string if there is no package
941 my $pkg_class = $self->pkg_class;
943 ? $pkg_class->classname
947 =item addon_classname
949 Returns the add-on package class name, or the empty string if there is no
950 add-on package class.
954 sub addon_classname {
956 my $pkg_class = $self->addon_pkg_class;
958 ? $pkg_class->classname
964 Returns the associated agent for this event, if any, as an FS::agent object.
970 qsearchs('agent', { 'agentnum' => $self->agentnum } );
973 =item pkg_svc [ HASHREF | OPTION => VALUE ]
975 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
976 definition (with non-zero quantity).
978 One option is available, I<disable_linked>. If set true it will return the
979 services for this package definition alone, omitting services from any add-on
986 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
993 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
999 return @{ $cache_pkg_svc{$self->pkgpart} }
1000 if $cache_enabled && $cache_pkg_svc{$self->pkgpart};
1002 # #sort { $b->primary cmp $a->primary }
1003 # grep { $_->quantity }
1004 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
1006 my $opt = ref($_[0]) ? $_[0] : { @_ };
1007 my %pkg_svc = map { $_->svcpart => $_ } $self->_pkg_svc;
1009 unless ( $opt->{disable_linked} ) {
1010 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
1011 my @pkg_svc = $dst_pkg->_pkg_svc;
1012 foreach my $pkg_svc ( @pkg_svc ) {
1013 if ( $pkg_svc{$pkg_svc->svcpart} ) {
1014 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
1015 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
1017 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
1023 my @pkg_svc = values(%pkg_svc);
1025 $cache_pkg_svc{$self->pkgpart} = \@pkg_svc if $cache_enabled;
1033 grep { $_->quantity }
1035 'select' => 'pkg_svc.*, part_svc.*',
1036 'table' => 'pkg_svc',
1037 'addl_from' => 'LEFT JOIN part_svc USING ( svcpart )',
1038 'hashref' => { 'pkgpart' => $self->pkgpart },
1042 =item svcpart [ SVCDB ]
1044 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
1045 associated with this package definition (see L<FS::pkg_svc>). Returns
1046 false if there not a primary service definition or exactly one service
1047 definition with quantity 1, or if SVCDB is specified and does not match the
1048 svcdb of the service definition. SVCDB can be specified as a scalar table
1049 name, such as 'svc_acct', or as an arrayref of possible table names.
1054 my $pkg_svc = shift->_primary_pkg_svc(@_);
1055 $pkg_svc ? $pkg_svc->svcpart : '';
1058 =item part_svc [ SVCDB ]
1060 Like the B<svcpart> method, but returns the FS::part_svc object (see
1066 my $pkg_svc = shift->_primary_pkg_svc(@_);
1067 $pkg_svc ? $pkg_svc->part_svc : '';
1070 sub _primary_pkg_svc {
1073 my $svcdb = scalar(@_) ? shift : [];
1074 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1075 my %svcdb = map { $_=>1 } @$svcdb;
1078 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1081 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1082 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1084 return '' if scalar(@pkg_svc) != 1;
1088 =item svcpart_unique_svcdb SVCDB
1090 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1091 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1092 false if there not a primary service definition for SVCDB or there are multiple
1093 service definitions for SVCDB.
1097 sub svcpart_unique_svcdb {
1098 my( $self, $svcdb ) = @_;
1099 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1100 return '' if scalar(@svcdb_pkg_svc) != 1;
1101 $svcdb_pkg_svc[0]->svcpart;
1106 Returns a list of the acceptable payment types for this package. Eventually
1107 this should come out of a database table and be editable, but currently has the
1108 following logic instead:
1110 If the package is free, the single item B<BILL> is
1111 returned, otherwise, the single item B<CARD> is returned.
1113 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1119 if ( $self->is_free ) {
1128 Returns true if this package is free.
1134 if ( $self->can('is_free_options') ) {
1135 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1136 map { $self->option($_) }
1137 $self->is_free_options;
1139 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1140 "provides neither is_free_options nor is_free method; returning false";
1145 # whether the plan allows discounts to be applied to this package
1146 sub can_discount { 0; }
1148 # whether the plan allows changing the start date
1149 sub can_start_date {
1151 $self->start_on_hold ? 0 : 1;
1154 # the delay start date if present
1155 sub delay_start_date {
1158 my $delay = $self->delay_start or return '';
1160 # avoid timelocal silliness
1161 my $dt = DateTime->today(time_zone => 'local');
1162 $dt->add(days => $delay);
1167 # moved to FS::Misc to make this accessible to other packages
1169 FS::Misc::pkg_freqs();
1174 Returns an english representation of the I<freq> field, such as "monthly",
1175 "weekly", "semi-annually", etc.
1181 my $freq = $self->freq;
1183 #my $freqs_href = $self->freqs_href;
1184 my $freqs_href = freqs_href();
1186 if ( exists($freqs_href->{$freq}) ) {
1187 $freqs_href->{$freq};
1189 my $interval = 'month';
1190 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1191 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1192 $interval = $interval{$2};
1197 "every $freq ${interval}s";
1202 =item add_freq TIMESTAMP [ FREQ ]
1204 Adds a billing period of some frequency to the provided timestamp and
1205 returns the resulting timestamp, or -1 if the frequency could not be
1206 parsed (shouldn't happen). By default, the frequency of this package
1207 will be used; to override this, pass a different frequency as a second
1213 my( $self, $date, $freq ) = @_;
1214 $freq = $self->freq unless $freq;
1216 #change this bit to use Date::Manip? CAREFUL with timezones (see
1217 # mailing list archive)
1218 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1220 if ( $freq =~ /^\d+$/ ) {
1222 until ( $mon < 12 ) { $mon -= 12; $year++; }
1224 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1226 } elsif ( $freq =~ /^(\d+)w$/ ) {
1228 $mday += $weeks * 7;
1229 } elsif ( $freq =~ /^(\d+)d$/ ) {
1232 } elsif ( $freq =~ /^(\d+)h$/ ) {
1239 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1244 For backwards compatibility, returns the plandata field as well as all options
1245 from FS::part_pkg_option.
1251 carp "plandata is deprecated";
1253 $self->SUPER::plandata(@_);
1255 my $plandata = $self->get('plandata');
1256 my %options = $self->options;
1257 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1262 =item part_pkg_vendor
1264 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1265 L<FS::part_pkg_vendor>).
1269 sub part_pkg_vendor {
1271 qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1274 =item vendor_pkg_ids
1276 Returns a list of vendor/external package ids by exportnum
1280 sub vendor_pkg_ids {
1282 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1285 =item part_pkg_option
1287 Returns all options as FS::part_pkg_option objects (see
1288 L<FS::part_pkg_option>).
1292 sub part_pkg_option {
1294 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1299 Returns a list of option names and values suitable for assigning to a hash.
1305 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1308 =item option OPTIONNAME [ QUIET ]
1310 Returns the option value for the given name, or the empty string. If a true
1311 value is passed as the second argument, warnings about missing the option
1317 my( $self, $opt, $ornull ) = @_;
1319 #cache: was pulled up in the original part_pkg query
1320 return $self->hashref->{"_opt_$opt"}
1321 if exists $self->hashref->{"_opt_$opt"};
1323 cluck "$self -> option: searching for $opt" if $DEBUG;
1324 my $part_pkg_option =
1325 qsearchs('part_pkg_option', {
1326 pkgpart => $self->pkgpart,
1329 return $part_pkg_option->optionvalue if $part_pkg_option;
1331 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1332 split("\n", $self->get('plandata') );
1333 return $plandata{$opt} if exists $plandata{$opt};
1334 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1335 "not found in options or plandata!\n"
1341 =item fcc_option OPTIONNAME
1343 Returns the FCC 477 report option value for the given name, or the empty
1349 my ($self, $name) = @_;
1350 my $part_pkg_fcc_option =
1351 qsearchs('part_pkg_fcc_option', {
1352 pkgpart => $self->pkgpart,
1353 fccoptionname => $name,
1355 $part_pkg_fcc_option ? $part_pkg_fcc_option->optionvalue : '';
1360 Returns all FCC 477 report options for this package, as a hash-like list.
1366 map { $_->fccoptionname => $_->optionvalue }
1367 qsearch('part_pkg_fcc_option', { pkgpart => $self->pkgpart });
1370 =item bill_part_pkg_link
1372 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1376 sub bill_part_pkg_link {
1377 shift->_part_pkg_link('bill', @_);
1380 =item svc_part_pkg_link
1382 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1386 sub svc_part_pkg_link {
1387 shift->_part_pkg_link('svc', @_);
1390 =item supp_part_pkg_link
1392 Returns the associated part_pkg_link records of type 'supp' (supplemental
1397 sub supp_part_pkg_link {
1398 shift->_part_pkg_link('supp', @_);
1401 sub _part_pkg_link {
1402 my( $self, $type ) = @_;
1404 return @{ $cache_link{$type}->{$self->pkgpart} }
1405 if $cache_enabled && $cache_link{$type}->{$self->pkgpart};
1407 cluck $type.'_part_pkg_link called' if $DEBUG;
1410 qsearch({ table => 'part_pkg_link',
1411 hashref => { src_pkgpart => $self->pkgpart,
1413 #protection against infinite recursive links
1414 dst_pkgpart => { op=>'!=', value=> $self->pkgpart },
1416 order_by => "ORDER BY hidden",
1419 $cache_link{$type}->{$self->pkgpart} = \@ppl if $cache_enabled;
1424 sub self_and_bill_linked {
1425 shift->_self_and_linked('bill', @_);
1428 sub self_and_svc_linked {
1429 shift->_self_and_linked('svc', @_);
1432 sub _self_and_linked {
1433 my( $self, $type, $hidden ) = @_;
1437 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1438 $self->_part_pkg_link($type) ) )
1440 $_->hidden($hidden) if $hidden;
1447 =item part_pkg_taxoverride [ CLASS ]
1449 Returns all associated FS::part_pkg_taxoverride objects (see
1450 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1451 of class CLASS if defined. Class may be one of 'setup', 'recur',
1452 the empty string (default), or a usage class number (see L<FS::usage_class>).
1453 When a class is specified, the empty string class (default) is returned
1454 if no more specific values exist.
1458 sub part_pkg_taxoverride {
1462 my $hashref = { 'pkgpart' => $self->pkgpart };
1463 $hashref->{'usage_class'} = $class if defined($class);
1464 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1466 unless ( scalar(@overrides) || !defined($class) || !$class ){
1467 $hashref->{'usage_class'} = '';
1468 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1474 =item has_taxproduct
1476 Returns true if this package has any taxproduct associated with it.
1480 sub has_taxproduct {
1483 $self->taxproductnum ||
1484 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1485 keys %{ {$self->options} }
1491 =item taxproduct [ CLASS ]
1493 Returns the associated tax product for this package definition (see
1494 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1495 the usage classnum (see L<FS::usage_class>). Returns the default
1496 tax product for this record if the more specific CLASS value does
1505 my $part_pkg_taxproduct;
1507 my $taxproductnum = $self->taxproductnum;
1509 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1510 $taxproductnum = $class_taxproductnum
1511 if $class_taxproductnum
1514 $part_pkg_taxproduct =
1515 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1517 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1518 $taxproductnum = $self->taxproductnum;
1519 $part_pkg_taxproduct =
1520 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1523 $part_pkg_taxproduct;
1526 =item taxproduct_description [ CLASS ]
1528 Returns the description of the associated tax product for this package
1529 definition (see L<FS::part_pkg_taxproduct>).
1533 sub taxproduct_description {
1535 my $part_pkg_taxproduct = $self->taxproduct(@_);
1536 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1540 =item tax_rates DATA_PROVIDER, GEOCODE, [ CLASS ]
1542 Returns the tax table entries (L<FS::tax_rate> objects) that apply to this
1543 package in the location specified by GEOCODE, for usage class CLASS (one of
1544 'setup', 'recur', null, or a C<usage_class> number).
1550 my ($vendor, $geocode, $class) = @_;
1551 # if this part_pkg is overridden into a specific taxclass, get that class
1552 my @taxclassnums = map { $_->taxclassnum }
1553 $self->part_pkg_taxoverride($class);
1554 # otherwise, get its tax product category
1555 if (!@taxclassnums) {
1556 my $part_pkg_taxproduct = $self->taxproduct($class);
1557 # If this isn't defined, then the class has no taxproduct designation,
1558 # so return no tax rates.
1559 return () if !$part_pkg_taxproduct;
1561 # convert the taxproduct to the tax classes that might apply to it in
1563 @taxclassnums = map { $_->taxclassnum }
1564 grep { $_->taxable eq 'Y' } # why do we need this?
1565 $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1567 return unless @taxclassnums;
1569 # then look up the actual tax_rate entries
1570 warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1572 my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1573 my @taxes = qsearch({ 'table' => 'tax_rate',
1574 'hashref' => { 'geocode' => $geocode,
1575 'data_vendor' => $vendor,
1577 'extra_sql' => $extra_sql,
1579 warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1585 =item part_pkg_discount
1587 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1592 sub part_pkg_discount {
1594 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1597 =item part_pkg_usage
1599 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1604 sub part_pkg_usage {
1606 qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1611 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1612 PLAN is the object's I<plan> field. There should be better docs
1613 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1619 my $plan = $self->plan;
1621 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1625 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1626 my $class = ref($self). "::$plan";
1627 warn "reblessing $self into $class" if $DEBUG > 1;
1630 bless($self, $class) unless $@;
1635 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1636 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1638 #fallback that return 0 for old legacy packages with no plan
1639 sub calc_remain { 0; }
1640 sub calc_units { 0; }
1642 #fallback for everything not based on flat.pm
1643 sub recur_temporality { 'upcoming'; }
1644 sub calc_cancel { 0; }
1646 #fallback for everything except bulk.pm
1647 sub hide_svc_detail { 0; }
1649 #fallback for packages that can't/won't summarize usage
1650 sub sum_usage { 0; }
1652 =item recur_cost_permonth CUST_PKG
1654 recur_cost divided by freq (only supported for monthly and longer frequencies)
1658 sub recur_cost_permonth {
1659 my($self, $cust_pkg) = @_;
1660 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1661 sprintf('%.2f', ($self->recur_cost || 0) / $self->freq );
1664 =item cust_bill_pkg_recur CUST_PKG
1666 Actual recurring charge for the specified customer package from customer's most
1671 sub cust_bill_pkg_recur {
1672 my($self, $cust_pkg) = @_;
1673 my $cust_bill_pkg = qsearchs({
1674 'table' => 'cust_bill_pkg',
1675 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1676 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1677 'recur' => { op=>'>', value=>'0' },
1679 'order_by' => 'ORDER BY cust_bill._date DESC,
1680 cust_bill_pkg.sdate DESC
1683 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1684 $cust_bill_pkg->recur;
1687 =item unit_setup CUST_PKG
1689 Returns the setup fee for one unit of the package.
1694 my ($self, $cust_pkg) = @_;
1695 $self->option('setup_fee') || 0;
1700 unit_setup minus setup_cost
1706 $self->unit_setup(@_) - ($self->setup_cost || 0);
1709 =item recur_margin_permonth
1711 base_recur_permonth minus recur_cost_permonth
1715 sub recur_margin_permonth {
1717 $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1720 =item format OPTION DATA
1722 Returns data formatted according to the function 'format' described
1723 in the plan info. Returns DATA if no such function exists.
1728 my ($self, $option, $data) = (shift, shift, shift);
1729 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1730 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1736 =item parse OPTION DATA
1738 Returns data parsed according to the function 'parse' described
1739 in the plan info. Returns DATA if no such function exists.
1744 my ($self, $option, $data) = (shift, shift, shift);
1745 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1746 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1756 =head1 CLASS METHODS
1764 # Used by FS::Upgrade to migrate to a new database.
1766 sub _upgrade_data { # class method
1767 my($class, %opts) = @_;
1769 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1771 my @part_pkg = qsearch({
1772 'table' => 'part_pkg',
1773 'extra_sql' => "WHERE ". join(' OR ',
1774 'plan IS NULL', "plan = '' ",
1778 foreach my $part_pkg (@part_pkg) {
1780 unless ( $part_pkg->plan ) {
1781 $part_pkg->plan('flat');
1787 # the rest can be done asynchronously
1790 sub queueable_upgrade {
1791 # now upgrade to the explicit custom flag
1793 my $search = FS::Cursor->new({
1794 'table' => 'part_pkg',
1795 'hashref' => { disabled => 'Y', custom => '' },
1796 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1800 while (my $part_pkg = $search->fetch) {
1801 my $new = new FS::part_pkg { $part_pkg->hash };
1803 my $comment = $part_pkg->comment;
1804 $comment =~ s/^\(CUSTOM\) //;
1805 $comment = '(none)' unless $comment =~ /\S/;
1806 $new->comment($comment);
1808 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1809 my $primary = $part_pkg->svcpart;
1810 my $options = { $part_pkg->options };
1812 my $error = $new->replace( $part_pkg,
1813 'pkg_svc' => $pkg_svc,
1814 'primary_svc' => $primary,
1815 'options' => $options,
1818 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1825 # set family_pkgpart on any packages that don't have it
1826 $search = FS::Cursor->new('part_pkg', { 'family_pkgpart' => '' });
1827 while (my $part_pkg = $search->fetch) {
1828 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1829 my $error = $part_pkg->SUPER::replace;
1831 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1838 my @part_pkg_option = qsearch('part_pkg_option',
1839 { 'optionname' => 'unused_credit',
1842 foreach my $old_opt (@part_pkg_option) {
1843 my $pkgpart = $old_opt->pkgpart;
1844 my $error = $old_opt->delete;
1845 die $error if $error;
1847 foreach (qw(unused_credit_cancel unused_credit_change)) {
1848 my $new_opt = new FS::part_pkg_option {
1849 'pkgpart' => $pkgpart,
1853 $error = $new_opt->insert;
1854 die $error if $error;
1858 # migrate use_disposition_taqua and use_disposition to disposition_in
1859 @part_pkg_option = qsearch('part_pkg_option',
1860 { 'optionname' => { op => 'LIKE',
1861 value => 'use_disposition%',
1865 my %newopts = map { $_->pkgpart => $_ }
1866 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1867 foreach my $old_opt (@part_pkg_option) {
1868 my $pkgpart = $old_opt->pkgpart;
1869 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1871 my $error = $old_opt->delete;
1872 die $error if $error;
1874 if ( exists($newopts{$pkgpart}) ) {
1875 my $opt = $newopts{$pkgpart};
1876 $opt->optionvalue($opt->optionvalue.",$newval");
1877 $error = $opt->replace;
1878 die $error if $error;
1880 my $new_opt = new FS::part_pkg_option {
1881 'pkgpart' => $pkgpart,
1882 'optionname' => 'disposition_in',
1883 'optionvalue' => $newval,
1885 $error = $new_opt->insert;
1886 die $error if $error;
1887 $newopts{$pkgpart} = $new_opt;
1891 # set any package with FCC voice lines to the "VoIP with broadband" category
1892 # for backward compatibility
1894 # recover from a bad upgrade bug
1895 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1896 if (!FS::upgrade_journal->is_done($upgrade)) {
1897 my $bad_upgrade = qsearchs('upgrade_journal',
1898 { upgrade => 'part_pkg_fcc_voip_class' }
1900 if ( $bad_upgrade ) {
1901 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1902 ' AND history_date > '.($bad_upgrade->_date - 3600);
1903 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1906 'table' => 'h_part_pkg_option',
1908 'extra_sql' => "$where AND history_action = 'delete'",
1909 'order_by' => 'ORDER BY history_date ASC',
1911 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1914 'table' => 'h_pkg_svc',
1916 'extra_sql' => "$where AND history_action = 'replace_old'",
1917 'order_by' => 'ORDER BY history_date ASC',
1920 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1921 my $pkgpart ||= $deleted->pkgpart;
1922 $opt{$pkgpart} ||= {
1928 if ( $deleted->isa('FS::part_pkg_option') ) {
1929 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1931 my $svcpart = $deleted->svcpart;
1932 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1933 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1934 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1937 foreach my $pkgpart (keys %opt) {
1938 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1939 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1941 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1944 } # $bad_upgrade exists
1945 else { # do the original upgrade, but correctly this time
1946 my @part_pkg = qsearch('part_pkg', {
1947 fcc_ds0s => { op => '>', value => 0 },
1948 fcc_voip_class => ''
1950 foreach my $part_pkg (@part_pkg) {
1951 $part_pkg->set(fcc_voip_class => 2);
1952 my @pkg_svc = $part_pkg->pkg_svc;
1953 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1954 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1955 my $error = $part_pkg->replace(
1956 $part_pkg->replace_old,
1957 options => { $part_pkg->options },
1958 pkg_svc => \%quantity,
1959 hidden_svc => \%hidden,
1960 primary_svc => ($part_pkg->svcpart || ''),
1962 die $error if $error;
1965 FS::upgrade_journal->set_done($upgrade);
1970 =item curuser_pkgs_sql
1972 Returns an SQL fragment for searching for packages the current user can
1973 use, either via part_pkg.agentnum directly, or via agent type (see
1978 sub curuser_pkgs_sql {
1981 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1985 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1987 Returns an SQL fragment for searching for packages the provided agent or agents
1988 can use, either via part_pkg.agentnum directly, or via agent type (see
1993 sub agent_pkgs_sql {
1994 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1995 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1997 $class->_pkgs_sql(@agentnums); #is this why
2002 my( $class, @agentnums ) = @_;
2003 my $agentnums = join(',', @agentnums);
2007 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
2008 OR ( agentnum IS NULL
2009 AND EXISTS ( SELECT 1
2011 LEFT JOIN agent_type USING ( typenum )
2012 LEFT JOIN agent AS typeagent USING ( typenum )
2013 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
2014 AND typeagent.agentnum IN ($agentnums)
2032 #false laziness w/part_export & cdr
2034 foreach my $INC ( @INC ) {
2035 warn "globbing $INC/FS/part_pkg/[a-z]*.pm\n" if $DEBUG;
2036 foreach my $file ( glob("$INC/FS/part_pkg/[a-z]*.pm") ) {
2037 warn "attempting to load plan info from $file\n" if $DEBUG;
2038 $file =~ /\/(\w+)\.pm$/ or do {
2039 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
2043 my $info = eval "use FS::part_pkg::$mod; ".
2044 "\\%FS::part_pkg::$mod\::info;";
2046 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
2049 unless ( keys %$info ) {
2050 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
2053 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
2054 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
2055 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
2058 $info{$mod} = $info;
2059 $info->{'weight'} ||= 0; # quiet warnings
2063 # copy one level deep to allow replacement of fields and fieldorder
2064 tie %plans, 'Tie::IxHash',
2065 map { my %infohash = %{ $info{$_} };
2067 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
2070 # inheritance of plan options
2071 foreach my $name (keys(%info)) {
2072 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
2073 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
2074 delete $plans{$name};
2077 my $parents = $info{$name}->{'inherit_fields'} || [];
2078 my (%fields, %field_exists, @fieldorder);
2079 foreach my $parent ($name, @$parents) {
2080 if ( !exists($info{$parent}) ) {
2081 warn "$name tried to inherit from nonexistent '$parent'\n";
2084 %fields = ( # avoid replacing existing fields
2085 %{ $info{$parent}->{'fields'} || {} },
2088 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2090 next if $field_exists{$_};
2091 $field_exists{$_} = 1;
2092 # allow inheritors to remove inherited fields from the fieldorder
2093 push @fieldorder, $_ if !exists($fields{$_}) or
2094 !exists($fields{$_}->{'disabled'});
2097 $plans{$name}->{'fields'} = \%fields;
2098 $plans{$name}->{'fieldorder'} = \@fieldorder;
2108 =head1 NEW PLAN CLASSES
2110 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2111 found in eg/plan_template.pm. Until then, it is suggested that you use the
2112 other modules in FS/FS/part_pkg/ as a guide.
2116 The delete method is unimplemented.
2118 setup and recur semantics are not yet defined (and are implemented in
2119 FS::cust_bill. hmm.). now they're deprecated and need to go.
2123 part_pkg_taxrate is Pg specific
2125 replace should be smarter about managing the related tables (options, pkg_svc)
2129 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2130 schema.html from the base documentation.