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 delay start date if present
1093 sub delay_start_date {
1096 my $delay = $self->delay_start or return '';
1098 my ($mday,$mon,$year) = (localtime(time))[3,4,5];
1099 timelocal(0,0,0,$mday,$mon,$year) + 86400 * $delay;
1103 sub can_currency_exchange { 0; }
1106 # moved to FS::Misc to make this accessible to other packages
1108 FS::Misc::pkg_freqs();
1113 Returns an english representation of the I<freq> field, such as "monthly",
1114 "weekly", "semi-annually", etc.
1120 my $freq = $self->freq;
1122 #my $freqs_href = $self->freqs_href;
1123 my $freqs_href = freqs_href();
1125 if ( exists($freqs_href->{$freq}) ) {
1126 $freqs_href->{$freq};
1128 my $interval = 'month';
1129 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1130 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1131 $interval = $interval{$2};
1136 "every $freq ${interval}s";
1141 =item add_freq TIMESTAMP [ FREQ ]
1143 Adds a billing period of some frequency to the provided timestamp and
1144 returns the resulting timestamp, or -1 if the frequency could not be
1145 parsed (shouldn't happen). By default, the frequency of this package
1146 will be used; to override this, pass a different frequency as a second
1152 my( $self, $date, $freq ) = @_;
1153 $freq = $self->freq unless $freq;
1155 #change this bit to use Date::Manip? CAREFUL with timezones (see
1156 # mailing list archive)
1157 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1159 if ( $freq =~ /^\d+$/ ) {
1161 until ( $mon < 12 ) { $mon -= 12; $year++; }
1163 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1165 } elsif ( $freq =~ /^(\d+)w$/ ) {
1167 $mday += $weeks * 7;
1168 } elsif ( $freq =~ /^(\d+)d$/ ) {
1171 } elsif ( $freq =~ /^(\d+)h$/ ) {
1178 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1183 For backwards compatibility, returns the plandata field as well as all options
1184 from FS::part_pkg_option.
1190 carp "plandata is deprecated";
1192 $self->SUPER::plandata(@_);
1194 my $plandata = $self->get('plandata');
1195 my %options = $self->options;
1196 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1201 =item part_pkg_vendor
1203 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1204 L<FS::part_pkg_vendor>).
1208 sub part_pkg_vendor {
1210 qsearch('part_pkg_vendor', { 'pkgpart' => $self->pkgpart } );
1213 =item vendor_pkg_ids
1215 Returns a list of vendor/external package ids by exportnum
1219 sub vendor_pkg_ids {
1221 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1224 =item part_pkg_option
1226 Returns all options as FS::part_pkg_option objects (see
1227 L<FS::part_pkg_option>).
1231 sub part_pkg_option {
1233 qsearch('part_pkg_option', { 'pkgpart' => $self->pkgpart } );
1238 Returns a list of option names and values suitable for assigning to a hash.
1244 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1247 =item option OPTIONNAME [ QUIET ]
1249 Returns the option value for the given name, or the empty string. If a true
1250 value is passed as the second argument, warnings about missing the option
1256 my( $self, $opt, $ornull ) = @_;
1257 my $part_pkg_option =
1258 qsearchs('part_pkg_option', {
1259 pkgpart => $self->pkgpart,
1262 return $part_pkg_option->optionvalue if $part_pkg_option;
1263 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1264 split("\n", $self->get('plandata') );
1265 return $plandata{$opt} if exists $plandata{$opt};
1266 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1267 "not found in options or plandata!\n"
1272 =item part_pkg_currency [ CURRENCY ]
1274 Returns all currency options as FS::part_pkg_currency objects (see
1275 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1276 objects for that currency.
1280 sub part_pkg_currency {
1282 my %hash = ( 'pkgpart' => $self->pkgpart );
1283 $hash{'currency'} = shift if @_;
1284 qsearch('part_pkg_currency', \%hash );
1287 =item part_pkg_currency_options CURRENCY
1289 Returns a list of option names and values from FS::part_pkg_currency for the
1294 sub part_pkg_currency_options {
1296 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1299 =item part_pkg_currency_option CURRENCY OPTIONNAME
1301 Returns the option value for the given name and currency.
1305 sub part_pkg_currency_option {
1306 my( $self, $currency, $optionname ) = @_;
1307 my $part_pkg_currency =
1308 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1309 'currency' => $currency,
1310 'optionname' => $optionname,
1313 #fatal if not found? that works for our use cases from
1314 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1315 #to behave. have to catch it there if we change it here...
1316 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1318 $part_pkg_currency->optionvalue;
1321 =item bill_part_pkg_link
1323 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1327 sub bill_part_pkg_link {
1328 shift->_part_pkg_link('bill', @_);
1331 =item svc_part_pkg_link
1333 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1337 sub svc_part_pkg_link {
1338 shift->_part_pkg_link('svc', @_);
1341 =item supp_part_pkg_link
1343 Returns the associated part_pkg_link records of type 'supp' (supplemental
1348 sub supp_part_pkg_link {
1349 shift->_part_pkg_link('supp', @_);
1352 sub _part_pkg_link {
1353 my( $self, $type ) = @_;
1354 qsearch({ table => 'part_pkg_link',
1355 hashref => { 'src_pkgpart' => $self->pkgpart,
1356 'link_type' => $type,
1357 #protection against infinite recursive links
1358 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1360 order_by => "ORDER BY hidden",
1364 sub self_and_bill_linked {
1365 shift->_self_and_linked('bill', @_);
1368 sub self_and_svc_linked {
1369 shift->_self_and_linked('svc', @_);
1372 sub _self_and_linked {
1373 my( $self, $type, $hidden ) = @_;
1377 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1378 $self->_part_pkg_link($type) ) )
1380 $_->hidden($hidden) if $hidden;
1387 =item part_pkg_taxoverride [ CLASS ]
1389 Returns all associated FS::part_pkg_taxoverride objects (see
1390 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1391 of class CLASS if defined. Class may be one of 'setup', 'recur',
1392 the empty string (default), or a usage class number (see L<FS::usage_class>).
1393 When a class is specified, the empty string class (default) is returned
1394 if no more specific values exist.
1398 sub part_pkg_taxoverride {
1402 my $hashref = { 'pkgpart' => $self->pkgpart };
1403 $hashref->{'usage_class'} = $class if defined($class);
1404 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1406 unless ( scalar(@overrides) || !defined($class) || !$class ){
1407 $hashref->{'usage_class'} = '';
1408 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1414 =item has_taxproduct
1416 Returns true if this package has any taxproduct associated with it.
1420 sub has_taxproduct {
1423 $self->taxproductnum ||
1424 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1425 keys %{ {$self->options} }
1431 =item taxproduct [ CLASS ]
1433 Returns the associated tax product for this package definition (see
1434 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1435 the usage classnum (see L<FS::usage_class>). Returns the default
1436 tax product for this record if the more specific CLASS value does
1445 my $part_pkg_taxproduct;
1447 my $taxproductnum = $self->taxproductnum;
1449 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1450 $taxproductnum = $class_taxproductnum
1451 if $class_taxproductnum
1454 $part_pkg_taxproduct =
1455 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1457 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1458 $taxproductnum = $self->taxproductnum;
1459 $part_pkg_taxproduct =
1460 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1463 $part_pkg_taxproduct;
1466 =item taxproduct_description [ CLASS ]
1468 Returns the description of the associated tax product for this package
1469 definition (see L<FS::part_pkg_taxproduct>).
1473 sub taxproduct_description {
1475 my $part_pkg_taxproduct = $self->taxproduct(@_);
1476 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1479 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1481 Returns the package to taxrate m2m records for this package in the location
1482 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1483 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1484 (see L<FS::usage_class>).
1488 sub _expand_cch_taxproductnum {
1491 my $part_pkg_taxproduct = $self->taxproduct($class);
1493 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1494 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1497 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1498 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1499 OR taxproduct = '$a:$b:$c:'
1500 OR taxproduct = '$a:$b:".":$d'
1501 OR taxproduct = '$a:$b:".":' )";
1502 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1503 'hashref' => { 'data_vendor'=>'cch' },
1504 'extra_sql' => $extra_sql,
1509 sub part_pkg_taxrate {
1511 my ($data_vendor, $geocode, $class) = @_;
1514 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1515 dbh->quote($data_vendor);
1517 # CCH oddness in m2m
1518 $extra_sql .= ' AND ('.
1519 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1523 # much more CCH oddness in m2m -- this is kludgy
1524 my @tpnums = $self->_expand_cch_taxproductnum($class);
1525 if (scalar(@tpnums)) {
1526 $extra_sql .= ' AND ('.
1527 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1530 $extra_sql .= ' AND ( 0 = 1 )';
1533 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1534 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1535 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1537 # should qsearch preface columns with the table to facilitate joins?
1538 qsearch( { 'table' => 'part_pkg_taxrate',
1539 'select' => $select,
1540 'hashref' => { # 'data_vendor' => $data_vendor,
1541 # 'taxproductnum' => $self->taxproductnum,
1543 'addl_from' => $addl_from,
1544 'extra_sql' => $extra_sql,
1545 'order_by' => $order_by,
1549 =item part_pkg_discount
1551 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1556 sub part_pkg_discount {
1558 qsearch('part_pkg_discount', { 'pkgpart' => $self->pkgpart });
1561 =item part_pkg_usage
1563 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1568 sub part_pkg_usage {
1570 qsearch('part_pkg_usage', { 'pkgpart' => $self->pkgpart });
1575 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1576 PLAN is the object's I<plan> field. There should be better docs
1577 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1583 my $plan = $self->plan;
1585 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1589 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1590 my $class = ref($self). "::$plan";
1591 warn "reblessing $self into $class" if $DEBUG > 1;
1594 bless($self, $class) unless $@;
1599 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1600 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1602 #fallback that return 0 for old legacy packages with no plan
1603 sub calc_remain { 0; }
1604 sub calc_units { 0; }
1606 #fallback for everything not based on flat.pm
1607 sub recur_temporality { 'upcoming'; }
1608 sub calc_cancel { 0; }
1610 #fallback for everything except bulk.pm
1611 sub hide_svc_detail { 0; }
1613 #fallback for packages that can't/won't summarize usage
1614 sub sum_usage { 0; }
1616 =item recur_cost_permonth CUST_PKG
1618 recur_cost divided by freq (only supported for monthly and longer frequencies)
1622 sub recur_cost_permonth {
1623 my($self, $cust_pkg) = @_;
1624 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1625 sprintf('%.2f', $self->recur_cost / $self->freq );
1628 =item cust_bill_pkg_recur CUST_PKG
1630 Actual recurring charge for the specified customer package from customer's most
1635 sub cust_bill_pkg_recur {
1636 my($self, $cust_pkg) = @_;
1637 my $cust_bill_pkg = qsearchs({
1638 'table' => 'cust_bill_pkg',
1639 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1640 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1641 'recur' => { op=>'>', value=>'0' },
1643 'order_by' => 'ORDER BY cust_bill._date DESC,
1644 cust_bill_pkg.sdate DESC
1647 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1648 $cust_bill_pkg->recur;
1651 =item format OPTION DATA
1653 Returns data formatted according to the function 'format' described
1654 in the plan info. Returns DATA if no such function exists.
1659 my ($self, $option, $data) = (shift, shift, shift);
1660 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1661 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1667 =item parse OPTION DATA
1669 Returns data parsed according to the function 'parse' described
1670 in the plan info. Returns DATA if no such function exists.
1675 my ($self, $option, $data) = (shift, shift, shift);
1676 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1677 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1687 =head1 CLASS METHODS
1695 # Used by FS::Upgrade to migrate to a new database.
1697 sub _upgrade_data { # class method
1698 my($class, %opts) = @_;
1700 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1702 my @part_pkg = qsearch({
1703 'table' => 'part_pkg',
1704 'extra_sql' => "WHERE ". join(' OR ',
1705 'plan IS NULL', "plan = '' ",
1709 foreach my $part_pkg (@part_pkg) {
1711 unless ( $part_pkg->plan ) {
1712 $part_pkg->plan('flat');
1719 # now upgrade to the explicit custom flag
1721 @part_pkg = qsearch({
1722 'table' => 'part_pkg',
1723 'hashref' => { disabled => 'Y', custom => '' },
1724 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1727 foreach my $part_pkg (@part_pkg) {
1728 my $new = new FS::part_pkg { $part_pkg->hash };
1730 my $comment = $part_pkg->comment;
1731 $comment =~ s/^\(CUSTOM\) //;
1732 $comment = '(none)' unless $comment =~ /\S/;
1733 $new->comment($comment);
1735 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1736 my $primary = $part_pkg->svcpart;
1737 my $options = { $part_pkg->options };
1739 my $error = $new->replace( $part_pkg,
1740 'pkg_svc' => $pkg_svc,
1741 'primary_svc' => $primary,
1742 'options' => $options,
1744 die $error if $error;
1747 # set family_pkgpart on any packages that don't have it
1748 @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1749 foreach my $part_pkg (@part_pkg) {
1750 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1751 my $error = $part_pkg->SUPER::replace;
1752 die $error if $error;
1755 my @part_pkg_option = qsearch('part_pkg_option',
1756 { 'optionname' => 'unused_credit',
1759 foreach my $old_opt (@part_pkg_option) {
1760 my $pkgpart = $old_opt->pkgpart;
1761 my $error = $old_opt->delete;
1762 die $error if $error;
1764 foreach (qw(unused_credit_cancel unused_credit_change)) {
1765 my $new_opt = new FS::part_pkg_option {
1766 'pkgpart' => $pkgpart,
1770 $error = $new_opt->insert;
1771 die $error if $error;
1775 # migrate use_disposition_taqua and use_disposition to disposition_in
1776 @part_pkg_option = qsearch('part_pkg_option',
1777 { 'optionname' => { op => 'LIKE',
1778 value => 'use_disposition%',
1782 my %newopts = map { $_->pkgpart => $_ }
1783 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1784 foreach my $old_opt (@part_pkg_option) {
1785 my $pkgpart = $old_opt->pkgpart;
1786 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1788 my $error = $old_opt->delete;
1789 die $error if $error;
1791 if ( exists($newopts{$pkgpart}) ) {
1792 my $opt = $newopts{$pkgpart};
1793 $opt->optionvalue($opt->optionvalue.",$newval");
1794 $error = $opt->replace;
1795 die $error if $error;
1797 my $new_opt = new FS::part_pkg_option {
1798 'pkgpart' => $pkgpart,
1799 'optionname' => 'disposition_in',
1800 'optionvalue' => $newval,
1802 $error = $new_opt->insert;
1803 die $error if $error;
1804 $newopts{$pkgpart} = $new_opt;
1808 # set any package with FCC voice lines to the "VoIP with broadband" category
1809 # for backward compatibility
1811 # recover from a bad upgrade bug
1812 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1813 if (!FS::upgrade_journal->is_done($upgrade)) {
1814 my $bad_upgrade = qsearchs('upgrade_journal',
1815 { upgrade => 'part_pkg_fcc_voip_class' }
1817 if ( $bad_upgrade ) {
1818 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1819 ' AND history_date > '.($bad_upgrade->_date - 3600);
1820 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1823 'table' => 'h_part_pkg_option',
1825 'extra_sql' => "$where AND history_action = 'delete'",
1826 'order_by' => 'ORDER BY history_date ASC',
1828 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1831 'table' => 'h_pkg_svc',
1833 'extra_sql' => "$where AND history_action = 'replace_old'",
1834 'order_by' => 'ORDER BY history_date ASC',
1837 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1838 my $pkgpart ||= $deleted->pkgpart;
1839 $opt{$pkgpart} ||= {
1845 if ( $deleted->isa('FS::part_pkg_option') ) {
1846 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1848 my $svcpart = $deleted->svcpart;
1849 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1850 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1851 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1854 foreach my $pkgpart (keys %opt) {
1855 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1856 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1858 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1861 } # $bad_upgrade exists
1862 else { # do the original upgrade, but correctly this time
1863 @part_pkg = qsearch('part_pkg', {
1864 fcc_ds0s => { op => '>', value => 0 },
1865 fcc_voip_class => ''
1867 foreach my $part_pkg (@part_pkg) {
1868 $part_pkg->set(fcc_voip_class => 2);
1869 my @pkg_svc = $part_pkg->pkg_svc;
1870 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1871 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1872 my $error = $part_pkg->replace(
1873 $part_pkg->replace_old,
1874 options => { $part_pkg->options },
1875 pkg_svc => \%quantity,
1876 hidden_svc => \%hidden,
1877 primary_svc => ($part_pkg->svcpart || ''),
1879 die $error if $error;
1882 FS::upgrade_journal->set_done($upgrade);
1887 =item curuser_pkgs_sql
1889 Returns an SQL fragment for searching for packages the current user can
1890 use, either via part_pkg.agentnum directly, or via agent type (see
1895 sub curuser_pkgs_sql {
1898 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1902 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1904 Returns an SQL fragment for searching for packages the provided agent or agents
1905 can use, either via part_pkg.agentnum directly, or via agent type (see
1910 sub agent_pkgs_sql {
1911 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1912 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1914 $class->_pkgs_sql(@agentnums); #is this why
1919 my( $class, @agentnums ) = @_;
1920 my $agentnums = join(',', @agentnums);
1924 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1925 OR ( agentnum IS NULL
1926 AND EXISTS ( SELECT 1
1928 LEFT JOIN agent_type USING ( typenum )
1929 LEFT JOIN agent AS typeagent USING ( typenum )
1930 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1931 AND typeagent.agentnum IN ($agentnums)
1949 #false laziness w/part_export & cdr
1951 foreach my $INC ( @INC ) {
1952 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1953 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1954 warn "attempting to load plan info from $file\n" if $DEBUG;
1955 $file =~ /\/(\w+)\.pm$/ or do {
1956 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1960 my $info = eval "use FS::part_pkg::$mod; ".
1961 "\\%FS::part_pkg::$mod\::info;";
1963 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1966 unless ( keys %$info ) {
1967 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1970 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1971 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1972 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1975 $info{$mod} = $info;
1976 $info->{'weight'} ||= 0; # quiet warnings
1980 # copy one level deep to allow replacement of fields and fieldorder
1981 tie %plans, 'Tie::IxHash',
1982 map { my %infohash = %{ $info{$_} };
1984 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1987 # inheritance of plan options
1988 foreach my $name (keys(%info)) {
1989 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1990 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1991 delete $plans{$name};
1994 my $parents = $info{$name}->{'inherit_fields'} || [];
1995 my (%fields, %field_exists, @fieldorder);
1996 foreach my $parent ($name, @$parents) {
1997 if ( !exists($info{$parent}) ) {
1998 warn "$name tried to inherit from nonexistent '$parent'\n";
2001 %fields = ( # avoid replacing existing fields
2002 %{ $info{$parent}->{'fields'} || {} },
2005 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2007 next if $field_exists{$_};
2008 $field_exists{$_} = 1;
2009 # allow inheritors to remove inherited fields from the fieldorder
2010 push @fieldorder, $_ if !exists($fields{$_}) or
2011 !exists($fields{$_}->{'disabled'});
2014 $plans{$name}->{'fields'} = \%fields;
2015 $plans{$name}->{'fieldorder'} = \@fieldorder;
2025 =head1 NEW PLAN CLASSES
2027 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2028 found in eg/plan_template.pm. Until then, it is suggested that you use the
2029 other modules in FS/FS/part_pkg/ as a guide.
2033 The delete method is unimplemented.
2035 setup and recur semantics are not yet defined (and are implemented in
2036 FS::cust_bill. hmm.). now they're deprecated and need to go.
2040 part_pkg_taxrate is Pg specific
2042 replace should be smarter about managing the related tables (options, pkg_svc)
2046 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2047 schema.html from the base documentation.