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 use Carp qw(carp cluck confess);
7 use Scalar::Util qw( blessed );
9 use Time::Local qw( timelocal timelocal_nocheck ); # eventually replace with DateTime
12 use FS::Record qw( qsearch qsearchs dbh dbdef );
13 use FS::Cursor; # for upgrade
19 use FS::part_pkg_option;
20 use FS::part_pkg_fcc_option;
23 use FS::part_pkg_msgcat;
24 use FS::part_pkg_taxrate;
25 use FS::part_pkg_taxoverride;
26 use FS::part_pkg_taxproduct;
27 use FS::part_pkg_link;
28 use FS::part_pkg_discount;
29 use FS::part_pkg_usage;
30 use FS::part_pkg_vendor;
34 $skip_pkg_svc_hack = 0;
38 FS::part_pkg - Object methods for part_pkg objects
44 $record = new FS::part_pkg \%hash
45 $record = new FS::part_pkg { 'column' => 'value' };
47 $custom_record = $template_record->clone;
49 $error = $record->insert;
51 $error = $new_record->replace($old_record);
53 $error = $record->delete;
55 $error = $record->check;
57 @pkg_svc = $record->pkg_svc;
59 $svcnum = $record->svcpart;
60 $svcnum = $record->svcpart( 'svc_acct' );
64 An FS::part_pkg object represents a package definition. FS::part_pkg
65 inherits from FS::Record. The following fields are currently supported:
69 =item pkgpart - primary key (assigned automatically for new package definitions)
71 =item pkg - Text name of this package definition (customer-viewable)
73 =item comment - Text name of this package definition (non-customer-viewable)
75 =item classnum - Optional package class (see L<FS::pkg_class>)
77 =item promo_code - Promotional code
79 =item setup - Setup fee expression (deprecated)
81 =item freq - Frequency of recurring fee
83 =item recur - Recurring fee expression (deprecated)
85 =item setuptax - Setup fee tax exempt flag, empty or `Y'
87 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
89 =item taxclass - Tax class
91 =item plan - Price plan
93 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
95 =item disabled - Disabled flag, empty or `Y'
97 =item custom - Custom flag, empty or `Y'
99 =item setup_cost - for cost tracking
101 =item recur_cost - for cost tracking
103 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
105 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
107 =item agentnum - Optional agentnum (see L<FS::agent>)
109 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
111 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
114 =item successor - Foreign key for the part_pkg that replaced this record.
115 If this record is not obsolete, will be null.
117 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
118 ancestor of this record. If this record is not a successor to another
119 part_pkg, will be equal to pkgpart.
121 =item delay_start - Number of days to delay package start, by default
131 Creates a new package definition. To add the package definition to
132 the database, see L<"insert">.
136 sub table { 'part_pkg'; }
140 An alternate constructor. Creates a new package definition by duplicating
141 an existing definition. A new pkgpart is assigned and the custom flag is
142 set to Y. To add the package definition to the database, see L<"insert">.
148 my $class = ref($self);
149 my %hash = $self->hash;
150 $hash{'pkgpart'} = '';
151 $hash{'custom'} = 'Y';
152 #new FS::part_pkg ( \%hash ); # ?
153 new $class ( \%hash ); # ?
156 =item insert [ , OPTION => VALUE ... ]
158 Adds this package definition to the database. If there is an error,
159 returns the error, otherwise returns false.
161 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
162 I<custnum_ref> and I<options>.
164 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
165 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
166 be set to a hashref of svcparts and flag values ('Y' or '') to set the
167 'hidden' field in these records.
169 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
170 FS::pkg_svc record will be updated.
172 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
173 record itself), the object will be updated to point to this package definition.
175 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
176 the scalar will be updated with the custnum value from the cust_pkg record.
178 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
179 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
180 records will be inserted.
182 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
183 records will be inserted.
190 warn "FS::part_pkg::insert called on $self with options ".
191 join(', ', map "$_=>$options{$_}", keys %options)
194 local $SIG{HUP} = 'IGNORE';
195 local $SIG{INT} = 'IGNORE';
196 local $SIG{QUIT} = 'IGNORE';
197 local $SIG{TERM} = 'IGNORE';
198 local $SIG{TSTP} = 'IGNORE';
199 local $SIG{PIPE} = 'IGNORE';
201 my $oldAutoCommit = $FS::UID::AutoCommit;
202 local $FS::UID::AutoCommit = 0;
205 warn " inserting part_pkg record" if $DEBUG;
206 my $error = $self->SUPER::insert( $options{options} );
208 $dbh->rollback if $oldAutoCommit;
213 if ( $self->get('family_pkgpart') eq '' ) {
214 $self->set('family_pkgpart' => $self->pkgpart);
215 $error = $self->SUPER::replace;
217 $dbh->rollback if $oldAutoCommit;
222 warn " inserting part_pkg_taxoverride records" if $DEBUG;
223 my %overrides = %{ $options{'tax_overrides'} || {} };
224 foreach my $usage_class ( keys %overrides ) {
226 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
227 ? $overrides{$usage_class}
229 my @overrides = (grep "$_", split(',', $override) );
230 my $error = $self->process_m2m (
231 'link_table' => 'part_pkg_taxoverride',
232 'target_table' => 'tax_class',
233 'hashref' => { 'usage_class' => $usage_class },
234 'params' => \@overrides,
237 $dbh->rollback if $oldAutoCommit;
242 unless ( $skip_pkg_svc_hack ) {
244 warn " inserting pkg_svc records" if $DEBUG;
245 my $pkg_svc = $options{'pkg_svc'} || {};
246 my $hidden_svc = $options{'hidden_svc'} || {};
247 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
248 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
250 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
254 my $pkg_svc = new FS::pkg_svc( {
255 'pkgpart' => $self->pkgpart,
256 'svcpart' => $part_svc->svcpart,
257 'quantity' => $quantity,
258 'primary_svc' => $primary_svc,
259 'hidden' => $hidden_svc->{$part_svc->svcpart},
261 my $error = $pkg_svc->insert;
263 $dbh->rollback if $oldAutoCommit;
270 if ( $options{'cust_pkg'} ) {
271 warn " updating cust_pkg record " if $DEBUG;
273 ref($options{'cust_pkg'})
274 ? $options{'cust_pkg'}
275 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
276 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
277 if $options{'custnum_ref'};
278 my %hash = $old_cust_pkg->hash;
279 $hash{'pkgpart'} = $self->pkgpart,
280 my $new_cust_pkg = new FS::cust_pkg \%hash;
281 local($FS::cust_pkg::disable_agentcheck) = 1;
282 my $error = $new_cust_pkg->replace($old_cust_pkg);
284 $dbh->rollback if $oldAutoCommit;
285 return "Error modifying cust_pkg record: $error";
289 if ( $options{'part_pkg_vendor'} ) {
290 while ( my ($exportnum, $vendor_pkg_id) =
291 each %{ $options{part_pkg_vendor} }
294 my $ppv = new FS::part_pkg_vendor( {
295 'pkgpart' => $self->pkgpart,
296 'exportnum' => $exportnum,
297 'vendor_pkg_id' => $vendor_pkg_id,
299 my $error = $ppv->insert;
301 $dbh->rollback if $oldAutoCommit;
302 return "Error inserting part_pkg_vendor record: $error";
307 if ( $options{fcc_options} ) {
308 warn " updating fcc options " if $DEBUG;
309 $self->set_fcc_options( $options{fcc_options} );
312 warn " committing transaction" if $DEBUG and $oldAutoCommit;
313 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
320 Currently unimplemented.
325 return "Can't (yet?) delete package definitions.";
326 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
329 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
331 Replaces OLD_RECORD with this one in the database. If there is an error,
332 returns the error, otherwise returns false.
334 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
337 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
338 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
339 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
340 'hidden' field in these records.
342 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
343 FS::pkg_svc record will be updated.
345 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
353 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
358 ( ref($_[0]) eq 'HASH' )
362 $options->{options} = { $old->options } unless defined($options->{options});
364 warn "FS::part_pkg::replace called on $new to replace $old with options".
365 join(', ', map "$_ => ". $options->{$_}, keys %$options)
368 local $SIG{HUP} = 'IGNORE';
369 local $SIG{INT} = 'IGNORE';
370 local $SIG{QUIT} = 'IGNORE';
371 local $SIG{TERM} = 'IGNORE';
372 local $SIG{TSTP} = 'IGNORE';
373 local $SIG{PIPE} = 'IGNORE';
375 my $oldAutoCommit = $FS::UID::AutoCommit;
376 local $FS::UID::AutoCommit = 0;
379 my $conf = new FS::Conf;
380 if ( $conf->exists('part_pkg-lineage') ) {
381 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
382 qw(setup_fee recur_fee) #others? config?
385 warn " superseding package" if $DEBUG;
387 my $error = $new->supersede($old, %$options);
389 $dbh->rollback if $oldAutoCommit;
393 warn " committing transaction" if $DEBUG and $oldAutoCommit;
394 $dbh->commit if $oldAutoCommit;
401 #plandata shit stays in replace for upgrades until after 2.0 (or edit
403 warn " saving legacy plandata" if $DEBUG;
404 my $plandata = $new->get('plandata');
405 $new->set('plandata', '');
407 warn " deleting old part_pkg_option records" if $DEBUG;
408 foreach my $part_pkg_option ( $old->part_pkg_option ) {
409 my $error = $part_pkg_option->delete;
411 $dbh->rollback if $oldAutoCommit;
416 warn " replacing part_pkg record" if $DEBUG;
417 my $error = $new->SUPER::replace($old, $options->{options} );
419 $dbh->rollback if $oldAutoCommit;
423 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
424 foreach my $part_pkg_option (
425 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
426 return "illegal plandata: $plandata";
428 new FS::part_pkg_option {
429 'pkgpart' => $new->pkgpart,
434 split("\n", $plandata)
436 my $error = $part_pkg_option->insert;
438 $dbh->rollback if $oldAutoCommit;
443 warn " replacing pkg_svc records" if $DEBUG;
444 my $pkg_svc = $options->{'pkg_svc'};
445 my $hidden_svc = $options->{'hidden_svc'} || {};
446 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
447 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
448 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
449 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
451 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
452 && $options->{'primary_svc'} == $part_svc->svcpart
457 my $old_pkg_svc = qsearchs('pkg_svc', {
458 'pkgpart' => $old->pkgpart,
459 'svcpart' => $part_svc->svcpart,
462 my $old_quantity = 0;
463 my $old_primary_svc = '';
465 if ( $old_pkg_svc ) {
466 $old_quantity = $old_pkg_svc->quantity;
467 $old_primary_svc = $old_pkg_svc->primary_svc
468 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
469 $old_hidden = $old_pkg_svc->hidden;
472 next unless $old_quantity != $quantity ||
473 $old_primary_svc ne $primary_svc ||
474 $old_hidden ne $hidden;
476 my $new_pkg_svc = new FS::pkg_svc( {
477 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
478 'pkgpart' => $new->pkgpart,
479 'svcpart' => $part_svc->svcpart,
480 'quantity' => $quantity,
481 'primary_svc' => $primary_svc,
484 my $error = $old_pkg_svc
485 ? $new_pkg_svc->replace($old_pkg_svc)
486 : $new_pkg_svc->insert;
488 $dbh->rollback if $oldAutoCommit;
492 } #if $options->{pkg_svc}
494 my @part_pkg_vendor = $old->part_pkg_vendor;
495 my @current_exportnum = ();
496 if ( $options->{'part_pkg_vendor'} ) {
497 my($exportnum,$vendor_pkg_id);
498 while ( ($exportnum,$vendor_pkg_id)
499 = each %{$options->{'part_pkg_vendor'}} ) {
501 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
502 if($exportnum == $part_pkg_vendor->exportnum
503 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
504 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
505 my $error = $part_pkg_vendor->replace;
507 $dbh->rollback if $oldAutoCommit;
508 return "Error replacing part_pkg_vendor record: $error";
513 elsif($exportnum == $part_pkg_vendor->exportnum
514 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
519 unless ( $noinsert ) {
520 my $ppv = new FS::part_pkg_vendor( {
521 'pkgpart' => $new->pkgpart,
522 'exportnum' => $exportnum,
523 'vendor_pkg_id' => $vendor_pkg_id,
525 my $error = $ppv->insert;
527 $dbh->rollback if $oldAutoCommit;
528 return "Error inserting part_pkg_vendor record: $error";
531 push @current_exportnum, $exportnum;
534 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
535 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
536 my $error = $part_pkg_vendor->delete;
538 $dbh->rollback if $oldAutoCommit;
539 return "Error deleting part_pkg_vendor record: $error";
544 # propagate changes to certain core fields
545 if ( $conf->exists('part_pkg-lineage') ) {
546 warn " propagating changes to family" if $DEBUG;
547 my $error = $new->propagate($old);
549 $dbh->rollback if $oldAutoCommit;
554 if ( $options->{fcc_options} ) {
555 warn " updating fcc options " if $DEBUG;
556 $new->set_fcc_options( $options->{fcc_options} );
559 warn " committing transaction" if $DEBUG and $oldAutoCommit;
560 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
566 Checks all fields to make sure this is a valid package definition. If
567 there is an error, returns the error, otherwise returns false. Called by the
568 insert and replace methods.
574 warn "FS::part_pkg::check called on $self" if $DEBUG;
576 for (qw(setup recur plandata)) {
577 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
578 return "Use of $_ field is deprecated; set a plan and options: ".
580 if length($self->get($_));
584 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
585 my $error = $self->ut_number('freq');
586 return $error if $error;
588 $self->freq =~ /^(\d+[hdw]?)$/
589 or return "Illegal or empty freq: ". $self->freq;
593 my @null_agentnum_right = ( 'Edit global package definitions' );
594 push @null_agentnum_right, 'One-time charge'
595 if $self->freq =~ /^0/;
596 push @null_agentnum_right, 'Customize customer package'
597 if $self->disabled eq 'Y'; #good enough
599 my $error = $self->ut_numbern('pkgpart')
600 || $self->ut_text('pkg')
601 || $self->ut_textn('comment')
602 || $self->ut_textn('promo_code')
603 || $self->ut_alphan('plan')
604 || $self->ut_enum('setuptax', [ '', 'Y' ] )
605 || $self->ut_enum('recurtax', [ '', 'Y' ] )
606 || $self->ut_textn('taxclass')
607 || $self->ut_enum('disabled', [ '', 'Y' ] )
608 || $self->ut_enum('custom', [ '', 'Y' ] )
609 || $self->ut_enum('no_auto', [ '', 'Y' ])
610 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
611 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
612 #|| $self->ut_moneyn('setup_cost')
613 #|| $self->ut_moneyn('recur_cost')
614 || $self->ut_floatn('setup_cost')
615 || $self->ut_floatn('recur_cost')
616 || $self->ut_floatn('pay_weight')
617 || $self->ut_floatn('credit_weight')
618 || $self->ut_numbern('taxproductnum')
619 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
620 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
621 || $self->ut_foreign_keyn('taxproductnum',
622 'part_pkg_taxproduct',
626 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
627 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
629 || $self->ut_numbern('fcc_ds0s')
630 || $self->ut_numbern('fcc_voip_class')
631 || $self->ut_numbern('delay_start')
632 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
633 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
634 || $self->ut_alphan('agent_pkgpartid')
635 || $self->SUPER::check
637 return $error if $error;
639 return 'Unknown plan '. $self->plan
640 unless exists($plans{$self->plan});
642 my $conf = new FS::Conf;
643 return 'Taxclass is required'
644 if ! $self->taxclass && $conf->exists('require_taxclasses');
649 =item supersede OLD [, OPTION => VALUE ... ]
651 Inserts this package as a successor to the package OLD. All options are as
652 for C<insert>. After inserting, disables OLD and sets the new package as its
658 my ($new, $old, %options) = @_;
661 $new->set('pkgpart' => '');
662 $new->set('family_pkgpart' => $old->family_pkgpart);
663 warn " inserting successor package\n" if $DEBUG;
664 $error = $new->insert(%options);
665 return $error if $error;
667 warn " disabling superseded package\n" if $DEBUG;
668 $old->set('successor' => $new->pkgpart);
669 $old->set('disabled' => 'Y');
670 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
671 return $error if $error;
673 warn " propagating changes to family" if $DEBUG;
674 $new->propagate($old);
679 If any of certain fields have changed from OLD to this package, then,
680 for all packages in the same lineage as this one, sets those fields
681 to their values in this package.
685 my @propagate_fields = (
686 qw( pkg classnum setup_cost recur_cost taxclass
687 setuptax recurtax pay_weight credit_weight
695 map { $_ => $new->get($_) }
696 grep { $new->get($_) ne $old->get($_) }
700 my @part_pkg = qsearch('part_pkg', {
701 'family_pkgpart' => $new->family_pkgpart
704 foreach my $part_pkg ( @part_pkg ) {
705 my $pkgpart = $part_pkg->pkgpart;
706 next if $pkgpart == $new->pkgpart; # don't modify $new
707 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
708 foreach ( keys %fields ) {
709 $part_pkg->set($_, $fields{$_});
711 # SUPER::replace to avoid changing non-core fields
712 my $error = $part_pkg->SUPER::replace;
713 push @error, "pkgpart $pkgpart: $error"
719 =item set_fcc_options HASHREF
721 Sets the FCC options on this package definition to the values specified
726 sub set_fcc_options {
728 my $pkgpart = $self->pkgpart;
736 my %existing_num = map { $_->fccoptionname => $_->num }
737 qsearch('part_pkg_fcc_option', { pkgpart => $pkgpart });
739 local $FS::Record::nowarn_identical = 1;
740 # set up params for process_o2m
743 foreach my $name (keys %$options ) {
744 $params->{ "num$i" } = $existing_num{$name} || '';
745 $params->{ "num$i".'_fccoptionname' } = $name;
746 $params->{ "num$i".'_optionvalue' } = $options->{$name};
751 table => 'part_pkg_fcc_option',
752 fields => [qw( fccoptionname optionvalue )],
757 =item pkg_locale LOCALE
759 Returns a customer-viewable string representing this package for the given
760 locale, from the part_pkg_msgcat table. If the given locale is empty or no
761 localized string is found, returns the base pkg field.
766 my( $self, $locale ) = @_;
767 return $self->pkg unless $locale;
768 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
769 $part_pkg_msgcat->pkg;
772 =item part_pkg_msgcat LOCALE
774 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
778 sub part_pkg_msgcat {
779 my( $self, $locale ) = @_;
780 qsearchs( 'part_pkg_msgcat', {
781 pkgpart => $self->pkgpart,
786 =item pkg_comment [ OPTION => VALUE... ]
788 Returns an (internal) string representing this package. Currently,
789 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
790 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
793 If the option nopkgpart is true then the "pkgpart: ' is omitted.
801 #$self->pkg. ' - '. $self->comment;
802 #$self->pkg. ' ('. $self->comment. ')';
803 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
804 my $custom_comment = $self->custom_comment(%opt);
805 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
808 #without price info (so without hitting the DB again)
809 sub pkg_comment_only {
813 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
814 my $comment = $self->comment;
815 $pre. $self->pkg. ( $comment ? " - $comment" : '' );
818 sub price_info { # safety, in case a part_pkg hasn't defined price_info
824 my $price_info = $self->price_info(@_);
825 ( $self->custom ? '(CUSTOM) ' : '' ).
827 ( ( ($self->custom || $self->comment) && $price_info ) ? ' - ' : '' ).
833 $self->pkg. ' - '. ($self->price_info || 'No charge');
838 Returns the package class, as an FS::pkg_class object, or the empty string
839 if there is no package class.
845 if ( $self->classnum ) {
846 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
852 =item addon_pkg_class
854 Returns the add-on package class, as an FS::pkg_class object, or the empty
855 string if there is no add-on package class.
859 sub addon_pkg_class {
861 if ( $self->addon_classnum ) {
862 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
870 Returns the package category name, or the empty string if there is no package
877 my $pkg_class = $self->pkg_class;
879 ? $pkg_class->categoryname
885 Returns the package class name, or the empty string if there is no package
892 my $pkg_class = $self->pkg_class;
894 ? $pkg_class->classname
898 =item addon_classname
900 Returns the add-on package class name, or the empty string if there is no
901 add-on package class.
905 sub addon_classname {
907 my $pkg_class = $self->addon_pkg_class;
909 ? $pkg_class->classname
915 Returns the associated agent for this event, if any, as an FS::agent object.
921 qsearchs('agent', { 'agentnum' => $self->agentnum } );
924 =item pkg_svc [ HASHREF | OPTION => VALUE ]
926 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
927 definition (with non-zero quantity).
929 One option is available, I<disable_linked>. If set true it will return the
930 services for this package definition alone, omitting services from any add-on
937 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
944 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
950 # #sort { $b->primary cmp $a->primary }
951 # grep { $_->quantity }
952 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
954 my $opt = ref($_[0]) ? $_[0] : { @_ };
955 my %pkg_svc = map { $_->svcpart => $_ }
956 grep { $_->quantity }
957 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
959 unless ( $opt->{disable_linked} ) {
960 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
961 my @pkg_svc = grep { $_->quantity }
962 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
963 foreach my $pkg_svc ( @pkg_svc ) {
964 if ( $pkg_svc{$pkg_svc->svcpart} ) {
965 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
966 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
968 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
978 =item svcpart [ SVCDB ]
980 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
981 associated with this package definition (see L<FS::pkg_svc>). Returns
982 false if there not a primary service definition or exactly one service
983 definition with quantity 1, or if SVCDB is specified and does not match the
984 svcdb of the service definition. SVCDB can be specified as a scalar table
985 name, such as 'svc_acct', or as an arrayref of possible table names.
990 my $pkg_svc = shift->_primary_pkg_svc(@_);
991 $pkg_svc ? $pkg_svc->svcpart : '';
994 =item part_svc [ SVCDB ]
996 Like the B<svcpart> method, but returns the FS::part_svc object (see
1002 my $pkg_svc = shift->_primary_pkg_svc(@_);
1003 $pkg_svc ? $pkg_svc->part_svc : '';
1006 sub _primary_pkg_svc {
1009 my $svcdb = scalar(@_) ? shift : [];
1010 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1011 my %svcdb = map { $_=>1 } @$svcdb;
1014 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1017 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1018 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1020 return '' if scalar(@pkg_svc) != 1;
1024 =item svcpart_unique_svcdb SVCDB
1026 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1027 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1028 false if there not a primary service definition for SVCDB or there are multiple
1029 service definitions for SVCDB.
1033 sub svcpart_unique_svcdb {
1034 my( $self, $svcdb ) = @_;
1035 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1036 return '' if scalar(@svcdb_pkg_svc) != 1;
1037 $svcdb_pkg_svc[0]->svcpart;
1042 Returns a list of the acceptable payment types for this package. Eventually
1043 this should come out of a database table and be editable, but currently has the
1044 following logic instead:
1046 If the package is free, the single item B<BILL> is
1047 returned, otherwise, the single item B<CARD> is returned.
1049 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1055 if ( $self->is_free ) {
1064 Returns true if this package is free.
1070 if ( $self->can('is_free_options') ) {
1071 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1072 map { $self->option($_) }
1073 $self->is_free_options;
1075 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1076 "provides neither is_free_options nor is_free method; returning false";
1081 # whether the plan allows discounts to be applied to this package
1082 sub can_discount { 0; }
1084 # whether the plan allows changing the start date
1085 sub can_start_date { 1; }
1087 # the delay start date if present
1088 sub delay_start_date {
1091 my $delay = $self->delay_start or return '';
1093 # avoid timelocal silliness
1094 my $dt = DateTime->today(time_zone => 'local');
1095 $dt->add(days => $delay);
1100 # moved to FS::Misc to make this accessible to other packages
1102 FS::Misc::pkg_freqs();
1107 Returns an english representation of the I<freq> field, such as "monthly",
1108 "weekly", "semi-annually", etc.
1114 my $freq = $self->freq;
1116 #my $freqs_href = $self->freqs_href;
1117 my $freqs_href = freqs_href();
1119 if ( exists($freqs_href->{$freq}) ) {
1120 $freqs_href->{$freq};
1122 my $interval = 'month';
1123 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1124 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1125 $interval = $interval{$2};
1130 "every $freq ${interval}s";
1135 =item add_freq TIMESTAMP [ FREQ ]
1137 Adds a billing period of some frequency to the provided timestamp and
1138 returns the resulting timestamp, or -1 if the frequency could not be
1139 parsed (shouldn't happen). By default, the frequency of this package
1140 will be used; to override this, pass a different frequency as a second
1146 my( $self, $date, $freq ) = @_;
1147 $freq = $self->freq unless $freq;
1149 #change this bit to use Date::Manip? CAREFUL with timezones (see
1150 # mailing list archive)
1151 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1153 if ( $freq =~ /^\d+$/ ) {
1155 until ( $mon < 12 ) { $mon -= 12; $year++; }
1157 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1159 } elsif ( $freq =~ /^(\d+)w$/ ) {
1161 $mday += $weeks * 7;
1162 } elsif ( $freq =~ /^(\d+)d$/ ) {
1165 } elsif ( $freq =~ /^(\d+)h$/ ) {
1172 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1177 For backwards compatibility, returns the plandata field as well as all options
1178 from FS::part_pkg_option.
1184 carp "plandata is deprecated";
1186 $self->SUPER::plandata(@_);
1188 my $plandata = $self->get('plandata');
1189 my %options = $self->options;
1190 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1195 =item part_pkg_vendor
1197 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1198 L<FS::part_pkg_vendor>).
1202 sub part_pkg_vendor {
1204 qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1207 =item vendor_pkg_ids
1209 Returns a list of vendor/external package ids by exportnum
1213 sub vendor_pkg_ids {
1215 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1218 =item part_pkg_option
1220 Returns all options as FS::part_pkg_option objects (see
1221 L<FS::part_pkg_option>).
1225 sub part_pkg_option {
1227 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1232 Returns a list of option names and values suitable for assigning to a hash.
1238 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1241 =item option OPTIONNAME [ QUIET ]
1243 Returns the option value for the given name, or the empty string. If a true
1244 value is passed as the second argument, warnings about missing the option
1250 my( $self, $opt, $ornull ) = @_;
1252 #cache: was pulled up in the original part_pkg query
1253 if ( $opt =~ /^(setup|recur)_fee$/ && defined($self->hashref->{"_$opt"}) ) {
1254 return $self->hashref->{"_$opt"};
1257 cluck "$self -> option: searching for $opt"
1259 my $part_pkg_option =
1260 qsearchs('part_pkg_option', {
1261 pkgpart => $self->pkgpart,
1264 return $part_pkg_option->optionvalue if $part_pkg_option;
1266 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1267 split("\n", $self->get('plandata') );
1268 return $plandata{$opt} if exists $plandata{$opt};
1269 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1270 "not found in options or plandata!\n"
1276 =item fcc_option OPTIONNAME
1278 Returns the FCC 477 report option value for the given name, or the empty
1284 my ($self, $name) = @_;
1285 my $part_pkg_fcc_option =
1286 qsearchs('part_pkg_fcc_option', {
1287 pkgpart => $self->pkgpart,
1288 fccoptionname => $name,
1290 $part_pkg_fcc_option ? $part_pkg_fcc_option->optionvalue : '';
1295 Returns all FCC 477 report options for this package, as a hash-like list.
1301 map { $_->fccoptionname => $_->optionvalue }
1302 qsearch('part_pkg_fcc_option', { pkgpart => $self->pkgpart });
1305 =item bill_part_pkg_link
1307 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1311 sub bill_part_pkg_link {
1312 shift->_part_pkg_link('bill', @_);
1315 =item svc_part_pkg_link
1317 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1321 sub svc_part_pkg_link {
1322 shift->_part_pkg_link('svc', @_);
1325 =item supp_part_pkg_link
1327 Returns the associated part_pkg_link records of type 'supp' (supplemental
1332 sub supp_part_pkg_link {
1333 shift->_part_pkg_link('supp', @_);
1336 sub _part_pkg_link {
1337 my( $self, $type ) = @_;
1338 qsearch({ table => 'part_pkg_link',
1339 hashref => { 'src_pkgpart' => $self->pkgpart,
1340 'link_type' => $type,
1341 #protection against infinite recursive links
1342 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1344 order_by => "ORDER BY hidden",
1348 sub self_and_bill_linked {
1349 shift->_self_and_linked('bill', @_);
1352 sub self_and_svc_linked {
1353 shift->_self_and_linked('svc', @_);
1356 sub _self_and_linked {
1357 my( $self, $type, $hidden ) = @_;
1361 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1362 $self->_part_pkg_link($type) ) )
1364 $_->hidden($hidden) if $hidden;
1371 =item part_pkg_taxoverride [ CLASS ]
1373 Returns all associated FS::part_pkg_taxoverride objects (see
1374 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1375 of class CLASS if defined. Class may be one of 'setup', 'recur',
1376 the empty string (default), or a usage class number (see L<FS::usage_class>).
1377 When a class is specified, the empty string class (default) is returned
1378 if no more specific values exist.
1382 sub part_pkg_taxoverride {
1386 my $hashref = { 'pkgpart' => $self->pkgpart };
1387 $hashref->{'usage_class'} = $class if defined($class);
1388 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1390 unless ( scalar(@overrides) || !defined($class) || !$class ){
1391 $hashref->{'usage_class'} = '';
1392 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1398 =item has_taxproduct
1400 Returns true if this package has any taxproduct associated with it.
1404 sub has_taxproduct {
1407 $self->taxproductnum ||
1408 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1409 keys %{ {$self->options} }
1415 =item taxproduct [ CLASS ]
1417 Returns the associated tax product for this package definition (see
1418 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1419 the usage classnum (see L<FS::usage_class>). Returns the default
1420 tax product for this record if the more specific CLASS value does
1429 my $part_pkg_taxproduct;
1431 my $taxproductnum = $self->taxproductnum;
1433 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1434 $taxproductnum = $class_taxproductnum
1435 if $class_taxproductnum
1438 $part_pkg_taxproduct =
1439 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1441 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1442 $taxproductnum = $self->taxproductnum;
1443 $part_pkg_taxproduct =
1444 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1447 $part_pkg_taxproduct;
1450 =item taxproduct_description [ CLASS ]
1452 Returns the description of the associated tax product for this package
1453 definition (see L<FS::part_pkg_taxproduct>).
1457 sub taxproduct_description {
1459 my $part_pkg_taxproduct = $self->taxproduct(@_);
1460 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1464 =item tax_rates DATA_PROVIDER, GEOCODE, [ CLASS ]
1466 Returns the tax table entries (L<FS::tax_rate> objects) that apply to this
1467 package in the location specified by GEOCODE, for usage class CLASS (one of
1468 'setup', 'recur', null, or a C<usage_class> number).
1474 my ($vendor, $geocode, $class) = @_;
1475 my @taxclassnums = map { $_->taxclassnum }
1476 $self->part_pkg_taxoverride($class);
1477 if (!@taxclassnums) {
1478 my $part_pkg_taxproduct = $self->taxproduct($class);
1479 # If this isn't defined, then the class has no taxproduct designation,
1480 # so return no tax rates.
1481 return () if !$part_pkg_taxproduct;
1483 # convert the taxproduct to the tax classes that might apply to it in
1485 @taxclassnums = map { $_->taxclassnum }
1486 grep { $_->taxable eq 'Y' } # why do we need this?
1487 $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1489 return unless @taxclassnums;
1491 # then look up the actual tax_rate entries
1492 warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1494 my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1495 my @taxes = qsearch({ 'table' => 'tax_rate',
1496 'hashref' => { 'geocode' => $geocode,
1497 'data_vendor' => $vendor },
1498 'extra_sql' => $extra_sql,
1500 warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1506 =item part_pkg_discount
1508 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1513 sub part_pkg_discount {
1515 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1518 =item part_pkg_usage
1520 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1525 sub part_pkg_usage {
1527 qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1532 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1533 PLAN is the object's I<plan> field. There should be better docs
1534 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1540 my $plan = $self->plan;
1542 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1546 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1547 my $class = ref($self). "::$plan";
1548 warn "reblessing $self into $class" if $DEBUG > 1;
1551 bless($self, $class) unless $@;
1556 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1557 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1559 #fallback that return 0 for old legacy packages with no plan
1560 sub calc_remain { 0; }
1561 sub calc_units { 0; }
1563 #fallback for everything not based on flat.pm
1564 sub recur_temporality { 'upcoming'; }
1565 sub calc_cancel { 0; }
1567 #fallback for everything except bulk.pm
1568 sub hide_svc_detail { 0; }
1570 #fallback for packages that can't/won't summarize usage
1571 sub sum_usage { 0; }
1573 =item recur_cost_permonth CUST_PKG
1575 recur_cost divided by freq (only supported for monthly and longer frequencies)
1579 sub recur_cost_permonth {
1580 my($self, $cust_pkg) = @_;
1581 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1582 sprintf('%.2f', $self->recur_cost / $self->freq );
1585 =item cust_bill_pkg_recur CUST_PKG
1587 Actual recurring charge for the specified customer package from customer's most
1592 sub cust_bill_pkg_recur {
1593 my($self, $cust_pkg) = @_;
1594 my $cust_bill_pkg = qsearchs({
1595 'table' => 'cust_bill_pkg',
1596 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1597 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1598 'recur' => { op=>'>', value=>'0' },
1600 'order_by' => 'ORDER BY cust_bill._date DESC,
1601 cust_bill_pkg.sdate DESC
1604 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1605 $cust_bill_pkg->recur;
1608 =item unit_setup CUST_PKG
1610 Returns the setup fee for one unit of the package.
1615 my ($self, $cust_pkg) = @_;
1616 $self->option('setup_fee') || 0;
1621 unit_setup minus setup_cost
1627 $self->unit_setup(@_) - $self->setup_cost;
1630 =item recur_margin_permonth
1632 base_recur_permonth minus recur_cost_permonth
1636 sub recur_margin_permonth {
1638 $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1641 =item format OPTION DATA
1643 Returns data formatted according to the function 'format' described
1644 in the plan info. Returns DATA if no such function exists.
1649 my ($self, $option, $data) = (shift, shift, shift);
1650 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1651 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1657 =item parse OPTION DATA
1659 Returns data parsed according to the function 'parse' described
1660 in the plan info. Returns DATA if no such function exists.
1665 my ($self, $option, $data) = (shift, shift, shift);
1666 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1667 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1677 =head1 CLASS METHODS
1685 # Used by FS::Upgrade to migrate to a new database.
1687 sub _upgrade_data { # class method
1688 my($class, %opts) = @_;
1690 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1692 my @part_pkg = qsearch({
1693 'table' => 'part_pkg',
1694 'extra_sql' => "WHERE ". join(' OR ',
1695 'plan IS NULL', "plan = '' ",
1699 foreach my $part_pkg (@part_pkg) {
1701 unless ( $part_pkg->plan ) {
1702 $part_pkg->plan('flat');
1708 # the rest can be done asynchronously
1711 sub queueable_upgrade {
1712 # now upgrade to the explicit custom flag
1714 my $search = FS::Cursor->new({
1715 'table' => 'part_pkg',
1716 'hashref' => { disabled => 'Y', custom => '' },
1717 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1721 while (my $part_pkg = $search->fetch) {
1722 my $new = new FS::part_pkg { $part_pkg->hash };
1724 my $comment = $part_pkg->comment;
1725 $comment =~ s/^\(CUSTOM\) //;
1726 $comment = '(none)' unless $comment =~ /\S/;
1727 $new->comment($comment);
1729 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1730 my $primary = $part_pkg->svcpart;
1731 my $options = { $part_pkg->options };
1733 my $error = $new->replace( $part_pkg,
1734 'pkg_svc' => $pkg_svc,
1735 'primary_svc' => $primary,
1736 'options' => $options,
1739 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1746 # set family_pkgpart on any packages that don't have it
1747 $search = FS::Cursor->new('part_pkg', { 'family_pkgpart' => '' });
1748 while (my $part_pkg = $search->fetch) {
1749 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1750 my $error = $part_pkg->SUPER::replace;
1752 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1759 my @part_pkg_option = qsearch('part_pkg_option',
1760 { 'optionname' => 'unused_credit',
1763 foreach my $old_opt (@part_pkg_option) {
1764 my $pkgpart = $old_opt->pkgpart;
1765 my $error = $old_opt->delete;
1766 die $error if $error;
1768 foreach (qw(unused_credit_cancel unused_credit_change)) {
1769 my $new_opt = new FS::part_pkg_option {
1770 'pkgpart' => $pkgpart,
1774 $error = $new_opt->insert;
1775 die $error if $error;
1779 # migrate use_disposition_taqua and use_disposition to disposition_in
1780 @part_pkg_option = qsearch('part_pkg_option',
1781 { 'optionname' => { op => 'LIKE',
1782 value => 'use_disposition%',
1786 my %newopts = map { $_->pkgpart => $_ }
1787 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1788 foreach my $old_opt (@part_pkg_option) {
1789 my $pkgpart = $old_opt->pkgpart;
1790 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1792 my $error = $old_opt->delete;
1793 die $error if $error;
1795 if ( exists($newopts{$pkgpart}) ) {
1796 my $opt = $newopts{$pkgpart};
1797 $opt->optionvalue($opt->optionvalue.",$newval");
1798 $error = $opt->replace;
1799 die $error if $error;
1801 my $new_opt = new FS::part_pkg_option {
1802 'pkgpart' => $pkgpart,
1803 'optionname' => 'disposition_in',
1804 'optionvalue' => $newval,
1806 $error = $new_opt->insert;
1807 die $error if $error;
1808 $newopts{$pkgpart} = $new_opt;
1812 # set any package with FCC voice lines to the "VoIP with broadband" category
1813 # for backward compatibility
1815 # recover from a bad upgrade bug
1816 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1817 if (!FS::upgrade_journal->is_done($upgrade)) {
1818 my $bad_upgrade = qsearchs('upgrade_journal',
1819 { upgrade => 'part_pkg_fcc_voip_class' }
1821 if ( $bad_upgrade ) {
1822 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1823 ' AND history_date > '.($bad_upgrade->_date - 3600);
1824 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1827 'table' => 'h_part_pkg_option',
1829 'extra_sql' => "$where AND history_action = 'delete'",
1830 'order_by' => 'ORDER BY history_date ASC',
1832 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1835 'table' => 'h_pkg_svc',
1837 'extra_sql' => "$where AND history_action = 'replace_old'",
1838 'order_by' => 'ORDER BY history_date ASC',
1841 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1842 my $pkgpart ||= $deleted->pkgpart;
1843 $opt{$pkgpart} ||= {
1849 if ( $deleted->isa('FS::part_pkg_option') ) {
1850 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1852 my $svcpart = $deleted->svcpart;
1853 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1854 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1855 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1858 foreach my $pkgpart (keys %opt) {
1859 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1860 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1862 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1865 } # $bad_upgrade exists
1866 else { # do the original upgrade, but correctly this time
1867 my @part_pkg = qsearch('part_pkg', {
1868 fcc_ds0s => { op => '>', value => 0 },
1869 fcc_voip_class => ''
1871 foreach my $part_pkg (@part_pkg) {
1872 $part_pkg->set(fcc_voip_class => 2);
1873 my @pkg_svc = $part_pkg->pkg_svc;
1874 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1875 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1876 my $error = $part_pkg->replace(
1877 $part_pkg->replace_old,
1878 options => { $part_pkg->options },
1879 pkg_svc => \%quantity,
1880 hidden_svc => \%hidden,
1881 primary_svc => ($part_pkg->svcpart || ''),
1883 die $error if $error;
1886 FS::upgrade_journal->set_done($upgrade);
1891 =item curuser_pkgs_sql
1893 Returns an SQL fragment for searching for packages the current user can
1894 use, either via part_pkg.agentnum directly, or via agent type (see
1899 sub curuser_pkgs_sql {
1902 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1906 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1908 Returns an SQL fragment for searching for packages the provided agent or agents
1909 can use, either via part_pkg.agentnum directly, or via agent type (see
1914 sub agent_pkgs_sql {
1915 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1916 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1918 $class->_pkgs_sql(@agentnums); #is this why
1923 my( $class, @agentnums ) = @_;
1924 my $agentnums = join(',', @agentnums);
1928 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1929 OR ( agentnum IS NULL
1930 AND EXISTS ( SELECT 1
1932 LEFT JOIN agent_type USING ( typenum )
1933 LEFT JOIN agent AS typeagent USING ( typenum )
1934 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1935 AND typeagent.agentnum IN ($agentnums)
1953 #false laziness w/part_export & cdr
1955 foreach my $INC ( @INC ) {
1956 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1957 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1958 warn "attempting to load plan info from $file\n" if $DEBUG;
1959 $file =~ /\/(\w+)\.pm$/ or do {
1960 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1964 my $info = eval "use FS::part_pkg::$mod; ".
1965 "\\%FS::part_pkg::$mod\::info;";
1967 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1970 unless ( keys %$info ) {
1971 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1974 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1975 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1976 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1979 $info{$mod} = $info;
1980 $info->{'weight'} ||= 0; # quiet warnings
1984 # copy one level deep to allow replacement of fields and fieldorder
1985 tie %plans, 'Tie::IxHash',
1986 map { my %infohash = %{ $info{$_} };
1988 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1991 # inheritance of plan options
1992 foreach my $name (keys(%info)) {
1993 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1994 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1995 delete $plans{$name};
1998 my $parents = $info{$name}->{'inherit_fields'} || [];
1999 my (%fields, %field_exists, @fieldorder);
2000 foreach my $parent ($name, @$parents) {
2001 if ( !exists($info{$parent}) ) {
2002 warn "$name tried to inherit from nonexistent '$parent'\n";
2005 %fields = ( # avoid replacing existing fields
2006 %{ $info{$parent}->{'fields'} || {} },
2009 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2011 next if $field_exists{$_};
2012 $field_exists{$_} = 1;
2013 # allow inheritors to remove inherited fields from the fieldorder
2014 push @fieldorder, $_ if !exists($fields{$_}) or
2015 !exists($fields{$_}->{'disabled'});
2018 $plans{$name}->{'fields'} = \%fields;
2019 $plans{$name}->{'fieldorder'} = \@fieldorder;
2029 =head1 NEW PLAN CLASSES
2031 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2032 found in eg/plan_template.pm. Until then, it is suggested that you use the
2033 other modules in FS/FS/part_pkg/ as a guide.
2037 The delete method is unimplemented.
2039 setup and recur semantics are not yet defined (and are implemented in
2040 FS::cust_bill. hmm.). now they're deprecated and need to go.
2044 part_pkg_taxrate is Pg specific
2046 replace should be smarter about managing the related tables (options, pkg_svc)
2050 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2051 schema.html from the base documentation.