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 );
18 use FS::part_pkg_option;
19 use FS::part_pkg_msgcat;
20 use FS::part_pkg_taxrate;
21 use FS::part_pkg_taxoverride;
22 use FS::part_pkg_taxproduct;
23 use FS::part_pkg_link;
24 use FS::part_pkg_discount;
25 use FS::part_pkg_vendor;
26 use FS::part_pkg_currency;
30 $skip_pkg_svc_hack = 0;
34 FS::part_pkg - Object methods for part_pkg objects
40 $record = new FS::part_pkg \%hash
41 $record = new FS::part_pkg { 'column' => 'value' };
43 $custom_record = $template_record->clone;
45 $error = $record->insert;
47 $error = $new_record->replace($old_record);
49 $error = $record->delete;
51 $error = $record->check;
53 @pkg_svc = $record->pkg_svc;
55 $svcnum = $record->svcpart;
56 $svcnum = $record->svcpart( 'svc_acct' );
60 An FS::part_pkg object represents a package definition. FS::part_pkg
61 inherits from FS::Record. The following fields are currently supported:
65 =item pkgpart - primary key (assigned automatically for new package definitions)
67 =item pkg - Text name of this package definition (customer-viewable)
69 =item comment - Text name of this package definition (non-customer-viewable)
71 =item classnum - Optional package class (see L<FS::pkg_class>)
73 =item promo_code - Promotional code
75 =item setup - Setup fee expression (deprecated)
77 =item freq - Frequency of recurring fee
79 =item recur - Recurring fee expression (deprecated)
81 =item setuptax - Setup fee tax exempt flag, empty or `Y'
83 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
85 =item taxclass - Tax class
87 =item plan - Price plan
89 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
91 =item disabled - Disabled flag, empty or `Y'
93 =item custom - Custom flag, empty or `Y'
95 =item setup_cost - for cost tracking
97 =item recur_cost - for cost tracking
99 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
101 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
103 =item agentnum - Optional agentnum (see L<FS::agent>)
105 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
107 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
110 =item successor - Foreign key for the part_pkg that replaced this record.
111 If this record is not obsolete, will be null.
113 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
114 ancestor of this record. If this record is not a successor to another
115 part_pkg, will be equal to pkgpart.
117 =item delay_start - Number of days to delay package start, by default
127 Creates a new package definition. To add the package definition to
128 the database, see L<"insert">.
132 sub table { 'part_pkg'; }
136 An alternate constructor. Creates a new package definition by duplicating
137 an existing definition. A new pkgpart is assigned and the custom flag is
138 set to Y. To add the package definition to the database, see L<"insert">.
144 my $class = ref($self);
145 my %hash = $self->hash;
146 $hash{'pkgpart'} = '';
147 $hash{'custom'} = 'Y';
148 #new FS::part_pkg ( \%hash ); # ?
149 new $class ( \%hash ); # ?
152 =item insert [ , OPTION => VALUE ... ]
154 Adds this package definition to the database. If there is an error,
155 returns the error, otherwise returns false.
157 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
158 I<custnum_ref> and I<options>.
160 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
161 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
162 be set to a hashref of svcparts and flag values ('Y' or '') to set the
163 'hidden' field in these records.
165 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
166 FS::pkg_svc record will be updated.
168 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
169 record itself), the object will be updated to point to this package definition.
171 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
172 the scalar will be updated with the custnum value from the cust_pkg record.
174 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
175 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
176 records will be inserted.
178 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
179 records will be inserted.
181 If I<part_pkg_currency> is set to a hashref of options (with the keys as
182 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
189 warn "FS::part_pkg::insert called on $self with options ".
190 join(', ', map "$_=>$options{$_}", keys %options)
193 local $SIG{HUP} = 'IGNORE';
194 local $SIG{INT} = 'IGNORE';
195 local $SIG{QUIT} = 'IGNORE';
196 local $SIG{TERM} = 'IGNORE';
197 local $SIG{TSTP} = 'IGNORE';
198 local $SIG{PIPE} = 'IGNORE';
200 my $oldAutoCommit = $FS::UID::AutoCommit;
201 local $FS::UID::AutoCommit = 0;
204 warn " inserting part_pkg record" if $DEBUG;
205 my $error = $self->SUPER::insert( $options{options} );
207 $dbh->rollback if $oldAutoCommit;
212 if ( $self->get('family_pkgpart') eq '' ) {
213 $self->set('family_pkgpart' => $self->pkgpart);
214 $error = $self->SUPER::replace;
216 $dbh->rollback if $oldAutoCommit;
221 warn " inserting part_pkg_taxoverride records" if $DEBUG;
222 my %overrides = %{ $options{'tax_overrides'} || {} };
223 foreach my $usage_class ( keys %overrides ) {
225 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
226 ? $overrides{$usage_class}
228 my @overrides = (grep "$_", split(',', $override) );
229 my $error = $self->process_m2m (
230 'link_table' => 'part_pkg_taxoverride',
231 'target_table' => 'tax_class',
232 'hashref' => { 'usage_class' => $usage_class },
233 'params' => \@overrides,
236 $dbh->rollback if $oldAutoCommit;
241 warn " inserting part_pkg_currency records" if $DEBUG;
242 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
243 foreach my $key ( keys %part_pkg_currency ) {
244 $key =~ /^(.+)_([A-Z]{3})$/ or next;
245 my( $optionname, $currency ) = ( $1, $2 );
246 if ( $part_pkg_currency{$key} =~ /^\s*$/ ) {
247 if ( $self->option($optionname) == 0 ) {
248 $part_pkg_currency{$key} = '0';
250 $dbh->rollback if $oldAutoCommit;
251 ( my $thing = $optionname ) =~ s/_/ /g;
252 return ucfirst($thing). " $currency is required";
255 my $part_pkg_currency = new FS::part_pkg_currency {
256 'pkgpart' => $self->pkgpart,
257 'optionname' => $optionname,
258 'currency' => $currency,
259 'optionvalue' => $part_pkg_currency{$key},
261 my $error = $part_pkg_currency->insert;
263 $dbh->rollback if $oldAutoCommit;
268 unless ( $skip_pkg_svc_hack ) {
270 warn " inserting pkg_svc records" if $DEBUG;
271 my $pkg_svc = $options{'pkg_svc'} || {};
272 my $hidden_svc = $options{'hidden_svc'} || {};
273 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
274 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
276 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
280 my $pkg_svc = new FS::pkg_svc( {
281 'pkgpart' => $self->pkgpart,
282 'svcpart' => $part_svc->svcpart,
283 'quantity' => $quantity,
284 'primary_svc' => $primary_svc,
285 'hidden' => $hidden_svc->{$part_svc->svcpart},
287 my $error = $pkg_svc->insert;
289 $dbh->rollback if $oldAutoCommit;
296 if ( $options{'cust_pkg'} ) {
297 warn " updating cust_pkg record " if $DEBUG;
299 ref($options{'cust_pkg'})
300 ? $options{'cust_pkg'}
301 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
302 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
303 if $options{'custnum_ref'};
304 my %hash = $old_cust_pkg->hash;
305 $hash{'pkgpart'} = $self->pkgpart,
306 my $new_cust_pkg = new FS::cust_pkg \%hash;
307 local($FS::cust_pkg::disable_agentcheck) = 1;
308 my $error = $new_cust_pkg->replace($old_cust_pkg);
310 $dbh->rollback if $oldAutoCommit;
311 return "Error modifying cust_pkg record: $error";
315 if ( $options{'part_pkg_vendor'} ) {
316 while ( my ($exportnum, $vendor_pkg_id) =
317 each %{ $options{part_pkg_vendor} }
320 my $ppv = new FS::part_pkg_vendor( {
321 'pkgpart' => $self->pkgpart,
322 'exportnum' => $exportnum,
323 'vendor_pkg_id' => $vendor_pkg_id,
325 my $error = $ppv->insert;
327 $dbh->rollback if $oldAutoCommit;
328 return "Error inserting part_pkg_vendor record: $error";
333 warn " committing transaction" if $DEBUG and $oldAutoCommit;
334 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
341 Currently unimplemented.
346 return "Can't (yet?) delete package definitions.";
347 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
350 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
352 Replaces OLD_RECORD with this one in the database. If there is an error,
353 returns the error, otherwise returns false.
355 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
358 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
359 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
360 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
361 'hidden' field in these records. I<bulk_skip> can be set to a hashref of
362 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
365 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
366 FS::pkg_svc record will be updated.
368 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
371 If I<part_pkg_currency> is set to a hashref of options (with the keys as
372 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
379 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
384 ( ref($_[0]) eq 'HASH' )
388 $options->{options} = { $old->options } unless defined($options->{options});
390 warn "FS::part_pkg::replace called on $new to replace $old with options".
391 join(', ', map "$_ => ". $options->{$_}, keys %$options)
394 local $SIG{HUP} = 'IGNORE';
395 local $SIG{INT} = 'IGNORE';
396 local $SIG{QUIT} = 'IGNORE';
397 local $SIG{TERM} = 'IGNORE';
398 local $SIG{TSTP} = 'IGNORE';
399 local $SIG{PIPE} = 'IGNORE';
401 my $oldAutoCommit = $FS::UID::AutoCommit;
402 local $FS::UID::AutoCommit = 0;
405 my $conf = new FS::Conf;
406 if ( $conf->exists('part_pkg-lineage') ) {
407 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
408 qw(setup_fee recur_fee) #others? config?
411 warn " superseding package" if $DEBUG;
413 my $error = $new->supersede($old, %$options);
415 $dbh->rollback if $oldAutoCommit;
419 warn " committing transaction" if $DEBUG and $oldAutoCommit;
420 $dbh->commit if $oldAutoCommit;
427 #plandata shit stays in replace for upgrades until after 2.0 (or edit
429 warn " saving legacy plandata" if $DEBUG;
430 my $plandata = $new->get('plandata');
431 $new->set('plandata', '');
433 warn " deleting old part_pkg_option records" if $DEBUG;
434 foreach my $part_pkg_option ( $old->part_pkg_option ) {
435 my $error = $part_pkg_option->delete;
437 $dbh->rollback if $oldAutoCommit;
442 warn " replacing part_pkg record" if $DEBUG;
443 my $error = $new->SUPER::replace($old, $options->{options} );
445 $dbh->rollback if $oldAutoCommit;
449 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
450 foreach my $part_pkg_option (
451 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
452 return "illegal plandata: $plandata";
454 new FS::part_pkg_option {
455 'pkgpart' => $new->pkgpart,
460 split("\n", $plandata)
462 my $error = $part_pkg_option->insert;
464 $dbh->rollback if $oldAutoCommit;
469 #trivial nit: not the most efficient to delete and reinsert
470 warn " deleting old part_pkg_currency records" if $DEBUG;
471 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
472 my $error = $part_pkg_currency->delete;
474 $dbh->rollback if $oldAutoCommit;
475 return "error deleting part_pkg_currency record: $error";
479 warn " inserting new part_pkg_currency records" if $DEBUG;
480 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
481 foreach my $key ( keys %part_pkg_currency ) {
482 $key =~ /^(.+)_([A-Z]{3})$/ or next;
483 my $part_pkg_currency = new FS::part_pkg_currency {
484 'pkgpart' => $new->pkgpart,
487 'optionvalue' => $part_pkg_currency{$key},
489 my $error = $part_pkg_currency->insert;
491 $dbh->rollback if $oldAutoCommit;
492 return "error inserting part_pkg_currency record: $error";
497 warn " replacing pkg_svc records" if $DEBUG;
498 my $pkg_svc = $options->{'pkg_svc'};
499 my $hidden_svc = $options->{'hidden_svc'} || {};
500 my $bulk_skip = $options->{'bulk_skip'} || {};
501 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
502 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
503 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
504 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
505 my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
507 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
508 && $options->{'primary_svc'} == $part_svc->svcpart
513 my $old_pkg_svc = qsearchs('pkg_svc', {
514 'pkgpart' => $old->pkgpart,
515 'svcpart' => $part_svc->svcpart,
518 my $old_quantity = 0;
519 my $old_primary_svc = '';
521 my $old_bulk_skip = '';
522 if ( $old_pkg_svc ) {
523 $old_quantity = $old_pkg_svc->quantity;
524 $old_primary_svc = $old_pkg_svc->primary_svc
525 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
526 $old_hidden = $old_pkg_svc->hidden;
527 $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
530 next unless $old_quantity != $quantity
531 || $old_primary_svc ne $primary_svc
532 || $old_hidden ne $hidden
533 || $old_bulk_skip ne $bulk_skip;
535 my $new_pkg_svc = new FS::pkg_svc( {
536 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
537 'pkgpart' => $new->pkgpart,
538 'svcpart' => $part_svc->svcpart,
539 'quantity' => $quantity,
540 'primary_svc' => $primary_svc,
542 'bulk_skip' => $bulk_skip,
544 my $error = $old_pkg_svc
545 ? $new_pkg_svc->replace($old_pkg_svc)
546 : $new_pkg_svc->insert;
548 $dbh->rollback if $oldAutoCommit;
552 } #if $options->{pkg_svc}
554 my @part_pkg_vendor = $old->part_pkg_vendor;
555 my @current_exportnum = ();
556 if ( $options->{'part_pkg_vendor'} ) {
557 my($exportnum,$vendor_pkg_id);
558 while ( ($exportnum,$vendor_pkg_id)
559 = each %{$options->{'part_pkg_vendor'}} ) {
561 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
562 if($exportnum == $part_pkg_vendor->exportnum
563 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
564 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
565 my $error = $part_pkg_vendor->replace;
567 $dbh->rollback if $oldAutoCommit;
568 return "Error replacing part_pkg_vendor record: $error";
573 elsif($exportnum == $part_pkg_vendor->exportnum
574 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
579 unless ( $noinsert ) {
580 my $ppv = new FS::part_pkg_vendor( {
581 'pkgpart' => $new->pkgpart,
582 'exportnum' => $exportnum,
583 'vendor_pkg_id' => $vendor_pkg_id,
585 my $error = $ppv->insert;
587 $dbh->rollback if $oldAutoCommit;
588 return "Error inserting part_pkg_vendor record: $error";
591 push @current_exportnum, $exportnum;
594 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
595 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
596 my $error = $part_pkg_vendor->delete;
598 $dbh->rollback if $oldAutoCommit;
599 return "Error deleting part_pkg_vendor record: $error";
604 # propagate changes to certain core fields
605 if ( $conf->exists('part_pkg-lineage') ) {
606 warn " propagating changes to family" if $DEBUG;
607 my $error = $new->propagate($old);
609 $dbh->rollback if $oldAutoCommit;
614 warn " committing transaction" if $DEBUG and $oldAutoCommit;
615 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
621 Checks all fields to make sure this is a valid package definition. If
622 there is an error, returns the error, otherwise returns false. Called by the
623 insert and replace methods.
629 warn "FS::part_pkg::check called on $self" if $DEBUG;
631 for (qw(setup recur plandata)) {
632 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
633 return "Use of $_ field is deprecated; set a plan and options: ".
635 if length($self->get($_));
639 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
640 my $error = $self->ut_number('freq');
641 return $error if $error;
643 $self->freq =~ /^(\d+[hdw]?)$/
644 or return "Illegal or empty freq: ". $self->freq;
648 my @null_agentnum_right = ( 'Edit global package definitions' );
649 push @null_agentnum_right, 'One-time charge'
650 if $self->freq =~ /^0/;
651 push @null_agentnum_right, 'Customize customer package'
652 if $self->disabled eq 'Y'; #good enough
654 my $error = $self->ut_numbern('pkgpart')
655 || $self->ut_text('pkg')
656 || $self->ut_textn('comment')
657 || $self->ut_textn('promo_code')
658 || $self->ut_alphan('plan')
659 || $self->ut_enum('setuptax', [ '', 'Y' ] )
660 || $self->ut_enum('recurtax', [ '', 'Y' ] )
661 || $self->ut_textn('taxclass')
662 || $self->ut_enum('disabled', [ '', 'Y' ] )
663 || $self->ut_enum('custom', [ '', 'Y' ] )
664 || $self->ut_enum('no_auto', [ '', 'Y' ])
665 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
666 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
667 #|| $self->ut_moneyn('setup_cost')
668 #|| $self->ut_moneyn('recur_cost')
669 || $self->ut_floatn('setup_cost')
670 || $self->ut_floatn('recur_cost')
671 || $self->ut_floatn('pay_weight')
672 || $self->ut_floatn('credit_weight')
673 || $self->ut_numbern('taxproductnum')
674 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
675 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
676 || $self->ut_foreign_keyn('taxproductnum',
677 'part_pkg_taxproduct',
681 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
682 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
684 || $self->ut_numbern('fcc_ds0s')
685 || $self->ut_numbern('fcc_voip_class')
686 || $self->ut_numbern('delay_start')
687 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
688 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
689 || $self->ut_alphan('agent_pkgpartid')
690 || $self->SUPER::check
692 return $error if $error;
694 return 'Unknown plan '. $self->plan
695 unless exists($plans{$self->plan});
697 my $conf = new FS::Conf;
698 return 'Taxclass is required'
699 if ! $self->taxclass && $conf->exists('require_taxclasses');
704 =item supersede OLD [, OPTION => VALUE ... ]
706 Inserts this package as a successor to the package OLD. All options are as
707 for C<insert>. After inserting, disables OLD and sets the new package as its
713 my ($new, $old, %options) = @_;
716 $new->set('pkgpart' => '');
717 $new->set('family_pkgpart' => $old->family_pkgpart);
718 warn " inserting successor package\n" if $DEBUG;
719 $error = $new->insert(%options);
720 return $error if $error;
722 warn " disabling superseded package\n" if $DEBUG;
723 $old->set('successor' => $new->pkgpart);
724 $old->set('disabled' => 'Y');
725 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
726 return $error if $error;
728 warn " propagating changes to family" if $DEBUG;
729 $new->propagate($old);
734 If any of certain fields have changed from OLD to this package, then,
735 for all packages in the same lineage as this one, sets those fields
736 to their values in this package.
740 my @propagate_fields = (
741 qw( pkg classnum setup_cost recur_cost taxclass
742 setuptax recurtax pay_weight credit_weight
750 map { $_ => $new->get($_) }
751 grep { $new->get($_) ne $old->get($_) }
755 my @part_pkg = qsearch('part_pkg', {
756 'family_pkgpart' => $new->family_pkgpart
759 foreach my $part_pkg ( @part_pkg ) {
760 my $pkgpart = $part_pkg->pkgpart;
761 next if $pkgpart == $new->pkgpart; # don't modify $new
762 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
763 foreach ( keys %fields ) {
764 $part_pkg->set($_, $fields{$_});
766 # SUPER::replace to avoid changing non-core fields
767 my $error = $part_pkg->SUPER::replace;
768 push @error, "pkgpart $pkgpart: $error"
774 =item pkg_locale LOCALE
776 Returns a customer-viewable string representing this package for the given
777 locale, from the part_pkg_msgcat table. If the given locale is empty or no
778 localized string is found, returns the base pkg field.
783 my( $self, $locale ) = @_;
784 return $self->pkg unless $locale;
785 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
786 $part_pkg_msgcat->pkg;
789 =item part_pkg_msgcat LOCALE
791 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
795 sub part_pkg_msgcat {
796 my( $self, $locale ) = @_;
797 qsearchs( 'part_pkg_msgcat', {
798 pkgpart => $self->pkgpart,
803 =item pkg_comment [ OPTION => VALUE... ]
805 Returns an (internal) string representing this package. Currently,
806 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
807 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
810 If the option nopkgpart is true then the "pkgpart: ' is omitted.
818 #$self->pkg. ' - '. $self->comment;
819 #$self->pkg. ' ('. $self->comment. ')';
820 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
821 my $custom_comment = $self->custom_comment(%opt);
822 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
825 #without price info (so without hitting the DB again)
826 sub pkg_comment_only {
830 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
831 my $comment = $self->comment;
832 $pre. $self->pkg. ( $comment ? " - $comment" : '' );
835 sub price_info { # safety, in case a part_pkg hasn't defined price_info
841 my $price_info = $self->price_info(@_);
842 ( $self->custom ? '(CUSTOM) ' : '' ).
844 ( ($self->custom || $self->comment) ? ' - ' : '' ).
845 ($price_info || 'No charge');
850 $self->pkg. ' - '. ($self->price_info || 'No charge');
855 Returns the package class, as an FS::pkg_class object, or the empty string
856 if there is no package class.
858 =item addon_pkg_class
860 Returns the add-on package class, as an FS::pkg_class object, or the empty
861 string if there is no add-on package class.
865 sub addon_pkg_class {
867 if ( $self->addon_classnum ) {
868 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
876 Returns the package category name, or the empty string if there is no package
883 my $pkg_class = $self->pkg_class;
885 ? $pkg_class->categoryname
891 Returns the package class name, or the empty string if there is no package
898 my $pkg_class = $self->pkg_class;
900 ? $pkg_class->classname
904 =item addon_classname
906 Returns the add-on package class name, or the empty string if there is no
907 add-on package class.
911 sub addon_classname {
913 my $pkg_class = $self->addon_pkg_class;
915 ? $pkg_class->classname
921 Returns the associated agent for this event, if any, as an FS::agent object.
923 =item pkg_svc [ HASHREF | OPTION => VALUE ]
925 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
926 definition (with non-zero quantity).
928 One option is available, I<disable_linked>. If set true it will return the
929 services for this package definition alone, omitting services from any add-on
936 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
944 # #sort { $b->primary cmp $a->primary }
945 # grep { $_->quantity }
946 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
948 my $opt = ref($_[0]) ? $_[0] : { @_ };
949 my %pkg_svc = map { $_->svcpart => $_ }
950 grep { $_->quantity }
951 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
953 unless ( $opt->{disable_linked} ) {
954 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
955 my @pkg_svc = grep { $_->quantity }
956 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
957 foreach my $pkg_svc ( @pkg_svc ) {
958 if ( $pkg_svc{$pkg_svc->svcpart} ) {
959 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
960 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
962 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
972 =item svcpart [ SVCDB ]
974 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
975 associated with this package definition (see L<FS::pkg_svc>). Returns
976 false if there not a primary service definition or exactly one service
977 definition with quantity 1, or if SVCDB is specified and does not match the
978 svcdb of the service definition. SVCDB can be specified as a scalar table
979 name, such as 'svc_acct', or as an arrayref of possible table names.
984 my $pkg_svc = shift->_primary_pkg_svc(@_);
985 $pkg_svc ? $pkg_svc->svcpart : '';
988 =item part_svc [ SVCDB ]
990 Like the B<svcpart> method, but returns the FS::part_svc object (see
996 my $pkg_svc = shift->_primary_pkg_svc(@_);
997 $pkg_svc ? $pkg_svc->part_svc : '';
1000 sub _primary_pkg_svc {
1003 my $svcdb = scalar(@_) ? shift : [];
1004 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1005 my %svcdb = map { $_=>1 } @$svcdb;
1008 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1011 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1012 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1014 return '' if scalar(@pkg_svc) != 1;
1018 =item svcpart_unique_svcdb SVCDB
1020 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1021 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1022 false if there not a primary service definition for SVCDB or there are multiple
1023 service definitions for SVCDB.
1027 sub svcpart_unique_svcdb {
1028 my( $self, $svcdb ) = @_;
1029 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1030 return '' if scalar(@svcdb_pkg_svc) != 1;
1031 $svcdb_pkg_svc[0]->svcpart;
1036 Returns a list of the acceptable payment types for this package. Eventually
1037 this should come out of a database table and be editable, but currently has the
1038 following logic instead:
1040 If the package is free, the single item B<BILL> is
1041 returned, otherwise, the single item B<CARD> is returned.
1043 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1049 if ( $self->is_free ) {
1058 Returns true if this package is free.
1064 if ( $self->can('is_free_options') ) {
1065 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1066 map { $self->option($_) }
1067 $self->is_free_options;
1069 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1070 "provides neither is_free_options nor is_free method; returning false";
1075 # whether the plan allows discounts to be applied to this package
1076 sub can_discount { 0; }
1078 # whether the plan allows changing the start date
1079 sub can_start_date { 1; }
1081 # whether the plan supports part_pkg_usageprice add-ons (a specific kind of
1082 # pre-selectable usage pricing, there's others this doesn't refer to)
1083 sub can_usageprice { 0; }
1085 # the delay start date if present
1086 sub delay_start_date {
1089 my $delay = $self->delay_start or return '';
1091 # avoid timelocal silliness
1092 my $dt = DateTime->today(time_zone => 'local');
1093 $dt->add(days => $delay);
1097 sub can_currency_exchange { 0; }
1100 # moved to FS::Misc to make this accessible to other packages
1102 FS::Misc::pkg_freqs();
1107 Returns an english representation of the I<freq> field, such as "monthly",
1108 "weekly", "semi-annually", etc.
1114 my $freq = $self->freq;
1116 #my $freqs_href = $self->freqs_href;
1117 my $freqs_href = freqs_href();
1119 if ( exists($freqs_href->{$freq}) ) {
1120 $freqs_href->{$freq};
1122 my $interval = 'month';
1123 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1124 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1125 $interval = $interval{$2};
1130 "every $freq ${interval}s";
1135 =item add_freq TIMESTAMP [ FREQ ]
1137 Adds a billing period of some frequency to the provided timestamp and
1138 returns the resulting timestamp, or -1 if the frequency could not be
1139 parsed (shouldn't happen). By default, the frequency of this package
1140 will be used; to override this, pass a different frequency as a second
1146 my( $self, $date, $freq ) = @_;
1147 $freq = $self->freq unless $freq;
1149 #change this bit to use Date::Manip? CAREFUL with timezones (see
1150 # mailing list archive)
1151 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1153 if ( $freq =~ /^\d+$/ ) {
1155 until ( $mon < 12 ) { $mon -= 12; $year++; }
1157 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1159 } elsif ( $freq =~ /^(\d+)w$/ ) {
1161 $mday += $weeks * 7;
1162 } elsif ( $freq =~ /^(\d+)d$/ ) {
1165 } elsif ( $freq =~ /^(\d+)h$/ ) {
1172 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1177 For backwards compatibility, returns the plandata field as well as all options
1178 from FS::part_pkg_option.
1184 carp "plandata is deprecated";
1186 $self->SUPER::plandata(@_);
1188 my $plandata = $self->get('plandata');
1189 my %options = $self->options;
1190 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1195 =item part_pkg_vendor
1197 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1198 L<FS::part_pkg_vendor>).
1200 =item vendor_pkg_ids
1202 Returns a list of vendor/external package ids by exportnum
1206 sub vendor_pkg_ids {
1208 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1211 =item part_pkg_option
1213 Returns all options as FS::part_pkg_option objects (see
1214 L<FS::part_pkg_option>).
1218 Returns a list of option names and values suitable for assigning to a hash.
1224 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1227 =item option OPTIONNAME [ QUIET ]
1229 Returns the option value for the given name, or the empty string. If a true
1230 value is passed as the second argument, warnings about missing the option
1236 my( $self, $opt, $ornull ) = @_;
1237 cluck "$self -> option: searching for $opt"
1239 my $part_pkg_option =
1240 qsearchs('part_pkg_option', {
1241 pkgpart => $self->pkgpart,
1244 return $part_pkg_option->optionvalue if $part_pkg_option;
1245 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1246 split("\n", $self->get('plandata') );
1247 return $plandata{$opt} if exists $plandata{$opt};
1248 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1249 "not found in options or plandata!\n"
1254 =item part_pkg_currency [ CURRENCY ]
1256 Returns all currency options as FS::part_pkg_currency objects (see
1257 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1258 objects for that currency.
1262 sub part_pkg_currency {
1264 my %hash = ( 'pkgpart' => $self->pkgpart );
1265 $hash{'currency'} = shift if @_;
1266 qsearch('part_pkg_currency', \%hash );
1269 =item part_pkg_currency_options CURRENCY
1271 Returns a list of option names and values from FS::part_pkg_currency for the
1276 sub part_pkg_currency_options {
1278 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1281 =item part_pkg_currency_option CURRENCY OPTIONNAME
1283 Returns the option value for the given name and currency.
1287 sub part_pkg_currency_option {
1288 my( $self, $currency, $optionname ) = @_;
1289 my $part_pkg_currency =
1290 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1291 'currency' => $currency,
1292 'optionname' => $optionname,
1295 #fatal if not found? that works for our use cases from
1296 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1297 #to behave. have to catch it there if we change it here...
1298 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1300 $part_pkg_currency->optionvalue;
1303 =item bill_part_pkg_link
1305 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1309 sub bill_part_pkg_link {
1310 shift->_part_pkg_link('bill', @_);
1313 =item svc_part_pkg_link
1315 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1319 sub svc_part_pkg_link {
1320 shift->_part_pkg_link('svc', @_);
1323 =item supp_part_pkg_link
1325 Returns the associated part_pkg_link records of type 'supp' (supplemental
1330 sub supp_part_pkg_link {
1331 shift->_part_pkg_link('supp', @_);
1334 sub _part_pkg_link {
1335 my( $self, $type ) = @_;
1336 qsearch({ table => 'part_pkg_link',
1337 hashref => { 'src_pkgpart' => $self->pkgpart,
1338 'link_type' => $type,
1339 #protection against infinite recursive links
1340 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1342 order_by => "ORDER BY hidden",
1346 sub self_and_bill_linked {
1347 shift->_self_and_linked('bill', @_);
1350 sub self_and_svc_linked {
1351 shift->_self_and_linked('svc', @_);
1354 sub _self_and_linked {
1355 my( $self, $type, $hidden ) = @_;
1359 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1360 $self->_part_pkg_link($type) ) )
1362 $_->hidden($hidden) if $hidden;
1369 =item part_pkg_taxoverride [ CLASS ]
1371 Returns all associated FS::part_pkg_taxoverride objects (see
1372 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1373 of class CLASS if defined. Class may be one of 'setup', 'recur',
1374 the empty string (default), or a usage class number (see L<FS::usage_class>).
1375 When a class is specified, the empty string class (default) is returned
1376 if no more specific values exist.
1380 sub part_pkg_taxoverride {
1384 my $hashref = { 'pkgpart' => $self->pkgpart };
1385 $hashref->{'usage_class'} = $class if defined($class);
1386 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1388 unless ( scalar(@overrides) || !defined($class) || !$class ){
1389 $hashref->{'usage_class'} = '';
1390 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1396 =item has_taxproduct
1398 Returns true if this package has any taxproduct associated with it.
1402 sub has_taxproduct {
1405 $self->taxproductnum ||
1406 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1407 keys %{ {$self->options} }
1413 =item taxproduct [ CLASS ]
1415 Returns the associated tax product for this package definition (see
1416 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1417 the usage classnum (see L<FS::usage_class>). Returns the default
1418 tax product for this record if the more specific CLASS value does
1427 my $part_pkg_taxproduct;
1429 my $taxproductnum = $self->taxproductnum;
1431 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1432 $taxproductnum = $class_taxproductnum
1433 if $class_taxproductnum
1436 $part_pkg_taxproduct =
1437 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1439 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1440 $taxproductnum = $self->taxproductnum;
1441 $part_pkg_taxproduct =
1442 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1445 $part_pkg_taxproduct;
1448 =item taxproduct_description [ CLASS ]
1450 Returns the description of the associated tax product for this package
1451 definition (see L<FS::part_pkg_taxproduct>).
1455 sub taxproduct_description {
1457 my $part_pkg_taxproduct = $self->taxproduct(@_);
1458 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1462 =item tax_rates DATA_PROVIDER, GEOCODE, [ CLASS ]
1464 Returns the tax table entries (L<FS::tax_rate> objects) that apply to this
1465 package in the location specified by GEOCODE, for usage class CLASS (one of
1466 'setup', 'recur', null, or a C<usage_class> number).
1472 my ($vendor, $geocode, $class) = @_;
1473 my @taxclassnums = map { $_->taxclassnum }
1474 $self->part_pkg_taxoverride($class);
1475 if (!@taxclassnums) {
1476 my $part_pkg_taxproduct = $self->taxproduct($class);
1477 @taxclassnums = map { $_->taxclassnum }
1478 grep { $_->taxable eq 'Y' } # why do we need this?
1479 $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1481 return unless @taxclassnums;
1483 warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1485 my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1486 my @taxes = qsearch({ 'table' => 'tax_rate',
1487 'hashref' => { 'geocode' => $geocode,
1488 'data_vendor' => $vendor },
1489 'extra_sql' => $extra_sql,
1491 warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1497 =item part_pkg_discount
1499 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1502 =item part_pkg_usage
1504 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1509 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1510 PLAN is the object's I<plan> field. There should be better docs
1511 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1517 my $plan = $self->plan;
1519 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1523 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1524 my $class = ref($self). "::$plan";
1525 warn "reblessing $self into $class" if $DEBUG > 1;
1528 bless($self, $class) unless $@;
1533 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1534 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1536 #fallback that return 0 for old legacy packages with no plan
1537 sub calc_remain { 0; }
1538 sub calc_units { 0; }
1540 #fallback for everything not based on flat.pm
1541 sub recur_temporality { 'upcoming'; }
1542 sub calc_cancel { 0; }
1544 #fallback for everything except bulk.pm
1545 sub hide_svc_detail { 0; }
1547 #fallback for packages that can't/won't summarize usage
1548 sub sum_usage { 0; }
1550 =item recur_cost_permonth CUST_PKG
1552 recur_cost divided by freq (only supported for monthly and longer frequencies)
1556 sub recur_cost_permonth {
1557 my($self, $cust_pkg) = @_;
1558 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1559 sprintf('%.2f', $self->recur_cost / $self->freq );
1562 =item cust_bill_pkg_recur CUST_PKG
1564 Actual recurring charge for the specified customer package from customer's most
1569 sub cust_bill_pkg_recur {
1570 my($self, $cust_pkg) = @_;
1571 my $cust_bill_pkg = qsearchs({
1572 'table' => 'cust_bill_pkg',
1573 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1574 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1575 'recur' => { op=>'>', value=>'0' },
1577 'order_by' => 'ORDER BY cust_bill._date DESC,
1578 cust_bill_pkg.sdate DESC
1581 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1582 $cust_bill_pkg->recur;
1585 =item unit_setup CUST_PKG
1587 Returns the setup fee for one unit of the package.
1592 my ($self, $cust_pkg) = @_;
1593 $self->option('setup_fee') || 0;
1598 unit_setup minus setup_cost
1604 $self->unit_setup(@_) - $self->setup_cost;
1607 =item recur_margin_permonth
1609 base_recur_permonth minus recur_cost_permonth
1613 sub recur_margin_permonth {
1615 $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1618 =item format OPTION DATA
1620 Returns data formatted according to the function 'format' described
1621 in the plan info. Returns DATA if no such function exists.
1626 my ($self, $option, $data) = (shift, shift, shift);
1627 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1628 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1634 =item parse OPTION DATA
1636 Returns data parsed according to the function 'parse' described
1637 in the plan info. Returns DATA if no such function exists.
1642 my ($self, $option, $data) = (shift, shift, shift);
1643 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1644 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1654 =head1 CLASS METHODS
1662 # Used by FS::Upgrade to migrate to a new database.
1664 sub _upgrade_data { # class method
1665 my($class, %opts) = @_;
1667 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1669 my @part_pkg = qsearch({
1670 'table' => 'part_pkg',
1671 'extra_sql' => "WHERE ". join(' OR ',
1672 'plan IS NULL', "plan = '' ",
1676 foreach my $part_pkg (@part_pkg) {
1678 unless ( $part_pkg->plan ) {
1679 $part_pkg->plan('flat');
1686 # now upgrade to the explicit custom flag
1688 @part_pkg = qsearch({
1689 'table' => 'part_pkg',
1690 'hashref' => { disabled => 'Y', custom => '' },
1691 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1694 foreach my $part_pkg (@part_pkg) {
1695 my $new = new FS::part_pkg { $part_pkg->hash };
1697 my $comment = $part_pkg->comment;
1698 $comment =~ s/^\(CUSTOM\) //;
1699 $comment = '(none)' unless $comment =~ /\S/;
1700 $new->comment($comment);
1702 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1703 my $primary = $part_pkg->svcpart;
1704 my $options = { $part_pkg->options };
1706 my $error = $new->replace( $part_pkg,
1707 'pkg_svc' => $pkg_svc,
1708 'primary_svc' => $primary,
1709 'options' => $options,
1711 die $error if $error;
1714 # set family_pkgpart on any packages that don't have it
1715 @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1716 foreach my $part_pkg (@part_pkg) {
1717 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1718 my $error = $part_pkg->SUPER::replace;
1719 die $error if $error;
1722 my @part_pkg_option = qsearch('part_pkg_option',
1723 { 'optionname' => 'unused_credit',
1726 foreach my $old_opt (@part_pkg_option) {
1727 my $pkgpart = $old_opt->pkgpart;
1728 my $error = $old_opt->delete;
1729 die $error if $error;
1731 foreach (qw(unused_credit_cancel unused_credit_change)) {
1732 my $new_opt = new FS::part_pkg_option {
1733 'pkgpart' => $pkgpart,
1737 $error = $new_opt->insert;
1738 die $error if $error;
1742 # migrate use_disposition_taqua and use_disposition to disposition_in
1743 @part_pkg_option = qsearch('part_pkg_option',
1744 { 'optionname' => { op => 'LIKE',
1745 value => 'use_disposition%',
1749 my %newopts = map { $_->pkgpart => $_ }
1750 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1751 foreach my $old_opt (@part_pkg_option) {
1752 my $pkgpart = $old_opt->pkgpart;
1753 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1755 my $error = $old_opt->delete;
1756 die $error if $error;
1758 if ( exists($newopts{$pkgpart}) ) {
1759 my $opt = $newopts{$pkgpart};
1760 $opt->optionvalue($opt->optionvalue.",$newval");
1761 $error = $opt->replace;
1762 die $error if $error;
1764 my $new_opt = new FS::part_pkg_option {
1765 'pkgpart' => $pkgpart,
1766 'optionname' => 'disposition_in',
1767 'optionvalue' => $newval,
1769 $error = $new_opt->insert;
1770 die $error if $error;
1771 $newopts{$pkgpart} = $new_opt;
1775 # set any package with FCC voice lines to the "VoIP with broadband" category
1776 # for backward compatibility
1778 # recover from a bad upgrade bug
1779 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1780 if (!FS::upgrade_journal->is_done($upgrade)) {
1781 my $bad_upgrade = qsearchs('upgrade_journal',
1782 { upgrade => 'part_pkg_fcc_voip_class' }
1784 if ( $bad_upgrade ) {
1785 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1786 ' AND history_date > '.($bad_upgrade->_date - 3600);
1787 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1790 'table' => 'h_part_pkg_option',
1792 'extra_sql' => "$where AND history_action = 'delete'",
1793 'order_by' => 'ORDER BY history_date ASC',
1795 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1798 'table' => 'h_pkg_svc',
1800 'extra_sql' => "$where AND history_action = 'replace_old'",
1801 'order_by' => 'ORDER BY history_date ASC',
1804 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1805 my $pkgpart ||= $deleted->pkgpart;
1806 $opt{$pkgpart} ||= {
1812 if ( $deleted->isa('FS::part_pkg_option') ) {
1813 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1815 my $svcpart = $deleted->svcpart;
1816 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1817 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1818 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1821 foreach my $pkgpart (keys %opt) {
1822 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1823 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1825 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1828 } # $bad_upgrade exists
1829 else { # do the original upgrade, but correctly this time
1830 @part_pkg = qsearch('part_pkg', {
1831 fcc_ds0s => { op => '>', value => 0 },
1832 fcc_voip_class => ''
1834 foreach my $part_pkg (@part_pkg) {
1835 $part_pkg->set(fcc_voip_class => 2);
1836 my @pkg_svc = $part_pkg->pkg_svc;
1837 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1838 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1839 my $error = $part_pkg->replace(
1840 $part_pkg->replace_old,
1841 options => { $part_pkg->options },
1842 pkg_svc => \%quantity,
1843 hidden_svc => \%hidden,
1844 primary_svc => ($part_pkg->svcpart || ''),
1846 die $error if $error;
1849 FS::upgrade_journal->set_done($upgrade);
1854 =item curuser_pkgs_sql
1856 Returns an SQL fragment for searching for packages the current user can
1857 use, either via part_pkg.agentnum directly, or via agent type (see
1862 sub curuser_pkgs_sql {
1865 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1869 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1871 Returns an SQL fragment for searching for packages the provided agent or agents
1872 can use, either via part_pkg.agentnum directly, or via agent type (see
1877 sub agent_pkgs_sql {
1878 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1879 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1881 $class->_pkgs_sql(@agentnums); #is this why
1886 my( $class, @agentnums ) = @_;
1887 my $agentnums = join(',', @agentnums);
1891 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1892 OR ( agentnum IS NULL
1893 AND EXISTS ( SELECT 1
1895 LEFT JOIN agent_type USING ( typenum )
1896 LEFT JOIN agent AS typeagent USING ( typenum )
1897 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1898 AND typeagent.agentnum IN ($agentnums)
1916 #false laziness w/part_export & cdr
1918 foreach my $INC ( @INC ) {
1919 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1920 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1921 warn "attempting to load plan info from $file\n" if $DEBUG;
1922 $file =~ /\/(\w+)\.pm$/ or do {
1923 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1927 my $info = eval "use FS::part_pkg::$mod; ".
1928 "\\%FS::part_pkg::$mod\::info;";
1930 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1933 unless ( keys %$info ) {
1934 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1937 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1938 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1939 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1942 $info{$mod} = $info;
1943 $info->{'weight'} ||= 0; # quiet warnings
1947 # copy one level deep to allow replacement of fields and fieldorder
1948 tie %plans, 'Tie::IxHash',
1949 map { my %infohash = %{ $info{$_} };
1951 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1954 # inheritance of plan options
1955 foreach my $name (keys(%info)) {
1956 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1957 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1958 delete $plans{$name};
1961 my $parents = $info{$name}->{'inherit_fields'} || [];
1962 my (%fields, %field_exists, @fieldorder);
1963 foreach my $parent ($name, @$parents) {
1964 if ( !exists($info{$parent}) ) {
1965 warn "$name tried to inherit from nonexistent '$parent'\n";
1968 %fields = ( # avoid replacing existing fields
1969 %{ $info{$parent}->{'fields'} || {} },
1972 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1974 next if $field_exists{$_};
1975 $field_exists{$_} = 1;
1976 # allow inheritors to remove inherited fields from the fieldorder
1977 push @fieldorder, $_ if !exists($fields{$_}) or
1978 !exists($fields{$_}->{'disabled'});
1981 $plans{$name}->{'fields'} = \%fields;
1982 $plans{$name}->{'fieldorder'} = \@fieldorder;
1992 =head1 NEW PLAN CLASSES
1994 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1995 found in eg/plan_template.pm. Until then, it is suggested that you use the
1996 other modules in FS/FS/part_pkg/ as a guide.
2000 The delete method is unimplemented.
2002 setup and recur semantics are not yet defined (and are implemented in
2003 FS::cust_bill. hmm.). now they're deprecated and need to go.
2007 part_pkg_taxrate is Pg specific
2009 replace should be smarter about managing the related tables (options, pkg_svc)
2013 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2014 schema.html from the base documentation.