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
123 =item start_on_hold - 'Y' to suspend this package immediately when it is
124 ordered. The package will not start billing or have a setup fee charged
125 until it is manually unsuspended.
135 Creates a new package definition. To add the package definition to
136 the database, see L<"insert">.
140 sub table { 'part_pkg'; }
144 An alternate constructor. Creates a new package definition by duplicating
145 an existing definition. A new pkgpart is assigned and the custom flag is
146 set to Y. To add the package definition to the database, see L<"insert">.
152 my $class = ref($self);
153 my %hash = $self->hash;
154 $hash{'pkgpart'} = '';
155 $hash{'custom'} = 'Y';
156 #new FS::part_pkg ( \%hash ); # ?
157 new $class ( \%hash ); # ?
160 =item insert [ , OPTION => VALUE ... ]
162 Adds this package definition to the database. If there is an error,
163 returns the error, otherwise returns false.
165 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
166 I<custnum_ref> and I<options>.
168 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
169 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
170 be set to a hashref of svcparts and flag values ('Y' or '') to set the
171 'hidden' field in these records.
173 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
174 FS::pkg_svc record will be updated.
176 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
177 record itself), the object will be updated to point to this package definition.
179 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
180 the scalar will be updated with the custnum value from the cust_pkg record.
182 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
183 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
184 records will be inserted.
186 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
187 records will be inserted.
194 warn "FS::part_pkg::insert called on $self with options ".
195 join(', ', map "$_=>$options{$_}", keys %options)
198 local $SIG{HUP} = 'IGNORE';
199 local $SIG{INT} = 'IGNORE';
200 local $SIG{QUIT} = 'IGNORE';
201 local $SIG{TERM} = 'IGNORE';
202 local $SIG{TSTP} = 'IGNORE';
203 local $SIG{PIPE} = 'IGNORE';
205 my $oldAutoCommit = $FS::UID::AutoCommit;
206 local $FS::UID::AutoCommit = 0;
209 warn " inserting part_pkg record" if $DEBUG;
210 my $error = $self->SUPER::insert( $options{options} );
212 $dbh->rollback if $oldAutoCommit;
217 if ( $self->get('family_pkgpart') eq '' ) {
218 $self->set('family_pkgpart' => $self->pkgpart);
219 $error = $self->SUPER::replace;
221 $dbh->rollback if $oldAutoCommit;
226 warn " inserting part_pkg_taxoverride records" if $DEBUG;
227 my %overrides = %{ $options{'tax_overrides'} || {} };
228 foreach my $usage_class ( keys %overrides ) {
230 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
231 ? $overrides{$usage_class}
233 my @overrides = (grep "$_", split(',', $override) );
234 my $error = $self->process_m2m (
235 'link_table' => 'part_pkg_taxoverride',
236 'target_table' => 'tax_class',
237 'hashref' => { 'usage_class' => $usage_class },
238 'params' => \@overrides,
241 $dbh->rollback if $oldAutoCommit;
246 unless ( $skip_pkg_svc_hack ) {
248 warn " inserting pkg_svc records" if $DEBUG;
249 my $pkg_svc = $options{'pkg_svc'} || {};
250 my $hidden_svc = $options{'hidden_svc'} || {};
251 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
252 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
254 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
258 my $pkg_svc = new FS::pkg_svc( {
259 'pkgpart' => $self->pkgpart,
260 'svcpart' => $part_svc->svcpart,
261 'quantity' => $quantity,
262 'primary_svc' => $primary_svc,
263 'hidden' => $hidden_svc->{$part_svc->svcpart},
265 my $error = $pkg_svc->insert;
267 $dbh->rollback if $oldAutoCommit;
274 if ( $options{'cust_pkg'} ) {
275 warn " updating cust_pkg record " if $DEBUG;
277 ref($options{'cust_pkg'})
278 ? $options{'cust_pkg'}
279 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
280 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
281 if $options{'custnum_ref'};
282 my %hash = $old_cust_pkg->hash;
283 $hash{'pkgpart'} = $self->pkgpart,
284 my $new_cust_pkg = new FS::cust_pkg \%hash;
285 local($FS::cust_pkg::disable_agentcheck) = 1;
286 my $error = $new_cust_pkg->replace($old_cust_pkg);
288 $dbh->rollback if $oldAutoCommit;
289 return "Error modifying cust_pkg record: $error";
293 if ( $options{'part_pkg_vendor'} ) {
294 while ( my ($exportnum, $vendor_pkg_id) =
295 each %{ $options{part_pkg_vendor} }
298 my $ppv = new FS::part_pkg_vendor( {
299 'pkgpart' => $self->pkgpart,
300 'exportnum' => $exportnum,
301 'vendor_pkg_id' => $vendor_pkg_id,
303 my $error = $ppv->insert;
305 $dbh->rollback if $oldAutoCommit;
306 return "Error inserting part_pkg_vendor record: $error";
311 if ( $options{fcc_options} ) {
312 warn " updating fcc options " if $DEBUG;
313 $self->set_fcc_options( $options{fcc_options} );
316 warn " committing transaction" if $DEBUG and $oldAutoCommit;
317 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
324 Currently unimplemented.
329 return "Can't (yet?) delete package definitions.";
330 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
333 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
335 Replaces OLD_RECORD with this one in the database. If there is an error,
336 returns the error, otherwise returns false.
338 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
341 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
342 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
343 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
344 'hidden' field in these records.
346 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
347 FS::pkg_svc record will be updated.
349 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
357 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
362 ( ref($_[0]) eq 'HASH' )
366 $options->{options} = { $old->options } unless defined($options->{options});
368 warn "FS::part_pkg::replace called on $new to replace $old with options".
369 join(', ', map "$_ => ". $options->{$_}, keys %$options)
372 local $SIG{HUP} = 'IGNORE';
373 local $SIG{INT} = 'IGNORE';
374 local $SIG{QUIT} = 'IGNORE';
375 local $SIG{TERM} = 'IGNORE';
376 local $SIG{TSTP} = 'IGNORE';
377 local $SIG{PIPE} = 'IGNORE';
379 my $oldAutoCommit = $FS::UID::AutoCommit;
380 local $FS::UID::AutoCommit = 0;
383 my $conf = new FS::Conf;
384 if ( $conf->exists('part_pkg-lineage') ) {
385 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
386 qw(setup_fee recur_fee) #others? config?
389 warn " superseding package" if $DEBUG;
391 my $error = $new->supersede($old, %$options);
393 $dbh->rollback if $oldAutoCommit;
397 warn " committing transaction" if $DEBUG and $oldAutoCommit;
398 $dbh->commit if $oldAutoCommit;
405 #plandata shit stays in replace for upgrades until after 2.0 (or edit
407 warn " saving legacy plandata" if $DEBUG;
408 my $plandata = $new->get('plandata');
409 $new->set('plandata', '');
411 warn " deleting old part_pkg_option records" if $DEBUG;
412 foreach my $part_pkg_option ( $old->part_pkg_option ) {
413 my $error = $part_pkg_option->delete;
415 $dbh->rollback if $oldAutoCommit;
420 warn " replacing part_pkg record" if $DEBUG;
421 my $error = $new->SUPER::replace($old, $options->{options} );
423 $dbh->rollback if $oldAutoCommit;
427 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
428 foreach my $part_pkg_option (
429 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
430 return "illegal plandata: $plandata";
432 new FS::part_pkg_option {
433 'pkgpart' => $new->pkgpart,
438 split("\n", $plandata)
440 my $error = $part_pkg_option->insert;
442 $dbh->rollback if $oldAutoCommit;
447 warn " replacing pkg_svc records" if $DEBUG;
448 my $pkg_svc = $options->{'pkg_svc'};
449 my $hidden_svc = $options->{'hidden_svc'} || {};
450 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
451 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
452 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
453 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
455 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
456 && $options->{'primary_svc'} == $part_svc->svcpart
461 my $old_pkg_svc = qsearchs('pkg_svc', {
462 'pkgpart' => $old->pkgpart,
463 'svcpart' => $part_svc->svcpart,
466 my $old_quantity = 0;
467 my $old_primary_svc = '';
469 if ( $old_pkg_svc ) {
470 $old_quantity = $old_pkg_svc->quantity;
471 $old_primary_svc = $old_pkg_svc->primary_svc
472 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
473 $old_hidden = $old_pkg_svc->hidden;
476 next unless $old_quantity != $quantity ||
477 $old_primary_svc ne $primary_svc ||
478 $old_hidden ne $hidden;
480 my $new_pkg_svc = new FS::pkg_svc( {
481 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
482 'pkgpart' => $new->pkgpart,
483 'svcpart' => $part_svc->svcpart,
484 'quantity' => $quantity,
485 'primary_svc' => $primary_svc,
488 my $error = $old_pkg_svc
489 ? $new_pkg_svc->replace($old_pkg_svc)
490 : $new_pkg_svc->insert;
492 $dbh->rollback if $oldAutoCommit;
496 } #if $options->{pkg_svc}
498 my @part_pkg_vendor = $old->part_pkg_vendor;
499 my @current_exportnum = ();
500 if ( $options->{'part_pkg_vendor'} ) {
501 my($exportnum,$vendor_pkg_id);
502 while ( ($exportnum,$vendor_pkg_id)
503 = each %{$options->{'part_pkg_vendor'}} ) {
505 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
506 if($exportnum == $part_pkg_vendor->exportnum
507 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
508 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
509 my $error = $part_pkg_vendor->replace;
511 $dbh->rollback if $oldAutoCommit;
512 return "Error replacing part_pkg_vendor record: $error";
517 elsif($exportnum == $part_pkg_vendor->exportnum
518 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
523 unless ( $noinsert ) {
524 my $ppv = new FS::part_pkg_vendor( {
525 'pkgpart' => $new->pkgpart,
526 'exportnum' => $exportnum,
527 'vendor_pkg_id' => $vendor_pkg_id,
529 my $error = $ppv->insert;
531 $dbh->rollback if $oldAutoCommit;
532 return "Error inserting part_pkg_vendor record: $error";
535 push @current_exportnum, $exportnum;
538 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
539 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
540 my $error = $part_pkg_vendor->delete;
542 $dbh->rollback if $oldAutoCommit;
543 return "Error deleting part_pkg_vendor record: $error";
548 # propagate changes to certain core fields
549 if ( $conf->exists('part_pkg-lineage') ) {
550 warn " propagating changes to family" if $DEBUG;
551 my $error = $new->propagate($old);
553 $dbh->rollback if $oldAutoCommit;
558 if ( $options->{fcc_options} ) {
559 warn " updating fcc options " if $DEBUG;
560 $new->set_fcc_options( $options->{fcc_options} );
563 warn " committing transaction" if $DEBUG and $oldAutoCommit;
564 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
570 Checks all fields to make sure this is a valid package definition. If
571 there is an error, returns the error, otherwise returns false. Called by the
572 insert and replace methods.
578 warn "FS::part_pkg::check called on $self" if $DEBUG;
580 for (qw(setup recur plandata)) {
581 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
582 return "Use of $_ field is deprecated; set a plan and options: ".
584 if length($self->get($_));
588 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
589 my $error = $self->ut_number('freq');
590 return $error if $error;
592 $self->freq =~ /^(\d+[hdw]?)$/
593 or return "Illegal or empty freq: ". $self->freq;
597 my @null_agentnum_right = ( 'Edit global package definitions' );
598 push @null_agentnum_right, 'One-time charge'
599 if $self->freq =~ /^0/;
600 push @null_agentnum_right, 'Customize customer package'
601 if $self->disabled eq 'Y'; #good enough
603 my $error = $self->ut_numbern('pkgpart')
604 || $self->ut_text('pkg')
605 || $self->ut_textn('comment')
606 || $self->ut_textn('promo_code')
607 || $self->ut_alphan('plan')
608 || $self->ut_flag('setuptax')
609 || $self->ut_flag('recurtax')
610 || $self->ut_textn('taxclass')
611 || $self->ut_flag('disabled')
612 || $self->ut_flag('custom')
613 || $self->ut_flag('no_auto')
614 || $self->ut_flag('recur_show_zero')
615 || $self->ut_flag('setup_show_zero')
616 || $self->ut_flag('start_on_hold')
617 #|| $self->ut_moneyn('setup_cost')
618 #|| $self->ut_moneyn('recur_cost')
619 || $self->ut_floatn('setup_cost')
620 || $self->ut_floatn('recur_cost')
621 || $self->ut_floatn('pay_weight')
622 || $self->ut_floatn('credit_weight')
623 || $self->ut_numbern('taxproductnum')
624 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
625 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
626 || $self->ut_foreign_keyn('taxproductnum',
627 'part_pkg_taxproduct',
631 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
632 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
634 || $self->ut_numbern('fcc_ds0s')
635 || $self->ut_numbern('fcc_voip_class')
636 || $self->ut_numbern('delay_start')
637 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
638 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
639 || $self->ut_alphan('agent_pkgpartid')
640 || $self->SUPER::check
642 return $error if $error;
644 return 'Unknown plan '. $self->plan
645 unless exists($plans{$self->plan});
647 my $conf = new FS::Conf;
648 return 'Taxclass is required'
649 if ! $self->taxclass && $conf->exists('require_taxclasses');
654 =item supersede OLD [, OPTION => VALUE ... ]
656 Inserts this package as a successor to the package OLD. All options are as
657 for C<insert>. After inserting, disables OLD and sets the new package as its
663 my ($new, $old, %options) = @_;
666 $new->set('pkgpart' => '');
667 $new->set('family_pkgpart' => $old->family_pkgpart);
668 warn " inserting successor package\n" if $DEBUG;
669 $error = $new->insert(%options);
670 return $error if $error;
672 warn " disabling superseded package\n" if $DEBUG;
673 $old->set('successor' => $new->pkgpart);
674 $old->set('disabled' => 'Y');
675 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
676 return $error if $error;
678 warn " propagating changes to family" if $DEBUG;
679 $new->propagate($old);
684 If any of certain fields have changed from OLD to this package, then,
685 for all packages in the same lineage as this one, sets those fields
686 to their values in this package.
690 my @propagate_fields = (
691 qw( pkg classnum setup_cost recur_cost taxclass
692 setuptax recurtax pay_weight credit_weight
700 map { $_ => $new->get($_) }
701 grep { $new->get($_) ne $old->get($_) }
705 my @part_pkg = qsearch('part_pkg', {
706 'family_pkgpart' => $new->family_pkgpart
709 foreach my $part_pkg ( @part_pkg ) {
710 my $pkgpart = $part_pkg->pkgpart;
711 next if $pkgpart == $new->pkgpart; # don't modify $new
712 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
713 foreach ( keys %fields ) {
714 $part_pkg->set($_, $fields{$_});
716 # SUPER::replace to avoid changing non-core fields
717 my $error = $part_pkg->SUPER::replace;
718 push @error, "pkgpart $pkgpart: $error"
724 =item set_fcc_options HASHREF
726 Sets the FCC options on this package definition to the values specified
731 sub set_fcc_options {
733 my $pkgpart = $self->pkgpart;
741 my %existing_num = map { $_->fccoptionname => $_->num }
742 qsearch('part_pkg_fcc_option', { pkgpart => $pkgpart });
744 local $FS::Record::nowarn_identical = 1;
745 # set up params for process_o2m
748 foreach my $name (keys %$options ) {
749 $params->{ "num$i" } = $existing_num{$name} || '';
750 $params->{ "num$i".'_fccoptionname' } = $name;
751 $params->{ "num$i".'_optionvalue' } = $options->{$name};
756 table => 'part_pkg_fcc_option',
757 fields => [qw( fccoptionname optionvalue )],
762 =item pkg_locale LOCALE
764 Returns a customer-viewable string representing this package for the given
765 locale, from the part_pkg_msgcat table. If the given locale is empty or no
766 localized string is found, returns the base pkg field.
771 my( $self, $locale ) = @_;
772 return $self->pkg unless $locale;
773 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
774 $part_pkg_msgcat->pkg;
777 =item part_pkg_msgcat LOCALE
779 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
783 sub part_pkg_msgcat {
784 my( $self, $locale ) = @_;
785 qsearchs( 'part_pkg_msgcat', {
786 pkgpart => $self->pkgpart,
791 =item pkg_comment [ OPTION => VALUE... ]
793 Returns an (internal) string representing this package. Currently,
794 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
795 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
798 If the option nopkgpart is true then the "pkgpart: ' is omitted.
806 #$self->pkg. ' - '. $self->comment;
807 #$self->pkg. ' ('. $self->comment. ')';
808 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
809 my $custom_comment = $self->custom_comment(%opt);
810 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
813 #without price info (so without hitting the DB again)
814 sub pkg_comment_only {
818 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
819 my $comment = $self->comment;
820 $pre. $self->pkg. ( $comment ? " - $comment" : '' );
823 sub price_info { # safety, in case a part_pkg hasn't defined price_info
829 my $price_info = $self->price_info(@_);
830 ( $self->custom ? '(CUSTOM) ' : '' ).
832 ( ( ($self->custom || $self->comment) && $price_info ) ? ' - ' : '' ).
838 $self->pkg. ' - '. ($self->price_info || 'No charge');
843 Returns the package class, as an FS::pkg_class object, or the empty string
844 if there is no package class.
850 if ( $self->classnum ) {
851 qsearchs('pkg_class', { 'classnum' => $self->classnum } );
857 =item addon_pkg_class
859 Returns the add-on package class, as an FS::pkg_class object, or the empty
860 string if there is no add-on package class.
864 sub addon_pkg_class {
866 if ( $self->addon_classnum ) {
867 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
875 Returns the package category name, or the empty string if there is no package
882 my $pkg_class = $self->pkg_class;
884 ? $pkg_class->categoryname
890 Returns the package class name, or the empty string if there is no package
897 my $pkg_class = $self->pkg_class;
899 ? $pkg_class->classname
903 =item addon_classname
905 Returns the add-on package class name, or the empty string if there is no
906 add-on package class.
910 sub addon_classname {
912 my $pkg_class = $self->addon_pkg_class;
914 ? $pkg_class->classname
920 Returns the associated agent for this event, if any, as an FS::agent object.
926 qsearchs('agent', { 'agentnum' => $self->agentnum } );
929 =item pkg_svc [ HASHREF | OPTION => VALUE ]
931 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
932 definition (with non-zero quantity).
934 One option is available, I<disable_linked>. If set true it will return the
935 services for this package definition alone, omitting services from any add-on
942 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
949 qsearch('type_pkgs', { 'pkgpart' => $self->pkgpart } );
955 # #sort { $b->primary cmp $a->primary }
956 # grep { $_->quantity }
957 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
959 my $opt = ref($_[0]) ? $_[0] : { @_ };
960 my %pkg_svc = map { $_->svcpart => $_ }
961 grep { $_->quantity }
962 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
964 unless ( $opt->{disable_linked} ) {
965 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
966 my @pkg_svc = grep { $_->quantity }
967 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
968 foreach my $pkg_svc ( @pkg_svc ) {
969 if ( $pkg_svc{$pkg_svc->svcpart} ) {
970 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
971 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
973 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
983 =item svcpart [ SVCDB ]
985 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
986 associated with this package definition (see L<FS::pkg_svc>). Returns
987 false if there not a primary service definition or exactly one service
988 definition with quantity 1, or if SVCDB is specified and does not match the
989 svcdb of the service definition. SVCDB can be specified as a scalar table
990 name, such as 'svc_acct', or as an arrayref of possible table names.
995 my $pkg_svc = shift->_primary_pkg_svc(@_);
996 $pkg_svc ? $pkg_svc->svcpart : '';
999 =item part_svc [ SVCDB ]
1001 Like the B<svcpart> method, but returns the FS::part_svc object (see
1007 my $pkg_svc = shift->_primary_pkg_svc(@_);
1008 $pkg_svc ? $pkg_svc->part_svc : '';
1011 sub _primary_pkg_svc {
1014 my $svcdb = scalar(@_) ? shift : [];
1015 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1016 my %svcdb = map { $_=>1 } @$svcdb;
1019 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1022 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1023 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1025 return '' if scalar(@pkg_svc) != 1;
1029 =item svcpart_unique_svcdb SVCDB
1031 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1032 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1033 false if there not a primary service definition for SVCDB or there are multiple
1034 service definitions for SVCDB.
1038 sub svcpart_unique_svcdb {
1039 my( $self, $svcdb ) = @_;
1040 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1041 return '' if scalar(@svcdb_pkg_svc) != 1;
1042 $svcdb_pkg_svc[0]->svcpart;
1047 Returns a list of the acceptable payment types for this package. Eventually
1048 this should come out of a database table and be editable, but currently has the
1049 following logic instead:
1051 If the package is free, the single item B<BILL> is
1052 returned, otherwise, the single item B<CARD> is returned.
1054 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1060 if ( $self->is_free ) {
1069 Returns true if this package is free.
1075 if ( $self->can('is_free_options') ) {
1076 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1077 map { $self->option($_) }
1078 $self->is_free_options;
1080 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1081 "provides neither is_free_options nor is_free method; returning false";
1086 # whether the plan allows discounts to be applied to this package
1087 sub can_discount { 0; }
1089 # whether the plan allows changing the start date
1090 sub can_start_date {
1092 $self->start_on_hold ? 0 : 1;
1095 # the delay start date if present
1096 sub delay_start_date {
1099 my $delay = $self->delay_start or return '';
1101 # avoid timelocal silliness
1102 my $dt = DateTime->today(time_zone => 'local');
1103 $dt->add(days => $delay);
1108 # moved to FS::Misc to make this accessible to other packages
1110 FS::Misc::pkg_freqs();
1115 Returns an english representation of the I<freq> field, such as "monthly",
1116 "weekly", "semi-annually", etc.
1122 my $freq = $self->freq;
1124 #my $freqs_href = $self->freqs_href;
1125 my $freqs_href = freqs_href();
1127 if ( exists($freqs_href->{$freq}) ) {
1128 $freqs_href->{$freq};
1130 my $interval = 'month';
1131 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1132 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1133 $interval = $interval{$2};
1138 "every $freq ${interval}s";
1143 =item add_freq TIMESTAMP [ FREQ ]
1145 Adds a billing period of some frequency to the provided timestamp and
1146 returns the resulting timestamp, or -1 if the frequency could not be
1147 parsed (shouldn't happen). By default, the frequency of this package
1148 will be used; to override this, pass a different frequency as a second
1154 my( $self, $date, $freq ) = @_;
1155 $freq = $self->freq unless $freq;
1157 #change this bit to use Date::Manip? CAREFUL with timezones (see
1158 # mailing list archive)
1159 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1161 if ( $freq =~ /^\d+$/ ) {
1163 until ( $mon < 12 ) { $mon -= 12; $year++; }
1165 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1167 } elsif ( $freq =~ /^(\d+)w$/ ) {
1169 $mday += $weeks * 7;
1170 } elsif ( $freq =~ /^(\d+)d$/ ) {
1173 } elsif ( $freq =~ /^(\d+)h$/ ) {
1180 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1185 For backwards compatibility, returns the plandata field as well as all options
1186 from FS::part_pkg_option.
1192 carp "plandata is deprecated";
1194 $self->SUPER::plandata(@_);
1196 my $plandata = $self->get('plandata');
1197 my %options = $self->options;
1198 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1203 =item part_pkg_vendor
1205 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1206 L<FS::part_pkg_vendor>).
1210 sub part_pkg_vendor {
1212 qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1215 =item vendor_pkg_ids
1217 Returns a list of vendor/external package ids by exportnum
1221 sub vendor_pkg_ids {
1223 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1226 =item part_pkg_option
1228 Returns all options as FS::part_pkg_option objects (see
1229 L<FS::part_pkg_option>).
1233 sub part_pkg_option {
1235 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1240 Returns a list of option names and values suitable for assigning to a hash.
1246 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1249 =item option OPTIONNAME [ QUIET ]
1251 Returns the option value for the given name, or the empty string. If a true
1252 value is passed as the second argument, warnings about missing the option
1258 my( $self, $opt, $ornull ) = @_;
1260 #cache: was pulled up in the original part_pkg query
1261 if ( $opt =~ /^(setup|recur)_fee$/ && defined($self->hashref->{"_$opt"}) ) {
1262 return $self->hashref->{"_$opt"};
1265 cluck "$self -> option: searching for $opt"
1267 my $part_pkg_option =
1268 qsearchs('part_pkg_option', {
1269 pkgpart => $self->pkgpart,
1272 return $part_pkg_option->optionvalue if $part_pkg_option;
1274 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1275 split("\n", $self->get('plandata') );
1276 return $plandata{$opt} if exists $plandata{$opt};
1277 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1278 "not found in options or plandata!\n"
1284 =item fcc_option OPTIONNAME
1286 Returns the FCC 477 report option value for the given name, or the empty
1292 my ($self, $name) = @_;
1293 my $part_pkg_fcc_option =
1294 qsearchs('part_pkg_fcc_option', {
1295 pkgpart => $self->pkgpart,
1296 fccoptionname => $name,
1298 $part_pkg_fcc_option ? $part_pkg_fcc_option->optionvalue : '';
1303 Returns all FCC 477 report options for this package, as a hash-like list.
1309 map { $_->fccoptionname => $_->optionvalue }
1310 qsearch('part_pkg_fcc_option', { pkgpart => $self->pkgpart });
1313 =item bill_part_pkg_link
1315 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1319 sub bill_part_pkg_link {
1320 shift->_part_pkg_link('bill', @_);
1323 =item svc_part_pkg_link
1325 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1329 sub svc_part_pkg_link {
1330 shift->_part_pkg_link('svc', @_);
1333 =item supp_part_pkg_link
1335 Returns the associated part_pkg_link records of type 'supp' (supplemental
1340 sub supp_part_pkg_link {
1341 shift->_part_pkg_link('supp', @_);
1344 sub _part_pkg_link {
1345 my( $self, $type ) = @_;
1346 qsearch({ table => 'part_pkg_link',
1347 hashref => { 'src_pkgpart' => $self->pkgpart,
1348 'link_type' => $type,
1349 #protection against infinite recursive links
1350 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1352 order_by => "ORDER BY hidden",
1356 sub self_and_bill_linked {
1357 shift->_self_and_linked('bill', @_);
1360 sub self_and_svc_linked {
1361 shift->_self_and_linked('svc', @_);
1364 sub _self_and_linked {
1365 my( $self, $type, $hidden ) = @_;
1369 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1370 $self->_part_pkg_link($type) ) )
1372 $_->hidden($hidden) if $hidden;
1379 =item part_pkg_taxoverride [ CLASS ]
1381 Returns all associated FS::part_pkg_taxoverride objects (see
1382 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1383 of class CLASS if defined. Class may be one of 'setup', 'recur',
1384 the empty string (default), or a usage class number (see L<FS::usage_class>).
1385 When a class is specified, the empty string class (default) is returned
1386 if no more specific values exist.
1390 sub part_pkg_taxoverride {
1394 my $hashref = { 'pkgpart' => $self->pkgpart };
1395 $hashref->{'usage_class'} = $class if defined($class);
1396 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1398 unless ( scalar(@overrides) || !defined($class) || !$class ){
1399 $hashref->{'usage_class'} = '';
1400 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1406 =item has_taxproduct
1408 Returns true if this package has any taxproduct associated with it.
1412 sub has_taxproduct {
1415 $self->taxproductnum ||
1416 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1417 keys %{ {$self->options} }
1423 =item taxproduct [ CLASS ]
1425 Returns the associated tax product for this package definition (see
1426 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1427 the usage classnum (see L<FS::usage_class>). Returns the default
1428 tax product for this record if the more specific CLASS value does
1437 my $part_pkg_taxproduct;
1439 my $taxproductnum = $self->taxproductnum;
1441 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1442 $taxproductnum = $class_taxproductnum
1443 if $class_taxproductnum
1446 $part_pkg_taxproduct =
1447 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1449 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1450 $taxproductnum = $self->taxproductnum;
1451 $part_pkg_taxproduct =
1452 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1455 $part_pkg_taxproduct;
1458 =item taxproduct_description [ CLASS ]
1460 Returns the description of the associated tax product for this package
1461 definition (see L<FS::part_pkg_taxproduct>).
1465 sub taxproduct_description {
1467 my $part_pkg_taxproduct = $self->taxproduct(@_);
1468 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1472 =item tax_rates DATA_PROVIDER, GEOCODE, [ CLASS ]
1474 Returns the tax table entries (L<FS::tax_rate> objects) that apply to this
1475 package in the location specified by GEOCODE, for usage class CLASS (one of
1476 'setup', 'recur', null, or a C<usage_class> number).
1482 my ($vendor, $geocode, $class) = @_;
1483 # if this part_pkg is overridden into a specific taxclass, get that class
1484 my @taxclassnums = map { $_->taxclassnum }
1485 $self->part_pkg_taxoverride($class);
1486 # otherwise, get its tax product category
1487 if (!@taxclassnums) {
1488 my $part_pkg_taxproduct = $self->taxproduct($class);
1489 # If this isn't defined, then the class has no taxproduct designation,
1490 # so return no tax rates.
1491 return () if !$part_pkg_taxproduct;
1493 # convert the taxproduct to the tax classes that might apply to it in
1495 @taxclassnums = map { $_->taxclassnum }
1496 grep { $_->taxable eq 'Y' } # why do we need this?
1497 $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1499 return unless @taxclassnums;
1501 # then look up the actual tax_rate entries
1502 warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1504 my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1505 my @taxes = qsearch({ 'table' => 'tax_rate',
1506 'hashref' => { 'geocode' => $geocode,
1507 'data_vendor' => $vendor,
1509 'extra_sql' => $extra_sql,
1511 warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1517 =item part_pkg_discount
1519 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1524 sub part_pkg_discount {
1526 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1529 =item part_pkg_usage
1531 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1536 sub part_pkg_usage {
1538 qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1543 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1544 PLAN is the object's I<plan> field. There should be better docs
1545 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1551 my $plan = $self->plan;
1553 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1557 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1558 my $class = ref($self). "::$plan";
1559 warn "reblessing $self into $class" if $DEBUG > 1;
1562 bless($self, $class) unless $@;
1567 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1568 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1570 #fallback that return 0 for old legacy packages with no plan
1571 sub calc_remain { 0; }
1572 sub calc_units { 0; }
1574 #fallback for everything not based on flat.pm
1575 sub recur_temporality { 'upcoming'; }
1576 sub calc_cancel { 0; }
1578 #fallback for everything except bulk.pm
1579 sub hide_svc_detail { 0; }
1581 #fallback for packages that can't/won't summarize usage
1582 sub sum_usage { 0; }
1584 =item recur_cost_permonth CUST_PKG
1586 recur_cost divided by freq (only supported for monthly and longer frequencies)
1590 sub recur_cost_permonth {
1591 my($self, $cust_pkg) = @_;
1592 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1593 sprintf('%.2f', ($self->recur_cost || 0) / $self->freq );
1596 =item cust_bill_pkg_recur CUST_PKG
1598 Actual recurring charge for the specified customer package from customer's most
1603 sub cust_bill_pkg_recur {
1604 my($self, $cust_pkg) = @_;
1605 my $cust_bill_pkg = qsearchs({
1606 'table' => 'cust_bill_pkg',
1607 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1608 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1609 'recur' => { op=>'>', value=>'0' },
1611 'order_by' => 'ORDER BY cust_bill._date DESC,
1612 cust_bill_pkg.sdate DESC
1615 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1616 $cust_bill_pkg->recur;
1619 =item unit_setup CUST_PKG
1621 Returns the setup fee for one unit of the package.
1626 my ($self, $cust_pkg) = @_;
1627 $self->option('setup_fee') || 0;
1632 unit_setup minus setup_cost
1638 $self->unit_setup(@_) - ($self->setup_cost || 0);
1641 =item recur_margin_permonth
1643 base_recur_permonth minus recur_cost_permonth
1647 sub recur_margin_permonth {
1649 $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1652 =item format OPTION DATA
1654 Returns data formatted according to the function 'format' described
1655 in the plan info. Returns DATA if no such function exists.
1660 my ($self, $option, $data) = (shift, shift, shift);
1661 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1662 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1668 =item parse OPTION DATA
1670 Returns data parsed according to the function 'parse' described
1671 in the plan info. Returns DATA if no such function exists.
1676 my ($self, $option, $data) = (shift, shift, shift);
1677 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1678 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1688 =head1 CLASS METHODS
1696 # Used by FS::Upgrade to migrate to a new database.
1698 sub _upgrade_data { # class method
1699 my($class, %opts) = @_;
1701 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1703 my @part_pkg = qsearch({
1704 'table' => 'part_pkg',
1705 'extra_sql' => "WHERE ". join(' OR ',
1706 'plan IS NULL', "plan = '' ",
1710 foreach my $part_pkg (@part_pkg) {
1712 unless ( $part_pkg->plan ) {
1713 $part_pkg->plan('flat');
1719 # the rest can be done asynchronously
1722 sub queueable_upgrade {
1723 # now upgrade to the explicit custom flag
1725 my $search = FS::Cursor->new({
1726 'table' => 'part_pkg',
1727 'hashref' => { disabled => 'Y', custom => '' },
1728 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1732 while (my $part_pkg = $search->fetch) {
1733 my $new = new FS::part_pkg { $part_pkg->hash };
1735 my $comment = $part_pkg->comment;
1736 $comment =~ s/^\(CUSTOM\) //;
1737 $comment = '(none)' unless $comment =~ /\S/;
1738 $new->comment($comment);
1740 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1741 my $primary = $part_pkg->svcpart;
1742 my $options = { $part_pkg->options };
1744 my $error = $new->replace( $part_pkg,
1745 'pkg_svc' => $pkg_svc,
1746 'primary_svc' => $primary,
1747 'options' => $options,
1750 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1757 # set family_pkgpart on any packages that don't have it
1758 $search = FS::Cursor->new('part_pkg', { 'family_pkgpart' => '' });
1759 while (my $part_pkg = $search->fetch) {
1760 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1761 my $error = $part_pkg->SUPER::replace;
1763 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
1770 my @part_pkg_option = qsearch('part_pkg_option',
1771 { 'optionname' => 'unused_credit',
1774 foreach my $old_opt (@part_pkg_option) {
1775 my $pkgpart = $old_opt->pkgpart;
1776 my $error = $old_opt->delete;
1777 die $error if $error;
1779 foreach (qw(unused_credit_cancel unused_credit_change)) {
1780 my $new_opt = new FS::part_pkg_option {
1781 'pkgpart' => $pkgpart,
1785 $error = $new_opt->insert;
1786 die $error if $error;
1790 # migrate use_disposition_taqua and use_disposition to disposition_in
1791 @part_pkg_option = qsearch('part_pkg_option',
1792 { 'optionname' => { op => 'LIKE',
1793 value => 'use_disposition%',
1797 my %newopts = map { $_->pkgpart => $_ }
1798 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1799 foreach my $old_opt (@part_pkg_option) {
1800 my $pkgpart = $old_opt->pkgpart;
1801 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1803 my $error = $old_opt->delete;
1804 die $error if $error;
1806 if ( exists($newopts{$pkgpart}) ) {
1807 my $opt = $newopts{$pkgpart};
1808 $opt->optionvalue($opt->optionvalue.",$newval");
1809 $error = $opt->replace;
1810 die $error if $error;
1812 my $new_opt = new FS::part_pkg_option {
1813 'pkgpart' => $pkgpart,
1814 'optionname' => 'disposition_in',
1815 'optionvalue' => $newval,
1817 $error = $new_opt->insert;
1818 die $error if $error;
1819 $newopts{$pkgpart} = $new_opt;
1823 # set any package with FCC voice lines to the "VoIP with broadband" category
1824 # for backward compatibility
1826 # recover from a bad upgrade bug
1827 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1828 if (!FS::upgrade_journal->is_done($upgrade)) {
1829 my $bad_upgrade = qsearchs('upgrade_journal',
1830 { upgrade => 'part_pkg_fcc_voip_class' }
1832 if ( $bad_upgrade ) {
1833 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1834 ' AND history_date > '.($bad_upgrade->_date - 3600);
1835 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1838 'table' => 'h_part_pkg_option',
1840 'extra_sql' => "$where AND history_action = 'delete'",
1841 'order_by' => 'ORDER BY history_date ASC',
1843 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1846 'table' => 'h_pkg_svc',
1848 'extra_sql' => "$where AND history_action = 'replace_old'",
1849 'order_by' => 'ORDER BY history_date ASC',
1852 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1853 my $pkgpart ||= $deleted->pkgpart;
1854 $opt{$pkgpart} ||= {
1860 if ( $deleted->isa('FS::part_pkg_option') ) {
1861 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1863 my $svcpart = $deleted->svcpart;
1864 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1865 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1866 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1869 foreach my $pkgpart (keys %opt) {
1870 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1871 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1873 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1876 } # $bad_upgrade exists
1877 else { # do the original upgrade, but correctly this time
1878 my @part_pkg = qsearch('part_pkg', {
1879 fcc_ds0s => { op => '>', value => 0 },
1880 fcc_voip_class => ''
1882 foreach my $part_pkg (@part_pkg) {
1883 $part_pkg->set(fcc_voip_class => 2);
1884 my @pkg_svc = $part_pkg->pkg_svc;
1885 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1886 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1887 my $error = $part_pkg->replace(
1888 $part_pkg->replace_old,
1889 options => { $part_pkg->options },
1890 pkg_svc => \%quantity,
1891 hidden_svc => \%hidden,
1892 primary_svc => ($part_pkg->svcpart || ''),
1894 die $error if $error;
1897 FS::upgrade_journal->set_done($upgrade);
1902 =item curuser_pkgs_sql
1904 Returns an SQL fragment for searching for packages the current user can
1905 use, either via part_pkg.agentnum directly, or via agent type (see
1910 sub curuser_pkgs_sql {
1913 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1917 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1919 Returns an SQL fragment for searching for packages the provided agent or agents
1920 can use, either via part_pkg.agentnum directly, or via agent type (see
1925 sub agent_pkgs_sql {
1926 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1927 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1929 $class->_pkgs_sql(@agentnums); #is this why
1934 my( $class, @agentnums ) = @_;
1935 my $agentnums = join(',', @agentnums);
1939 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1940 OR ( agentnum IS NULL
1941 AND EXISTS ( SELECT 1
1943 LEFT JOIN agent_type USING ( typenum )
1944 LEFT JOIN agent AS typeagent USING ( typenum )
1945 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1946 AND typeagent.agentnum IN ($agentnums)
1964 #false laziness w/part_export & cdr
1966 foreach my $INC ( @INC ) {
1967 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1968 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1969 warn "attempting to load plan info from $file\n" if $DEBUG;
1970 $file =~ /\/(\w+)\.pm$/ or do {
1971 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1975 my $info = eval "use FS::part_pkg::$mod; ".
1976 "\\%FS::part_pkg::$mod\::info;";
1978 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1981 unless ( keys %$info ) {
1982 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1985 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1986 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1987 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1990 $info{$mod} = $info;
1991 $info->{'weight'} ||= 0; # quiet warnings
1995 # copy one level deep to allow replacement of fields and fieldorder
1996 tie %plans, 'Tie::IxHash',
1997 map { my %infohash = %{ $info{$_} };
1999 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
2002 # inheritance of plan options
2003 foreach my $name (keys(%info)) {
2004 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
2005 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
2006 delete $plans{$name};
2009 my $parents = $info{$name}->{'inherit_fields'} || [];
2010 my (%fields, %field_exists, @fieldorder);
2011 foreach my $parent ($name, @$parents) {
2012 if ( !exists($info{$parent}) ) {
2013 warn "$name tried to inherit from nonexistent '$parent'\n";
2016 %fields = ( # avoid replacing existing fields
2017 %{ $info{$parent}->{'fields'} || {} },
2020 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2022 next if $field_exists{$_};
2023 $field_exists{$_} = 1;
2024 # allow inheritors to remove inherited fields from the fieldorder
2025 push @fieldorder, $_ if !exists($fields{$_}) or
2026 !exists($fields{$_}->{'disabled'});
2029 $plans{$name}->{'fields'} = \%fields;
2030 $plans{$name}->{'fieldorder'} = \@fieldorder;
2040 =head1 NEW PLAN CLASSES
2042 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2043 found in eg/plan_template.pm. Until then, it is suggested that you use the
2044 other modules in FS/FS/part_pkg/ as a guide.
2048 The delete method is unimplemented.
2050 setup and recur semantics are not yet defined (and are implemented in
2051 FS::cust_bill. hmm.). now they're deprecated and need to go.
2055 part_pkg_taxrate is Pg specific
2057 replace should be smarter about managing the related tables (options, pkg_svc)
2061 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2062 schema.html from the base documentation.