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 );
8 use Time::Local qw( timelocal timelocal_nocheck );
11 use FS::Record qw( qsearch qsearchs dbh dbdef );
17 use FS::part_pkg_option;
20 use FS::part_pkg_msgcat;
21 use FS::part_pkg_taxrate;
22 use FS::part_pkg_taxoverride;
23 use FS::part_pkg_taxproduct;
24 use FS::part_pkg_link;
25 use FS::part_pkg_discount;
26 use FS::part_pkg_usage;
27 use FS::part_pkg_vendor;
28 use FS::part_pkg_currency;
32 $skip_pkg_svc_hack = 0;
36 FS::part_pkg - Object methods for part_pkg objects
42 $record = new FS::part_pkg \%hash
43 $record = new FS::part_pkg { 'column' => 'value' };
45 $custom_record = $template_record->clone;
47 $error = $record->insert;
49 $error = $new_record->replace($old_record);
51 $error = $record->delete;
53 $error = $record->check;
55 @pkg_svc = $record->pkg_svc;
57 $svcnum = $record->svcpart;
58 $svcnum = $record->svcpart( 'svc_acct' );
62 An FS::part_pkg object represents a package definition. FS::part_pkg
63 inherits from FS::Record. The following fields are currently supported:
67 =item pkgpart - primary key (assigned automatically for new package definitions)
69 =item pkg - Text name of this package definition (customer-viewable)
71 =item comment - Text name of this package definition (non-customer-viewable)
73 =item classnum - Optional package class (see L<FS::pkg_class>)
75 =item promo_code - Promotional code
77 =item setup - Setup fee expression (deprecated)
79 =item freq - Frequency of recurring fee
81 =item recur - Recurring fee expression (deprecated)
83 =item setuptax - Setup fee tax exempt flag, empty or `Y'
85 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
87 =item taxclass - Tax class
89 =item plan - Price plan
91 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
93 =item disabled - Disabled flag, empty or `Y'
95 =item custom - Custom flag, empty or `Y'
97 =item setup_cost - for cost tracking
99 =item recur_cost - for cost tracking
101 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
103 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
105 =item agentnum - Optional agentnum (see L<FS::agent>)
107 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
109 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
112 =item successor - Foreign key for the part_pkg that replaced this record.
113 If this record is not obsolete, will be null.
115 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
116 ancestor of this record. If this record is not a successor to another
117 part_pkg, will be equal to pkgpart.
119 =item delay_start - Number of days to delay package start, by default
129 Creates a new package definition. To add the package definition to
130 the database, see L<"insert">.
134 sub table { 'part_pkg'; }
138 An alternate constructor. Creates a new package definition by duplicating
139 an existing definition. A new pkgpart is assigned and the custom flag is
140 set to Y. To add the package definition to the database, see L<"insert">.
146 my $class = ref($self);
147 my %hash = $self->hash;
148 $hash{'pkgpart'} = '';
149 $hash{'custom'} = 'Y';
150 #new FS::part_pkg ( \%hash ); # ?
151 new $class ( \%hash ); # ?
154 =item insert [ , OPTION => VALUE ... ]
156 Adds this package definition to the database. If there is an error,
157 returns the error, otherwise returns false.
159 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
160 I<custnum_ref> and I<options>.
162 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
163 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
164 be set to a hashref of svcparts and flag values ('Y' or '') to set the
165 'hidden' field in these records.
167 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
168 FS::pkg_svc record will be updated.
170 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
171 record itself), the object will be updated to point to this package definition.
173 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
174 the scalar will be updated with the custnum value from the cust_pkg record.
176 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
177 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
178 records will be inserted.
180 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
181 records will be inserted.
183 If I<part_pkg_currency> is set to a hashref of options (with the keys as
184 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
191 warn "FS::part_pkg::insert called on $self with options ".
192 join(', ', map "$_=>$options{$_}", keys %options)
195 local $SIG{HUP} = 'IGNORE';
196 local $SIG{INT} = 'IGNORE';
197 local $SIG{QUIT} = 'IGNORE';
198 local $SIG{TERM} = 'IGNORE';
199 local $SIG{TSTP} = 'IGNORE';
200 local $SIG{PIPE} = 'IGNORE';
202 my $oldAutoCommit = $FS::UID::AutoCommit;
203 local $FS::UID::AutoCommit = 0;
206 warn " inserting part_pkg record" if $DEBUG;
207 my $error = $self->SUPER::insert( $options{options} );
209 $dbh->rollback if $oldAutoCommit;
214 if ( $self->get('family_pkgpart') eq '' ) {
215 $self->set('family_pkgpart' => $self->pkgpart);
216 $error = $self->SUPER::replace;
218 $dbh->rollback if $oldAutoCommit;
223 my $conf = new FS::Conf;
224 if ( $conf->exists('agent_defaultpkg') ) {
225 warn " agent_defaultpkg set; allowing all agents to purchase package"
227 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
228 my $type_pkgs = new FS::type_pkgs({
229 'typenum' => $agent_type->typenum,
230 'pkgpart' => $self->pkgpart,
232 my $error = $type_pkgs->insert;
234 $dbh->rollback if $oldAutoCommit;
240 warn " inserting part_pkg_taxoverride records" if $DEBUG;
241 my %overrides = %{ $options{'tax_overrides'} || {} };
242 foreach my $usage_class ( keys %overrides ) {
244 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
245 ? $overrides{$usage_class}
247 my @overrides = (grep "$_", split(',', $override) );
248 my $error = $self->process_m2m (
249 'link_table' => 'part_pkg_taxoverride',
250 'target_table' => 'tax_class',
251 'hashref' => { 'usage_class' => $usage_class },
252 'params' => \@overrides,
255 $dbh->rollback if $oldAutoCommit;
260 warn " inserting part_pkg_currency records" if $DEBUG;
261 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
262 foreach my $key ( keys %part_pkg_currency ) {
263 $key =~ /^(.+)_([A-Z]{3})$/ or next;
264 my $part_pkg_currency = new FS::part_pkg_currency {
265 'pkgpart' => $self->pkgpart,
268 'optionvalue' => $part_pkg_currency{$key},
270 my $error = $part_pkg_currency->insert;
272 $dbh->rollback if $oldAutoCommit;
277 unless ( $skip_pkg_svc_hack ) {
279 warn " inserting pkg_svc records" if $DEBUG;
280 my $pkg_svc = $options{'pkg_svc'} || {};
281 my $hidden_svc = $options{'hidden_svc'} || {};
282 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
283 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
285 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
289 my $pkg_svc = new FS::pkg_svc( {
290 'pkgpart' => $self->pkgpart,
291 'svcpart' => $part_svc->svcpart,
292 'quantity' => $quantity,
293 'primary_svc' => $primary_svc,
294 'hidden' => $hidden_svc->{$part_svc->svcpart},
296 my $error = $pkg_svc->insert;
298 $dbh->rollback if $oldAutoCommit;
305 if ( $options{'cust_pkg'} ) {
306 warn " updating cust_pkg record " if $DEBUG;
308 ref($options{'cust_pkg'})
309 ? $options{'cust_pkg'}
310 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
311 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
312 if $options{'custnum_ref'};
313 my %hash = $old_cust_pkg->hash;
314 $hash{'pkgpart'} = $self->pkgpart,
315 my $new_cust_pkg = new FS::cust_pkg \%hash;
316 local($FS::cust_pkg::disable_agentcheck) = 1;
317 my $error = $new_cust_pkg->replace($old_cust_pkg);
319 $dbh->rollback if $oldAutoCommit;
320 return "Error modifying cust_pkg record: $error";
324 if ( $options{'part_pkg_vendor'} ) {
325 while ( my ($exportnum, $vendor_pkg_id) =
326 each %{ $options{part_pkg_vendor} }
329 my $ppv = new FS::part_pkg_vendor( {
330 'pkgpart' => $self->pkgpart,
331 'exportnum' => $exportnum,
332 'vendor_pkg_id' => $vendor_pkg_id,
334 my $error = $ppv->insert;
336 $dbh->rollback if $oldAutoCommit;
337 return "Error inserting part_pkg_vendor record: $error";
342 warn " committing transaction" if $DEBUG and $oldAutoCommit;
343 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
350 Currently unimplemented.
355 return "Can't (yet?) delete package definitions.";
356 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
359 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
361 Replaces OLD_RECORD with this one in the database. If there is an error,
362 returns the error, otherwise returns false.
364 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
367 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
368 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
369 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
370 'hidden' field in these records. I<bulk_skip> can be set to a hashref of
371 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
374 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
375 FS::pkg_svc record will be updated.
377 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
380 If I<part_pkg_currency> is set to a hashref of options (with the keys as
381 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
388 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
393 ( ref($_[0]) eq 'HASH' )
397 $options->{options} = { $old->options } unless defined($options->{options});
399 warn "FS::part_pkg::replace called on $new to replace $old with options".
400 join(', ', map "$_ => ". $options->{$_}, keys %$options)
403 local $SIG{HUP} = 'IGNORE';
404 local $SIG{INT} = 'IGNORE';
405 local $SIG{QUIT} = 'IGNORE';
406 local $SIG{TERM} = 'IGNORE';
407 local $SIG{TSTP} = 'IGNORE';
408 local $SIG{PIPE} = 'IGNORE';
410 my $oldAutoCommit = $FS::UID::AutoCommit;
411 local $FS::UID::AutoCommit = 0;
414 my $conf = new FS::Conf;
415 if ( $conf->exists('part_pkg-lineage') ) {
416 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
417 qw(setup_fee recur_fee) #others? config?
420 warn " superseding package" if $DEBUG;
422 my $error = $new->supersede($old, %$options);
424 $dbh->rollback if $oldAutoCommit;
428 warn " committing transaction" if $DEBUG and $oldAutoCommit;
429 $dbh->commit if $oldAutoCommit;
436 #plandata shit stays in replace for upgrades until after 2.0 (or edit
438 warn " saving legacy plandata" if $DEBUG;
439 my $plandata = $new->get('plandata');
440 $new->set('plandata', '');
442 warn " deleting old part_pkg_option records" if $DEBUG;
443 foreach my $part_pkg_option ( $old->part_pkg_option ) {
444 my $error = $part_pkg_option->delete;
446 $dbh->rollback if $oldAutoCommit;
451 warn " replacing part_pkg record" if $DEBUG;
452 my $error = $new->SUPER::replace($old, $options->{options} );
454 $dbh->rollback if $oldAutoCommit;
458 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
459 foreach my $part_pkg_option (
460 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
461 return "illegal plandata: $plandata";
463 new FS::part_pkg_option {
464 'pkgpart' => $new->pkgpart,
469 split("\n", $plandata)
471 my $error = $part_pkg_option->insert;
473 $dbh->rollback if $oldAutoCommit;
478 #trivial nit: not the most efficient to delete and reinsert
479 warn " deleting old part_pkg_currency records" if $DEBUG;
480 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
481 my $error = $part_pkg_currency->delete;
483 $dbh->rollback if $oldAutoCommit;
484 return "error deleting part_pkg_currency record: $error";
488 warn " inserting new part_pkg_currency records" if $DEBUG;
489 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
490 foreach my $key ( keys %part_pkg_currency ) {
491 $key =~ /^(.+)_([A-Z]{3})$/ or next;
492 my $part_pkg_currency = new FS::part_pkg_currency {
493 'pkgpart' => $new->pkgpart,
496 'optionvalue' => $part_pkg_currency{$key},
498 my $error = $part_pkg_currency->insert;
500 $dbh->rollback if $oldAutoCommit;
501 return "error inserting part_pkg_currency record: $error";
506 warn " replacing pkg_svc records" if $DEBUG;
507 my $pkg_svc = $options->{'pkg_svc'};
508 my $hidden_svc = $options->{'hidden_svc'} || {};
509 my $bulk_skip = $options->{'bulk_skip'} || {};
510 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
511 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
512 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
513 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
514 my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
516 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
517 && $options->{'primary_svc'} == $part_svc->svcpart
522 my $old_pkg_svc = qsearchs('pkg_svc', {
523 'pkgpart' => $old->pkgpart,
524 'svcpart' => $part_svc->svcpart,
527 my $old_quantity = 0;
528 my $old_primary_svc = '';
530 my $old_bulk_skip = '';
531 if ( $old_pkg_svc ) {
532 $old_quantity = $old_pkg_svc->quantity;
533 $old_primary_svc = $old_pkg_svc->primary_svc
534 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
535 $old_hidden = $old_pkg_svc->hidden;
536 $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
539 next unless $old_quantity != $quantity
540 || $old_primary_svc ne $primary_svc
541 || $old_hidden ne $hidden
542 || $old_bulk_skip ne $bulk_skip;
544 my $new_pkg_svc = new FS::pkg_svc( {
545 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
546 'pkgpart' => $new->pkgpart,
547 'svcpart' => $part_svc->svcpart,
548 'quantity' => $quantity,
549 'primary_svc' => $primary_svc,
551 'bulk_skip' => $bulk_skip,
553 my $error = $old_pkg_svc
554 ? $new_pkg_svc->replace($old_pkg_svc)
555 : $new_pkg_svc->insert;
557 $dbh->rollback if $oldAutoCommit;
561 } #if $options->{pkg_svc}
563 my @part_pkg_vendor = $old->part_pkg_vendor;
564 my @current_exportnum = ();
565 if ( $options->{'part_pkg_vendor'} ) {
566 my($exportnum,$vendor_pkg_id);
567 while ( ($exportnum,$vendor_pkg_id)
568 = each %{$options->{'part_pkg_vendor'}} ) {
570 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
571 if($exportnum == $part_pkg_vendor->exportnum
572 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
573 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
574 my $error = $part_pkg_vendor->replace;
576 $dbh->rollback if $oldAutoCommit;
577 return "Error replacing part_pkg_vendor record: $error";
582 elsif($exportnum == $part_pkg_vendor->exportnum
583 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
588 unless ( $noinsert ) {
589 my $ppv = new FS::part_pkg_vendor( {
590 'pkgpart' => $new->pkgpart,
591 'exportnum' => $exportnum,
592 'vendor_pkg_id' => $vendor_pkg_id,
594 my $error = $ppv->insert;
596 $dbh->rollback if $oldAutoCommit;
597 return "Error inserting part_pkg_vendor record: $error";
600 push @current_exportnum, $exportnum;
603 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
604 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
605 my $error = $part_pkg_vendor->delete;
607 $dbh->rollback if $oldAutoCommit;
608 return "Error deleting part_pkg_vendor record: $error";
613 # propagate changes to certain core fields
614 if ( $conf->exists('part_pkg-lineage') ) {
615 warn " propagating changes to family" if $DEBUG;
616 my $error = $new->propagate($old);
618 $dbh->rollback if $oldAutoCommit;
623 warn " committing transaction" if $DEBUG and $oldAutoCommit;
624 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
630 Checks all fields to make sure this is a valid package definition. If
631 there is an error, returns the error, otherwise returns false. Called by the
632 insert and replace methods.
638 warn "FS::part_pkg::check called on $self" if $DEBUG;
640 for (qw(setup recur plandata)) {
641 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
642 return "Use of $_ field is deprecated; set a plan and options: ".
644 if length($self->get($_));
648 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
649 my $error = $self->ut_number('freq');
650 return $error if $error;
652 $self->freq =~ /^(\d+[hdw]?)$/
653 or return "Illegal or empty freq: ". $self->freq;
657 my @null_agentnum_right = ( 'Edit global package definitions' );
658 push @null_agentnum_right, 'One-time charge'
659 if $self->freq =~ /^0/;
660 push @null_agentnum_right, 'Customize customer package'
661 if $self->disabled eq 'Y'; #good enough
663 my $error = $self->ut_numbern('pkgpart')
664 || $self->ut_text('pkg')
665 || $self->ut_text('comment')
666 || $self->ut_textn('promo_code')
667 || $self->ut_alphan('plan')
668 || $self->ut_enum('setuptax', [ '', 'Y' ] )
669 || $self->ut_enum('recurtax', [ '', 'Y' ] )
670 || $self->ut_textn('taxclass')
671 || $self->ut_enum('disabled', [ '', 'Y' ] )
672 || $self->ut_enum('custom', [ '', 'Y' ] )
673 || $self->ut_enum('no_auto', [ '', 'Y' ])
674 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
675 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
676 #|| $self->ut_moneyn('setup_cost')
677 #|| $self->ut_moneyn('recur_cost')
678 || $self->ut_floatn('setup_cost')
679 || $self->ut_floatn('recur_cost')
680 || $self->ut_floatn('pay_weight')
681 || $self->ut_floatn('credit_weight')
682 || $self->ut_numbern('taxproductnum')
683 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
684 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
685 || $self->ut_foreign_keyn('taxproductnum',
686 'part_pkg_taxproduct',
690 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
691 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
693 || $self->ut_numbern('fcc_ds0s')
694 || $self->ut_numbern('fcc_voip_class')
695 || $self->ut_numbern('delay_start')
696 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
697 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
698 || $self->SUPER::check
700 return $error if $error;
702 return 'Unknown plan '. $self->plan
703 unless exists($plans{$self->plan});
705 my $conf = new FS::Conf;
706 return 'Taxclass is required'
707 if ! $self->taxclass && $conf->exists('require_taxclasses');
712 =item supersede OLD [, OPTION => VALUE ... ]
714 Inserts this package as a successor to the package OLD. All options are as
715 for C<insert>. After inserting, disables OLD and sets the new package as its
721 my ($new, $old, %options) = @_;
724 $new->set('pkgpart' => '');
725 $new->set('family_pkgpart' => $old->family_pkgpart);
726 warn " inserting successor package\n" if $DEBUG;
727 $error = $new->insert(%options);
728 return $error if $error;
730 warn " disabling superseded package\n" if $DEBUG;
731 $old->set('successor' => $new->pkgpart);
732 $old->set('disabled' => 'Y');
733 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
734 return $error if $error;
736 warn " propagating changes to family" if $DEBUG;
737 $new->propagate($old);
742 If any of certain fields have changed from OLD to this package, then,
743 for all packages in the same lineage as this one, sets those fields
744 to their values in this package.
748 my @propagate_fields = (
749 qw( pkg classnum setup_cost recur_cost taxclass
750 setuptax recurtax pay_weight credit_weight
758 map { $_ => $new->get($_) }
759 grep { $new->get($_) ne $old->get($_) }
763 my @part_pkg = qsearch('part_pkg', {
764 'family_pkgpart' => $new->family_pkgpart
767 foreach my $part_pkg ( @part_pkg ) {
768 my $pkgpart = $part_pkg->pkgpart;
769 next if $pkgpart == $new->pkgpart; # don't modify $new
770 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
771 foreach ( keys %fields ) {
772 $part_pkg->set($_, $fields{$_});
774 # SUPER::replace to avoid changing non-core fields
775 my $error = $part_pkg->SUPER::replace;
776 push @error, "pkgpart $pkgpart: $error"
782 =item pkg_locale LOCALE
784 Returns a customer-viewable string representing this package for the given
785 locale, from the part_pkg_msgcat table. If the given locale is empty or no
786 localized string is found, returns the base pkg field.
791 my( $self, $locale ) = @_;
792 return $self->pkg unless $locale;
793 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
794 $part_pkg_msgcat->pkg;
797 =item part_pkg_msgcat LOCALE
799 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
803 sub part_pkg_msgcat {
804 my( $self, $locale ) = @_;
805 qsearchs( 'part_pkg_msgcat', {
806 pkgpart => $self->pkgpart,
811 =item pkg_comment [ OPTION => VALUE... ]
813 Returns an (internal) string representing this package. Currently,
814 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
815 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
818 If the option nopkgpart is true then the "pkgpart: ' is omitted.
826 #$self->pkg. ' - '. $self->comment;
827 #$self->pkg. ' ('. $self->comment. ')';
828 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
829 $pre. $self->pkg. ' - '. $self->custom_comment;
832 sub price_info { # safety, in case a part_pkg hasn't defined price_info
838 ( $self->custom ? '(CUSTOM) ' : '' ). $self->comment . ' ' . $self->price_info;
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 { 1; }
1092 # the default start date; takes an FS::cust_main as an argument
1093 sub default_start_date {
1095 my $cust_main = shift;
1096 my $conf = FS::Conf->new;
1098 if ( $self->delay_start ) {
1099 my $delay = $self->delay_start;
1101 my ($mday,$mon,$year) = (localtime(time))[3,4,5];
1102 my $start_date = timelocal(0,0,0,$mday,$mon,$year) + 86400 * $delay;
1105 } elsif ( $conf->exists('order_pkg-no_start_date') ) {
1109 } elsif ( $cust_main ) {
1111 return $cust_main->next_bill_date;
1120 sub can_currency_exchange { 0; }
1123 # moved to FS::Misc to make this accessible to other packages
1125 FS::Misc::pkg_freqs();
1130 Returns an english representation of the I<freq> field, such as "monthly",
1131 "weekly", "semi-annually", etc.
1137 my $freq = $self->freq;
1139 #my $freqs_href = $self->freqs_href;
1140 my $freqs_href = freqs_href();
1142 if ( exists($freqs_href->{$freq}) ) {
1143 $freqs_href->{$freq};
1145 my $interval = 'month';
1146 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1147 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1148 $interval = $interval{$2};
1153 "every $freq ${interval}s";
1158 =item add_freq TIMESTAMP [ FREQ ]
1160 Adds a billing period of some frequency to the provided timestamp and
1161 returns the resulting timestamp, or -1 if the frequency could not be
1162 parsed (shouldn't happen). By default, the frequency of this package
1163 will be used; to override this, pass a different frequency as a second
1169 my( $self, $date, $freq ) = @_;
1170 $freq = $self->freq unless $freq;
1172 #change this bit to use Date::Manip? CAREFUL with timezones (see
1173 # mailing list archive)
1174 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1176 if ( $freq =~ /^\d+$/ ) {
1178 until ( $mon < 12 ) { $mon -= 12; $year++; }
1180 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1182 } elsif ( $freq =~ /^(\d+)w$/ ) {
1184 $mday += $weeks * 7;
1185 } elsif ( $freq =~ /^(\d+)d$/ ) {
1188 } elsif ( $freq =~ /^(\d+)h$/ ) {
1195 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1200 For backwards compatibility, returns the plandata field as well as all options
1201 from FS::part_pkg_option.
1207 carp "plandata is deprecated";
1209 $self->SUPER::plandata(@_);
1211 my $plandata = $self->get('plandata');
1212 my %options = $self->options;
1213 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1218 =item part_pkg_vendor
1220 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1221 L<FS::part_pkg_vendor>).
1225 sub part_pkg_vendor {
1227 qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1230 =item vendor_pkg_ids
1232 Returns a list of vendor/external package ids by exportnum
1236 sub vendor_pkg_ids {
1238 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1241 =item part_pkg_option
1243 Returns all options as FS::part_pkg_option objects (see
1244 L<FS::part_pkg_option>).
1248 sub part_pkg_option {
1250 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1255 Returns a list of option names and values suitable for assigning to a hash.
1261 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1264 =item option OPTIONNAME [ QUIET ]
1266 Returns the option value for the given name, or the empty string. If a true
1267 value is passed as the second argument, warnings about missing the option
1273 my( $self, $opt, $ornull ) = @_;
1274 my $part_pkg_option =
1275 qsearchs('part_pkg_option', {
1276 pkgpart => $self->pkgpart,
1279 return $part_pkg_option->optionvalue if $part_pkg_option;
1280 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1281 split("\n", $self->get('plandata') );
1282 return $plandata{$opt} if exists $plandata{$opt};
1283 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1284 "not found in options or plandata!\n"
1289 =item part_pkg_currency [ CURRENCY ]
1291 Returns all currency options as FS::part_pkg_currency objects (see
1292 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1293 objects for that currency.
1297 sub part_pkg_currency {
1299 my %hash = ( 'pkgpart' => $self->pkgpart );
1300 $hash{'currency'} = shift if @_;
1301 qsearch('part_pkg_currency', \%hash );
1304 =item part_pkg_currency_options CURRENCY
1306 Returns a list of option names and values from FS::part_pkg_currency for the
1311 sub part_pkg_currency_options {
1313 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1316 =item part_pkg_currency_option CURRENCY OPTIONNAME
1318 Returns the option value for the given name and currency.
1322 sub part_pkg_currency_option {
1323 my( $self, $currency, $optionname ) = @_;
1324 my $part_pkg_currency =
1325 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1326 'currency' => $currency,
1327 'optionname' => $optionname,
1330 #fatal if not found? that works for our use cases from
1331 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1332 #to behave. have to catch it there if we change it here...
1333 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1335 $part_pkg_currency->optionvalue;
1338 =item bill_part_pkg_link
1340 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1344 sub bill_part_pkg_link {
1345 shift->_part_pkg_link('bill', @_);
1348 =item svc_part_pkg_link
1350 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1354 sub svc_part_pkg_link {
1355 shift->_part_pkg_link('svc', @_);
1358 =item supp_part_pkg_link
1360 Returns the associated part_pkg_link records of type 'supp' (supplemental
1365 sub supp_part_pkg_link {
1366 shift->_part_pkg_link('supp', @_);
1369 sub _part_pkg_link {
1370 my( $self, $type ) = @_;
1371 qsearch({ table => 'part_pkg_link',
1372 hashref => { 'src_pkgpart' => $self->pkgpart,
1373 'link_type' => $type,
1374 #protection against infinite recursive links
1375 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1377 order_by => "ORDER BY hidden",
1381 sub self_and_bill_linked {
1382 shift->_self_and_linked('bill', @_);
1385 sub self_and_svc_linked {
1386 shift->_self_and_linked('svc', @_);
1389 sub _self_and_linked {
1390 my( $self, $type, $hidden ) = @_;
1394 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1395 $self->_part_pkg_link($type) ) )
1397 $_->hidden($hidden) if $hidden;
1404 =item part_pkg_taxoverride [ CLASS ]
1406 Returns all associated FS::part_pkg_taxoverride objects (see
1407 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1408 of class CLASS if defined. Class may be one of 'setup', 'recur',
1409 the empty string (default), or a usage class number (see L<FS::usage_class>).
1410 When a class is specified, the empty string class (default) is returned
1411 if no more specific values exist.
1415 sub part_pkg_taxoverride {
1419 my $hashref = { 'pkgpart' => $self->pkgpart };
1420 $hashref->{'usage_class'} = $class if defined($class);
1421 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1423 unless ( scalar(@overrides) || !defined($class) || !$class ){
1424 $hashref->{'usage_class'} = '';
1425 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1431 =item has_taxproduct
1433 Returns true if this package has any taxproduct associated with it.
1437 sub has_taxproduct {
1440 $self->taxproductnum ||
1441 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1442 keys %{ {$self->options} }
1448 =item taxproduct [ CLASS ]
1450 Returns the associated tax product for this package definition (see
1451 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1452 the usage classnum (see L<FS::usage_class>). Returns the default
1453 tax product for this record if the more specific CLASS value does
1462 my $part_pkg_taxproduct;
1464 my $taxproductnum = $self->taxproductnum;
1466 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1467 $taxproductnum = $class_taxproductnum
1468 if $class_taxproductnum
1471 $part_pkg_taxproduct =
1472 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1474 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1475 $taxproductnum = $self->taxproductnum;
1476 $part_pkg_taxproduct =
1477 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1480 $part_pkg_taxproduct;
1483 =item taxproduct_description [ CLASS ]
1485 Returns the description of the associated tax product for this package
1486 definition (see L<FS::part_pkg_taxproduct>).
1490 sub taxproduct_description {
1492 my $part_pkg_taxproduct = $self->taxproduct(@_);
1493 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1496 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1498 Returns the package to taxrate m2m records for this package in the location
1499 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1500 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1501 (see L<FS::usage_class>).
1505 sub _expand_cch_taxproductnum {
1508 my $part_pkg_taxproduct = $self->taxproduct($class);
1510 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1511 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1514 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1515 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1516 OR taxproduct = '$a:$b:$c:'
1517 OR taxproduct = '$a:$b:".":$d'
1518 OR taxproduct = '$a:$b:".":' )";
1519 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1520 'hashref' => { 'data_vendor'=>'cch' },
1521 'extra_sql' => $extra_sql,
1526 sub part_pkg_taxrate {
1528 my ($data_vendor, $geocode, $class) = @_;
1531 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1532 dbh->quote($data_vendor);
1534 # CCH oddness in m2m
1535 $extra_sql .= ' AND ('.
1536 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1540 # much more CCH oddness in m2m -- this is kludgy
1541 my @tpnums = $self->_expand_cch_taxproductnum($class);
1542 if (scalar(@tpnums)) {
1543 $extra_sql .= ' AND ('.
1544 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1547 $extra_sql .= ' AND ( 0 = 1 )';
1550 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1551 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1552 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1554 # should qsearch preface columns with the table to facilitate joins?
1555 qsearch( { 'table' => 'part_pkg_taxrate',
1556 'select' => $select,
1557 'hashref' => { # 'data_vendor' => $data_vendor,
1558 # 'taxproductnum' => $self->taxproductnum,
1560 'addl_from' => $addl_from,
1561 'extra_sql' => $extra_sql,
1562 'order_by' => $order_by,
1566 =item part_pkg_discount
1568 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1573 sub part_pkg_discount {
1575 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1578 =item part_pkg_usage
1580 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1585 sub part_pkg_usage {
1587 qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1592 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1593 PLAN is the object's I<plan> field. There should be better docs
1594 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1600 my $plan = $self->plan;
1602 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1606 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1607 my $class = ref($self). "::$plan";
1608 warn "reblessing $self into $class" if $DEBUG > 1;
1611 bless($self, $class) unless $@;
1616 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1617 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1619 #fallback that return 0 for old legacy packages with no plan
1620 sub calc_remain { 0; }
1621 sub calc_units { 0; }
1623 #fallback for everything not based on flat.pm
1624 sub recur_temporality { 'upcoming'; }
1625 sub calc_cancel { 0; }
1627 #fallback for everything except bulk.pm
1628 sub hide_svc_detail { 0; }
1630 #fallback for packages that can't/won't summarize usage
1631 sub sum_usage { 0; }
1633 =item recur_cost_permonth CUST_PKG
1635 recur_cost divided by freq (only supported for monthly and longer frequencies)
1639 sub recur_cost_permonth {
1640 my($self, $cust_pkg) = @_;
1641 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1642 sprintf('%.2f', $self->recur_cost / $self->freq );
1645 =item cust_bill_pkg_recur CUST_PKG
1647 Actual recurring charge for the specified customer package from customer's most
1652 sub cust_bill_pkg_recur {
1653 my($self, $cust_pkg) = @_;
1654 my $cust_bill_pkg = qsearchs({
1655 'table' => 'cust_bill_pkg',
1656 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1657 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1658 'recur' => { op=>'>', value=>'0' },
1660 'order_by' => 'ORDER BY cust_bill._date DESC,
1661 cust_bill_pkg.sdate DESC
1664 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1665 $cust_bill_pkg->recur;
1668 =item format OPTION DATA
1670 Returns data formatted according to the function 'format' 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}{format})) {
1678 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1684 =item parse OPTION DATA
1686 Returns data parsed according to the function 'parse' described
1687 in the plan info. Returns DATA if no such function exists.
1692 my ($self, $option, $data) = (shift, shift, shift);
1693 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1694 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1704 =head1 CLASS METHODS
1712 # Used by FS::Upgrade to migrate to a new database.
1714 sub _upgrade_data { # class method
1715 my($class, %opts) = @_;
1717 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1719 my @part_pkg = qsearch({
1720 'table' => 'part_pkg',
1721 'extra_sql' => "WHERE ". join(' OR ',
1722 'plan IS NULL', "plan = '' ",
1726 foreach my $part_pkg (@part_pkg) {
1728 unless ( $part_pkg->plan ) {
1729 $part_pkg->plan('flat');
1736 # now upgrade to the explicit custom flag
1738 @part_pkg = qsearch({
1739 'table' => 'part_pkg',
1740 'hashref' => { disabled => 'Y', custom => '' },
1741 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1744 foreach my $part_pkg (@part_pkg) {
1745 my $new = new FS::part_pkg { $part_pkg->hash };
1747 my $comment = $part_pkg->comment;
1748 $comment =~ s/^\(CUSTOM\) //;
1749 $comment = '(none)' unless $comment =~ /\S/;
1750 $new->comment($comment);
1752 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1753 my $primary = $part_pkg->svcpart;
1754 my $options = { $part_pkg->options };
1756 my $error = $new->replace( $part_pkg,
1757 'pkg_svc' => $pkg_svc,
1758 'primary_svc' => $primary,
1759 'options' => $options,
1761 die $error if $error;
1764 # set family_pkgpart on any packages that don't have it
1765 @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1766 foreach my $part_pkg (@part_pkg) {
1767 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1768 my $error = $part_pkg->SUPER::replace;
1769 die $error if $error;
1772 my @part_pkg_option = qsearch('part_pkg_option',
1773 { 'optionname' => 'unused_credit',
1776 foreach my $old_opt (@part_pkg_option) {
1777 my $pkgpart = $old_opt->pkgpart;
1778 my $error = $old_opt->delete;
1779 die $error if $error;
1781 foreach (qw(unused_credit_cancel unused_credit_change)) {
1782 my $new_opt = new FS::part_pkg_option {
1783 'pkgpart' => $pkgpart,
1787 $error = $new_opt->insert;
1788 die $error if $error;
1792 # migrate use_disposition_taqua and use_disposition to disposition_in
1793 @part_pkg_option = qsearch('part_pkg_option',
1794 { 'optionname' => { op => 'LIKE',
1795 value => 'use_disposition%',
1799 my %newopts = map { $_->pkgpart => $_ }
1800 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1801 foreach my $old_opt (@part_pkg_option) {
1802 my $pkgpart = $old_opt->pkgpart;
1803 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1805 my $error = $old_opt->delete;
1806 die $error if $error;
1808 if ( exists($newopts{$pkgpart}) ) {
1809 my $opt = $newopts{$pkgpart};
1810 $opt->optionvalue($opt->optionvalue.",$newval");
1811 $error = $opt->replace;
1812 die $error if $error;
1814 my $new_opt = new FS::part_pkg_option {
1815 'pkgpart' => $pkgpart,
1816 'optionname' => 'disposition_in',
1817 'optionvalue' => $newval,
1819 $error = $new_opt->insert;
1820 die $error if $error;
1821 $newopts{$pkgpart} = $new_opt;
1825 # set any package with FCC voice lines to the "VoIP with broadband" category
1826 # for backward compatibility
1828 # recover from a bad upgrade bug
1829 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1830 if (!FS::upgrade_journal->is_done($upgrade)) {
1831 my $bad_upgrade = qsearchs('upgrade_journal',
1832 { upgrade => 'part_pkg_fcc_voip_class' }
1834 if ( $bad_upgrade ) {
1835 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1836 ' AND history_date > '.($bad_upgrade->_date - 3600);
1837 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1840 'table' => 'h_part_pkg_option',
1842 'extra_sql' => "$where AND history_action = 'delete'",
1843 'order_by' => 'ORDER BY history_date ASC',
1845 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1848 'table' => 'h_pkg_svc',
1850 'extra_sql' => "$where AND history_action = 'replace_old'",
1851 'order_by' => 'ORDER BY history_date ASC',
1854 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1855 my $pkgpart ||= $deleted->pkgpart;
1856 $opt{$pkgpart} ||= {
1862 if ( $deleted->isa('FS::part_pkg_option') ) {
1863 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1865 my $svcpart = $deleted->svcpart;
1866 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1867 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1868 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1871 foreach my $pkgpart (keys %opt) {
1872 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1873 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1875 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1878 } # $bad_upgrade exists
1879 else { # do the original upgrade, but correctly this time
1880 @part_pkg = qsearch('part_pkg', {
1881 fcc_ds0s => { op => '>', value => 0 },
1882 fcc_voip_class => ''
1884 foreach my $part_pkg (@part_pkg) {
1885 $part_pkg->set(fcc_voip_class => 2);
1886 my @pkg_svc = $part_pkg->pkg_svc;
1887 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1888 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1889 my $error = $part_pkg->replace(
1890 $part_pkg->replace_old,
1891 options => { $part_pkg->options },
1892 pkg_svc => \%quantity,
1893 hidden_svc => \%hidden,
1894 primary_svc => ($part_pkg->svcpart || ''),
1896 die $error if $error;
1899 FS::upgrade_journal->set_done($upgrade);
1904 =item curuser_pkgs_sql
1906 Returns an SQL fragment for searching for packages the current user can
1907 use, either via part_pkg.agentnum directly, or via agent type (see
1912 sub curuser_pkgs_sql {
1915 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1919 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1921 Returns an SQL fragment for searching for packages the provided agent or agents
1922 can use, either via part_pkg.agentnum directly, or via agent type (see
1927 sub agent_pkgs_sql {
1928 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1929 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1931 $class->_pkgs_sql(@agentnums); #is this why
1936 my( $class, @agentnums ) = @_;
1937 my $agentnums = join(',', @agentnums);
1941 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1942 OR ( agentnum IS NULL
1943 AND EXISTS ( SELECT 1
1945 LEFT JOIN agent_type USING ( typenum )
1946 LEFT JOIN agent AS typeagent USING ( typenum )
1947 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1948 AND typeagent.agentnum IN ($agentnums)
1966 #false laziness w/part_export & cdr
1968 foreach my $INC ( @INC ) {
1969 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1970 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1971 warn "attempting to load plan info from $file\n" if $DEBUG;
1972 $file =~ /\/(\w+)\.pm$/ or do {
1973 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1977 my $info = eval "use FS::part_pkg::$mod; ".
1978 "\\%FS::part_pkg::$mod\::info;";
1980 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1983 unless ( keys %$info ) {
1984 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1987 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1988 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1989 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1992 $info{$mod} = $info;
1993 $info->{'weight'} ||= 0; # quiet warnings
1997 # copy one level deep to allow replacement of fields and fieldorder
1998 tie %plans, 'Tie::IxHash',
1999 map { my %infohash = %{ $info{$_} };
2001 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
2004 # inheritance of plan options
2005 foreach my $name (keys(%info)) {
2006 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
2007 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
2008 delete $plans{$name};
2011 my $parents = $info{$name}->{'inherit_fields'} || [];
2012 my (%fields, %field_exists, @fieldorder);
2013 foreach my $parent ($name, @$parents) {
2014 if ( !exists($info{$parent}) ) {
2015 warn "$name tried to inherit from nonexistent '$parent'\n";
2018 %fields = ( # avoid replacing existing fields
2019 %{ $info{$parent}->{'fields'} || {} },
2022 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2024 next if $field_exists{$_};
2025 $field_exists{$_} = 1;
2026 # allow inheritors to remove inherited fields from the fieldorder
2027 push @fieldorder, $_ if !exists($fields{$_}) or
2028 !exists($fields{$_}->{'disabled'});
2031 $plans{$name}->{'fields'} = \%fields;
2032 $plans{$name}->{'fieldorder'} = \@fieldorder;
2042 =head1 NEW PLAN CLASSES
2044 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2045 found in eg/plan_template.pm. Until then, it is suggested that you use the
2046 other modules in FS/FS/part_pkg/ as a guide.
2050 The delete method is unimplemented.
2052 setup and recur semantics are not yet defined (and are implemented in
2053 FS::cust_bill. hmm.). now they're deprecated and need to go.
2057 part_pkg_taxrate is Pg specific
2059 replace should be smarter about managing the related tables (options, pkg_svc)
2063 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2064 schema.html from the base documentation.