2 use base qw( FS::part_pkg::API
3 FS::m2m_Common FS::o2m_Common FS::option_Common
7 use vars qw( %plans $DEBUG $setup_hack $skip_pkg_svc_hack );
8 use Carp qw(carp cluck confess);
9 use Scalar::Util qw( blessed );
11 use Time::Local qw( timelocal timelocal_nocheck ); # eventually replace with DateTime
14 use FS::Record qw( qsearch qsearchs dbh dbdef );
15 use FS::Cursor; # for upgrade
21 use FS::part_pkg_option;
22 use FS::part_pkg_fcc_option;
25 use FS::part_pkg_msgcat;
26 use FS::part_pkg_taxrate;
27 use FS::part_pkg_taxoverride;
28 use FS::part_pkg_taxproduct;
29 use FS::part_pkg_link;
30 use FS::part_pkg_discount;
31 use FS::part_pkg_vendor;
32 use FS::part_pkg_currency;
36 $skip_pkg_svc_hack = 0;
40 FS::part_pkg - Object methods for part_pkg objects
46 $record = new FS::part_pkg \%hash
47 $record = new FS::part_pkg { 'column' => 'value' };
49 $custom_record = $template_record->clone;
51 $error = $record->insert;
53 $error = $new_record->replace($old_record);
55 $error = $record->delete;
57 $error = $record->check;
59 @pkg_svc = $record->pkg_svc;
61 $svcnum = $record->svcpart;
62 $svcnum = $record->svcpart( 'svc_acct' );
66 An FS::part_pkg object represents a package definition. FS::part_pkg
67 inherits from FS::Record. The following fields are currently supported:
71 =item pkgpart - primary key (assigned automatically for new package definitions)
73 =item pkg - Text name of this package definition (customer-viewable)
75 =item comment - Text name of this package definition (non-customer-viewable)
77 =item classnum - Optional package class (see L<FS::pkg_class>)
79 =item promo_code - Promotional code
81 =item setup - Setup fee expression (deprecated)
83 =item freq - Frequency of recurring fee
85 =item recur - Recurring fee expression (deprecated)
87 =item setuptax - Setup fee tax exempt flag, empty or `Y'
89 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
91 =item taxclass - Tax class
93 =item plan - Price plan
95 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
97 =item disabled - Disabled flag, empty or `Y'
99 =item custom - Custom flag, empty or `Y'
101 =item setup_cost - for cost tracking
103 =item recur_cost - for cost tracking
105 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
107 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
109 =item agentnum - Optional agentnum (see L<FS::agent>)
111 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
113 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
116 =item successor - Foreign key for the part_pkg that replaced this record.
117 If this record is not obsolete, will be null.
119 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
120 ancestor of this record. If this record is not a successor to another
121 part_pkg, will be equal to pkgpart.
123 =item delay_start - Number of days to delay package start, by default
125 =item start_on_hold - 'Y' to suspend this package immediately when it is
126 ordered. The package will not start billing or have a setup fee charged
127 until it is manually unsuspended.
137 Creates a new package definition. To add the package definition to
138 the database, see L<"insert">.
142 sub table { 'part_pkg'; }
146 An alternate constructor. Creates a new package definition by duplicating
147 an existing definition. A new pkgpart is assigned and the custom flag is
148 set to Y. To add the package definition to the database, see L<"insert">.
154 my $class = ref($self);
155 my %hash = $self->hash;
156 $hash{'pkgpart'} = '';
157 $hash{'custom'} = 'Y';
158 #new FS::part_pkg ( \%hash ); # ?
159 new $class ( \%hash ); # ?
162 =item insert [ , OPTION => VALUE ... ]
164 Adds this package definition to the database. If there is an error,
165 returns the error, otherwise returns false.
167 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
168 I<custnum_ref> and I<options>.
170 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
171 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
172 be set to a hashref of svcparts and flag values ('Y' or '') to set the
173 'hidden' field in these records.
175 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
176 FS::pkg_svc record will be updated.
178 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
179 record itself), the object will be updated to point to this package definition.
181 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
182 the scalar will be updated with the custnum value from the cust_pkg record.
184 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
185 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
186 records will be inserted.
188 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
189 records will be inserted.
191 If I<part_pkg_currency> is set to a hashref of options (with the keys as
192 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
199 warn "FS::part_pkg::insert called on $self with options ".
200 join(', ', map "$_=>$options{$_}", keys %options)
203 local $SIG{HUP} = 'IGNORE';
204 local $SIG{INT} = 'IGNORE';
205 local $SIG{QUIT} = 'IGNORE';
206 local $SIG{TERM} = 'IGNORE';
207 local $SIG{TSTP} = 'IGNORE';
208 local $SIG{PIPE} = 'IGNORE';
210 my $oldAutoCommit = $FS::UID::AutoCommit;
211 local $FS::UID::AutoCommit = 0;
214 warn " inserting part_pkg record" if $DEBUG;
215 my $error = $self->SUPER::insert( $options{options} );
217 $dbh->rollback if $oldAutoCommit;
222 if ( $self->get('family_pkgpart') eq '' ) {
223 $self->set('family_pkgpart' => $self->pkgpart);
224 $error = $self->SUPER::replace;
226 $dbh->rollback if $oldAutoCommit;
231 warn " inserting part_pkg_taxoverride records" if $DEBUG;
232 my %overrides = %{ $options{'tax_overrides'} || {} };
233 foreach my $usage_class ( keys %overrides ) {
235 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
236 ? $overrides{$usage_class}
238 my @overrides = (grep "$_", split(',', $override) );
239 my $error = $self->process_m2m (
240 'link_table' => 'part_pkg_taxoverride',
241 'target_table' => 'tax_class',
242 'hashref' => { 'usage_class' => $usage_class },
243 'params' => \@overrides,
246 $dbh->rollback if $oldAutoCommit;
251 warn " inserting part_pkg_currency records" if $DEBUG;
252 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
253 foreach my $key ( keys %part_pkg_currency ) {
254 $key =~ /^(.+)_([A-Z]{3})$/ or next;
255 my( $optionname, $currency ) = ( $1, $2 );
256 if ( $part_pkg_currency{$key} =~ /^\s*$/ ) {
257 if ( $self->option($optionname) == 0 ) {
258 $part_pkg_currency{$key} = '0';
260 $dbh->rollback if $oldAutoCommit;
261 ( my $thing = $optionname ) =~ s/_/ /g;
262 return ucfirst($thing). " $currency is required";
265 my $part_pkg_currency = new FS::part_pkg_currency {
266 'pkgpart' => $self->pkgpart,
267 'optionname' => $optionname,
268 'currency' => $currency,
269 'optionvalue' => $part_pkg_currency{$key},
271 my $error = $part_pkg_currency->insert;
273 $dbh->rollback if $oldAutoCommit;
278 unless ( $skip_pkg_svc_hack ) {
280 warn " inserting pkg_svc records" if $DEBUG;
281 my $pkg_svc = $options{'pkg_svc'} || {};
282 my $hidden_svc = $options{'hidden_svc'} || {};
283 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
284 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
286 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
290 my $pkg_svc = new FS::pkg_svc( {
291 'pkgpart' => $self->pkgpart,
292 'svcpart' => $part_svc->svcpart,
293 'quantity' => $quantity,
294 'primary_svc' => $primary_svc,
295 'hidden' => $hidden_svc->{$part_svc->svcpart},
297 my $error = $pkg_svc->insert;
299 $dbh->rollback if $oldAutoCommit;
304 my $error = $self->check_pkg_svc(%options);
306 $dbh->rollback if $oldAutoCommit;
312 if ( $options{'cust_pkg'} ) {
313 warn " updating cust_pkg record " if $DEBUG;
315 ref($options{'cust_pkg'})
316 ? $options{'cust_pkg'}
317 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
318 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
319 if $options{'custnum_ref'};
320 my %hash = $old_cust_pkg->hash;
321 $hash{'pkgpart'} = $self->pkgpart,
322 my $new_cust_pkg = new FS::cust_pkg \%hash;
323 local($FS::cust_pkg::disable_agentcheck) = 1;
324 my $error = $new_cust_pkg->replace($old_cust_pkg);
326 $dbh->rollback if $oldAutoCommit;
327 return "Error modifying cust_pkg record: $error";
331 if ( $options{'part_pkg_vendor'} ) {
332 while ( my ($exportnum, $vendor_pkg_id) =
333 each %{ $options{part_pkg_vendor} }
336 my $ppv = new FS::part_pkg_vendor( {
337 'pkgpart' => $self->pkgpart,
338 'exportnum' => $exportnum,
339 'vendor_pkg_id' => $vendor_pkg_id,
341 my $error = $ppv->insert;
343 $dbh->rollback if $oldAutoCommit;
344 return "Error inserting part_pkg_vendor record: $error";
349 if ( $options{fcc_options} ) {
350 warn " updating fcc options " if $DEBUG;
351 $self->set_fcc_options( $options{fcc_options} );
354 warn " committing transaction" if $DEBUG and $oldAutoCommit;
355 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
362 Currently unimplemented.
367 return "Can't (yet?) delete package definitions.";
368 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
371 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
373 Replaces OLD_RECORD with this one in the database. If there is an error,
374 returns the error, otherwise returns false.
376 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
379 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
380 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
381 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
382 'hidden' field in these records. I<bulk_skip> can be set to a hashref of
383 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
386 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
387 FS::pkg_svc record will be updated.
389 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
392 If I<part_pkg_currency> is set to a hashref of options (with the keys as
393 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
400 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
405 ( ref($_[0]) eq 'HASH' )
409 $options->{options} = { $old->options } unless defined($options->{options});
411 warn "FS::part_pkg::replace called on $new to replace $old with options".
412 join(', ', map "$_ => ". $options->{$_}, keys %$options)
415 local $SIG{HUP} = 'IGNORE';
416 local $SIG{INT} = 'IGNORE';
417 local $SIG{QUIT} = 'IGNORE';
418 local $SIG{TERM} = 'IGNORE';
419 local $SIG{TSTP} = 'IGNORE';
420 local $SIG{PIPE} = 'IGNORE';
422 my $oldAutoCommit = $FS::UID::AutoCommit;
423 local $FS::UID::AutoCommit = 0;
426 my $conf = new FS::Conf;
427 if ( $conf->exists('part_pkg-lineage') ) {
428 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
429 qw(setup_fee recur_fee) #others? config?
432 warn " superseding package" if $DEBUG;
434 my $error = $new->supersede($old, %$options);
436 $dbh->rollback if $oldAutoCommit;
440 warn " committing transaction" if $DEBUG and $oldAutoCommit;
441 $dbh->commit if $oldAutoCommit;
448 #plandata shit stays in replace for upgrades until after 2.0 (or edit
450 warn " saving legacy plandata" if $DEBUG;
451 my $plandata = $new->get('plandata');
452 $new->set('plandata', '');
454 warn " deleting old part_pkg_option records" if $DEBUG;
455 foreach my $part_pkg_option ( $old->part_pkg_option ) {
456 my $error = $part_pkg_option->delete;
458 $dbh->rollback if $oldAutoCommit;
463 warn " replacing part_pkg record" if $DEBUG;
464 my $error = $new->SUPER::replace($old, $options->{options} );
466 $dbh->rollback if $oldAutoCommit;
470 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
471 foreach my $part_pkg_option (
472 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
473 return "illegal plandata: $plandata";
475 new FS::part_pkg_option {
476 'pkgpart' => $new->pkgpart,
481 split("\n", $plandata)
483 my $error = $part_pkg_option->insert;
485 $dbh->rollback if $oldAutoCommit;
490 #trivial nit: not the most efficient to delete and reinsert
491 warn " deleting old part_pkg_currency records" if $DEBUG;
492 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
493 my $error = $part_pkg_currency->delete;
495 $dbh->rollback if $oldAutoCommit;
496 return "error deleting part_pkg_currency record: $error";
500 warn " inserting new part_pkg_currency records" if $DEBUG;
501 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
502 foreach my $key ( keys %part_pkg_currency ) {
503 $key =~ /^(.+)_([A-Z]{3})$/ or next;
504 my $part_pkg_currency = new FS::part_pkg_currency {
505 'pkgpart' => $new->pkgpart,
508 'optionvalue' => $part_pkg_currency{$key},
510 my $error = $part_pkg_currency->insert;
512 $dbh->rollback if $oldAutoCommit;
513 return "error inserting part_pkg_currency record: $error";
518 warn " replacing pkg_svc records" if $DEBUG;
519 my $pkg_svc = $options->{'pkg_svc'};
520 my $hidden_svc = $options->{'hidden_svc'} || {};
521 my $bulk_skip = $options->{'bulk_skip'} || {};
522 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
524 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
525 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
526 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
527 my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
529 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
530 && $options->{'primary_svc'} == $part_svc->svcpart
535 my $old_pkg_svc = qsearchs('pkg_svc', {
536 'pkgpart' => $old->pkgpart,
537 'svcpart' => $part_svc->svcpart,
540 my $old_quantity = 0;
541 my $old_primary_svc = '';
543 my $old_bulk_skip = '';
544 if ( $old_pkg_svc ) {
545 $old_quantity = $old_pkg_svc->quantity;
546 $old_primary_svc = $old_pkg_svc->primary_svc
547 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
548 $old_hidden = $old_pkg_svc->hidden;
549 $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
552 next unless $old_quantity != $quantity
553 || $old_primary_svc ne $primary_svc
554 || $old_hidden ne $hidden
555 || $old_bulk_skip ne $bulk_skip;
557 my $new_pkg_svc = new FS::pkg_svc( {
558 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
559 'pkgpart' => $new->pkgpart,
560 'svcpart' => $part_svc->svcpart,
561 'quantity' => $quantity,
562 'primary_svc' => $primary_svc,
564 'bulk_skip' => $bulk_skip,
566 my $error = $old_pkg_svc
567 ? $new_pkg_svc->replace($old_pkg_svc)
568 : $new_pkg_svc->insert;
570 $dbh->rollback if $oldAutoCommit;
575 my $error = $new->check_pkg_svc(%$options);
577 $dbh->rollback if $oldAutoCommit;
581 } #if $options->{pkg_svc}
583 my @part_pkg_vendor = $old->part_pkg_vendor;
584 my @current_exportnum = ();
585 if ( $options->{'part_pkg_vendor'} ) {
586 my($exportnum,$vendor_pkg_id);
587 while ( ($exportnum,$vendor_pkg_id)
588 = each %{$options->{'part_pkg_vendor'}} ) {
590 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
591 if($exportnum == $part_pkg_vendor->exportnum
592 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
593 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
594 my $error = $part_pkg_vendor->replace;
596 $dbh->rollback if $oldAutoCommit;
597 return "Error replacing part_pkg_vendor record: $error";
602 elsif($exportnum == $part_pkg_vendor->exportnum
603 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
608 unless ( $noinsert ) {
609 my $ppv = new FS::part_pkg_vendor( {
610 'pkgpart' => $new->pkgpart,
611 'exportnum' => $exportnum,
612 'vendor_pkg_id' => $vendor_pkg_id,
614 my $error = $ppv->insert;
616 $dbh->rollback if $oldAutoCommit;
617 return "Error inserting part_pkg_vendor record: $error";
620 push @current_exportnum, $exportnum;
623 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
624 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
625 my $error = $part_pkg_vendor->delete;
627 $dbh->rollback if $oldAutoCommit;
628 return "Error deleting part_pkg_vendor record: $error";
633 # propagate changes to certain core fields
634 if ( $conf->exists('part_pkg-lineage') ) {
635 warn " propagating changes to family" if $DEBUG;
636 my $error = $new->propagate($old);
638 $dbh->rollback if $oldAutoCommit;
643 if ( $options->{fcc_options} ) {
644 warn " updating fcc options " if $DEBUG;
645 $new->set_fcc_options( $options->{fcc_options} );
648 warn " committing transaction" if $DEBUG and $oldAutoCommit;
649 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
655 Checks all fields to make sure this is a valid package definition. If
656 there is an error, returns the error, otherwise returns false. Called by the
657 insert and replace methods.
663 warn "FS::part_pkg::check called on $self" if $DEBUG;
665 for (qw(setup recur plandata)) {
666 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
667 return "Use of $_ field is deprecated; set a plan and options: ".
669 if length($self->get($_));
673 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
674 my $error = $self->ut_number('freq');
675 return $error if $error;
677 $self->freq =~ /^(\d+[hdw]?)$/
678 or return "Illegal or empty freq: ". $self->freq;
682 my @null_agentnum_right = ( 'Edit global package definitions' );
683 push @null_agentnum_right, 'One-time charge'
684 if $self->freq =~ /^0/;
685 push @null_agentnum_right, 'Customize customer package'
686 if $self->disabled eq 'Y'; #good enough
688 my $error = $self->ut_numbern('pkgpart')
689 || $self->ut_text('pkg')
690 || $self->ut_textn('comment')
691 || $self->ut_textn('promo_code')
692 || $self->ut_alphan('plan')
693 || $self->ut_flag('setuptax')
694 || $self->ut_flag('recurtax')
695 || $self->ut_textn('taxclass')
696 || $self->ut_flag('disabled')
697 || $self->ut_flag('custom')
698 || $self->ut_flag('no_auto')
699 || $self->ut_flag('recur_show_zero')
700 || $self->ut_flag('setup_show_zero')
701 || $self->ut_flag('start_on_hold')
702 #|| $self->ut_moneyn('setup_cost')
703 #|| $self->ut_moneyn('recur_cost')
704 || $self->ut_floatn('setup_cost')
705 || $self->ut_floatn('recur_cost')
706 || $self->ut_floatn('pay_weight')
707 || $self->ut_floatn('credit_weight')
708 || $self->ut_numbern('taxproductnum')
709 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
710 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
711 || $self->ut_foreign_keyn('taxproductnum',
712 'part_pkg_taxproduct',
716 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
717 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
719 || $self->ut_numbern('fcc_ds0s')
720 || $self->ut_numbern('fcc_voip_class')
721 || $self->ut_numbern('delay_start')
722 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
723 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
724 || $self->ut_alphan('agent_pkgpartid')
725 || $self->SUPER::check
727 return $error if $error;
729 return 'Unknown plan '. $self->plan
730 unless exists($plans{$self->plan});
732 my $conf = new FS::Conf;
733 return 'Taxclass is required'
734 if ! $self->taxclass && $conf->exists('require_taxclasses');
741 Checks pkg_svc records as a whole (for part_svc_link dependencies).
743 If there is an error, returns the error, otherwise returns false.
748 my( $self, %opt ) = @_;
750 my $agentnum = $self->agentnum;
752 my %pkg_svc = map { $_->svcpart => $_ } $self->pkg_svc;
754 foreach my $svcpart ( keys %pkg_svc ) {
756 foreach my $part_svc_link ( $self->part_svc_link(
757 'src_svcpart' => $svcpart,
758 'link_type' => 'part_pkg_restrict',
762 return $part_svc_link->dst_svc. ' must be included with '.
763 $part_svc_link->src_svc
764 unless $pkg_svc{ $part_svc_link->dst_svcpart };
769 return '' if $opt{part_pkg_restrict_soft_override};
771 foreach my $svcpart ( keys %pkg_svc ) {
773 foreach my $part_svc_link ( $self->part_svc_link(
774 'src_svcpart' => $svcpart,
775 'link_type' => 'part_pkg_restrict_soft',
778 return $part_svc_link->dst_svc. ' is suggested with '.
779 $part_svc_link->src_svc
780 unless $pkg_svc{ $part_svc_link->dst_svcpart };
788 =item part_svc_link OPTION => VALUE ...
790 Returns the service dependencies (see L<FS::part_svc_link>) for the given
791 search options, taking into account this package definition's agent.
793 Available options are any field in part_svc_link. Typically used options are
794 src_svcpart and link_type.
799 my( $self, %opt ) = @_;
801 my $agentnum = $self->agentnum;
803 qsearch({ 'table' => 'part_svc_link',
807 ? "AND ( agentnum IS NULL OR agentnum = $agentnum )"
808 : 'AND agentnum IS NULL',
812 =item supersede OLD [, OPTION => VALUE ... ]
814 Inserts this package as a successor to the package OLD. All options are as
815 for C<insert>. After inserting, disables OLD and sets the new package as its
821 my ($new, $old, %options) = @_;
824 $new->set('pkgpart' => '');
825 $new->set('family_pkgpart' => $old->family_pkgpart);
826 warn " inserting successor package\n" if $DEBUG;
827 $error = $new->insert(%options);
828 return $error if $error;
830 warn " disabling superseded package\n" if $DEBUG;
831 $old->set('successor' => $new->pkgpart);
832 $old->set('disabled' => 'Y');
833 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
834 return $error if $error;
836 warn " propagating changes to family" if $DEBUG;
837 $new->propagate($old);
842 If any of certain fields have changed from OLD to this package, then,
843 for all packages in the same lineage as this one, sets those fields
844 to their values in this package.
848 my @propagate_fields = (
849 qw( pkg classnum setup_cost recur_cost taxclass
850 setuptax recurtax pay_weight credit_weight
858 map { $_ => $new->get($_) }
859 grep { $new->get($_) ne $old->get($_) }
863 my @part_pkg = qsearch('part_pkg', {
864 'family_pkgpart' => $new->family_pkgpart
867 foreach my $part_pkg ( @part_pkg ) {
868 my $pkgpart = $part_pkg->pkgpart;
869 next if $pkgpart == $new->pkgpart; # don't modify $new
870 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
871 foreach ( keys %fields ) {
872 $part_pkg->set($_, $fields{$_});
874 # SUPER::replace to avoid changing non-core fields
875 my $error = $part_pkg->SUPER::replace;
876 push @error, "pkgpart $pkgpart: $error"
882 =item set_fcc_options HASHREF
884 Sets the FCC options on this package definition to the values specified
889 sub set_fcc_options {
891 my $pkgpart = $self->pkgpart;
899 my %existing_num = map { $_->fccoptionname => $_->num }
900 qsearch('part_pkg_fcc_option', { pkgpart => $pkgpart });
902 local $FS::Record::nowarn_identical = 1;
903 # set up params for process_o2m
906 foreach my $name (keys %$options ) {
907 $params->{ "num$i" } = $existing_num{$name} || '';
908 $params->{ "num$i".'_fccoptionname' } = $name;
909 $params->{ "num$i".'_optionvalue' } = $options->{$name};
914 table => 'part_pkg_fcc_option',
915 fields => [qw( fccoptionname optionvalue )],
920 =item pkg_locale LOCALE
922 Returns a customer-viewable string representing this package for the given
923 locale, from the part_pkg_msgcat table. If the given locale is empty or no
924 localized string is found, returns the base pkg field.
929 my( $self, $locale ) = @_;
930 return $self->pkg unless $locale;
931 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
932 $part_pkg_msgcat->pkg;
935 =item part_pkg_msgcat LOCALE
937 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
941 sub part_pkg_msgcat {
942 my( $self, $locale ) = @_;
943 qsearchs( 'part_pkg_msgcat', {
944 pkgpart => $self->pkgpart,
949 =item pkg_comment [ OPTION => VALUE... ]
951 Returns an (internal) string representing this package. Currently,
952 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
953 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
956 If the option nopkgpart is true then the "pkgpart: ' is omitted.
964 #$self->pkg. ' - '. $self->comment;
965 #$self->pkg. ' ('. $self->comment. ')';
966 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
967 my $custom_comment = $self->custom_comment(%opt);
968 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
971 #without price info (so without hitting the DB again)
972 sub pkg_comment_only {
976 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
977 my $comment = $self->comment;
978 $pre. $self->pkg. ( $comment ? " - $comment" : '' );
981 sub price_info { # safety, in case a part_pkg hasn't defined price_info
987 my $price_info = $self->price_info(@_);
988 ( $self->custom ? '(CUSTOM) ' : '' ).
990 ( ($self->custom || $self->comment) ? ' - ' : '' ).
991 ($price_info || 'No charge');
996 $self->pkg. ' - '. ($self->price_info || 'No charge');
1001 Returns the package class, as an FS::pkg_class object, or the empty string
1002 if there is no package class.
1004 =item addon_pkg_class
1006 Returns the add-on package class, as an FS::pkg_class object, or the empty
1007 string if there is no add-on package class.
1011 sub addon_pkg_class {
1013 if ( $self->addon_classnum ) {
1014 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
1022 Returns the package category name, or the empty string if there is no package
1029 my $pkg_class = $self->pkg_class;
1031 ? $pkg_class->categoryname
1037 Returns the package class name, or the empty string if there is no package
1044 my $pkg_class = $self->pkg_class;
1046 ? $pkg_class->classname
1050 =item addon_classname
1052 Returns the add-on package class name, or the empty string if there is no
1053 add-on package class.
1057 sub addon_classname {
1059 my $pkg_class = $self->addon_pkg_class;
1061 ? $pkg_class->classname
1067 Returns the associated agent for this event, if any, as an FS::agent object.
1069 =item pkg_svc [ HASHREF | OPTION => VALUE ]
1071 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
1072 definition (with non-zero quantity).
1074 One option is available, I<disable_linked>. If set true it will return the
1075 services for this package definition alone, omitting services from any add-on
1082 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
1090 # #sort { $b->primary cmp $a->primary }
1091 # grep { $_->quantity }
1092 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
1094 my $opt = ref($_[0]) ? $_[0] : { @_ };
1095 my %pkg_svc = map { $_->svcpart => $_ }
1096 grep { $_->quantity }
1097 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
1099 unless ( $opt->{disable_linked} ) {
1100 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
1101 my @pkg_svc = grep { $_->quantity }
1102 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
1103 foreach my $pkg_svc ( @pkg_svc ) {
1104 if ( $pkg_svc{$pkg_svc->svcpart} ) {
1105 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
1106 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
1108 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
1118 =item svcpart [ SVCDB ]
1120 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
1121 associated with this package definition (see L<FS::pkg_svc>). Returns
1122 false if there not a primary service definition or exactly one service
1123 definition with quantity 1, or if SVCDB is specified and does not match the
1124 svcdb of the service definition. SVCDB can be specified as a scalar table
1125 name, such as 'svc_acct', or as an arrayref of possible table names.
1130 my $pkg_svc = shift->_primary_pkg_svc(@_);
1131 $pkg_svc ? $pkg_svc->svcpart : '';
1134 =item part_svc [ SVCDB ]
1136 Like the B<svcpart> method, but returns the FS::part_svc object (see
1142 my $pkg_svc = shift->_primary_pkg_svc(@_);
1143 $pkg_svc ? $pkg_svc->part_svc : '';
1146 sub _primary_pkg_svc {
1149 my $svcdb = scalar(@_) ? shift : [];
1150 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
1151 my %svcdb = map { $_=>1 } @$svcdb;
1154 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1157 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1158 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1160 return '' if scalar(@pkg_svc) != 1;
1164 =item svcpart_unique_svcdb SVCDB
1166 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1167 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1168 false if there not a primary service definition for SVCDB or there are multiple
1169 service definitions for SVCDB.
1173 sub svcpart_unique_svcdb {
1174 my( $self, $svcdb ) = @_;
1175 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1176 return '' if scalar(@svcdb_pkg_svc) != 1;
1177 $svcdb_pkg_svc[0]->svcpart;
1182 Returns a list of the acceptable payment types for this package. Eventually
1183 this should come out of a database table and be editable, but currently has the
1184 following logic instead:
1186 If the package is free, the single item B<BILL> is
1187 returned, otherwise, the single item B<CARD> is returned.
1189 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1195 if ( $self->is_free ) {
1204 Returns true if this package is free.
1210 if ( $self->can('is_free_options') ) {
1211 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1212 map { $self->option($_) }
1213 $self->is_free_options;
1215 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1216 "provides neither is_free_options nor is_free method; returning false";
1221 # whether the plan allows discounts to be applied to this package
1222 sub can_discount { 0; }
1224 # whether the plan allows changing the start date
1225 sub can_start_date {
1227 $self->start_on_hold ? 0 : 1;
1230 # whether the plan supports part_pkg_usageprice add-ons (a specific kind of
1231 # pre-selectable usage pricing, there's others this doesn't refer to)
1232 sub can_usageprice { 0; }
1234 # the delay start date if present
1235 sub delay_start_date {
1238 my $delay = $self->delay_start or return '';
1240 # avoid timelocal silliness
1241 my $dt = DateTime->today(time_zone => 'local');
1242 $dt->add(days => $delay);
1246 sub can_currency_exchange { 0; }
1249 # moved to FS::Misc to make this accessible to other packages
1251 FS::Misc::pkg_freqs();
1256 Returns an english representation of the I<freq> field, such as "monthly",
1257 "weekly", "semi-annually", etc.
1263 my $freq = $self->freq;
1265 #my $freqs_href = $self->freqs_href;
1266 my $freqs_href = freqs_href();
1268 if ( exists($freqs_href->{$freq}) ) {
1269 $freqs_href->{$freq};
1271 my $interval = 'month';
1272 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1273 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1274 $interval = $interval{$2};
1279 "every $freq ${interval}s";
1284 =item add_freq TIMESTAMP [ FREQ ]
1286 Adds a billing period of some frequency to the provided timestamp and
1287 returns the resulting timestamp, or -1 if the frequency could not be
1288 parsed (shouldn't happen). By default, the frequency of this package
1289 will be used; to override this, pass a different frequency as a second
1295 my( $self, $date, $freq ) = @_;
1296 $freq = $self->freq unless $freq;
1298 #change this bit to use Date::Manip? CAREFUL with timezones (see
1299 # mailing list archive)
1300 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1302 if ( $freq =~ /^\d+$/ ) {
1304 until ( $mon < 12 ) { $mon -= 12; $year++; }
1306 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1308 } elsif ( $freq =~ /^(\d+)w$/ ) {
1310 $mday += $weeks * 7;
1311 } elsif ( $freq =~ /^(\d+)d$/ ) {
1314 } elsif ( $freq =~ /^(\d+)h$/ ) {
1321 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1326 For backwards compatibility, returns the plandata field as well as all options
1327 from FS::part_pkg_option.
1333 carp "plandata is deprecated";
1335 $self->SUPER::plandata(@_);
1337 my $plandata = $self->get('plandata');
1338 my %options = $self->options;
1339 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1344 =item part_pkg_vendor
1346 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1347 L<FS::part_pkg_vendor>).
1349 =item vendor_pkg_ids
1351 Returns a list of vendor/external package ids by exportnum
1355 sub vendor_pkg_ids {
1357 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1360 =item part_pkg_option
1362 Returns all options as FS::part_pkg_option objects (see
1363 L<FS::part_pkg_option>).
1367 Returns a list of option names and values suitable for assigning to a hash.
1373 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1376 =item option OPTIONNAME [ QUIET ]
1378 Returns the option value for the given name, or the empty string. If a true
1379 value is passed as the second argument, warnings about missing the option
1385 my( $self, $opt, $ornull ) = @_;
1387 #cache: was pulled up in the original part_pkg query
1388 if ( $opt =~ /^(setup|recur)_fee$/ && defined($self->hashref->{"_$opt"}) ) {
1389 return $self->hashref->{"_$opt"};
1392 cluck "$self -> option: searching for $opt"
1394 my $part_pkg_option =
1395 qsearchs('part_pkg_option', {
1396 pkgpart => $self->pkgpart,
1399 return $part_pkg_option->optionvalue if $part_pkg_option;
1401 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1402 split("\n", $self->get('plandata') );
1403 return $plandata{$opt} if exists $plandata{$opt};
1404 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1405 "not found in options or plandata!\n"
1411 =item part_pkg_currency [ CURRENCY ]
1413 Returns all currency options as FS::part_pkg_currency objects (see
1414 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1415 objects for that currency.
1419 sub part_pkg_currency {
1421 my %hash = ( 'pkgpart' => $self->pkgpart );
1422 $hash{'currency'} = shift if @_;
1423 qsearch('part_pkg_currency', \%hash );
1426 =item part_pkg_currency_options CURRENCY
1428 Returns a list of option names and values from FS::part_pkg_currency for the
1433 sub part_pkg_currency_options {
1435 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1438 =item part_pkg_currency_option CURRENCY OPTIONNAME
1440 Returns the option value for the given name and currency.
1444 sub part_pkg_currency_option {
1445 my( $self, $currency, $optionname ) = @_;
1446 my $part_pkg_currency =
1447 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1448 'currency' => $currency,
1449 'optionname' => $optionname,
1452 #fatal if not found? that works for our use cases from
1453 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1454 #to behave. have to catch it there if we change it here...
1455 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1457 $part_pkg_currency->optionvalue;
1460 =item fcc_option OPTIONNAME
1462 Returns the FCC 477 report option value for the given name, or the empty
1468 my ($self, $name) = @_;
1469 my $part_pkg_fcc_option =
1470 qsearchs('part_pkg_fcc_option', {
1471 pkgpart => $self->pkgpart,
1472 fccoptionname => $name,
1474 $part_pkg_fcc_option ? $part_pkg_fcc_option->optionvalue : '';
1479 Returns all FCC 477 report options for this package, as a hash-like list.
1485 map { $_->fccoptionname => $_->optionvalue }
1486 qsearch('part_pkg_fcc_option', { pkgpart => $self->pkgpart });
1489 =item bill_part_pkg_link
1491 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1495 sub bill_part_pkg_link {
1496 shift->_part_pkg_link('bill', @_);
1499 =item svc_part_pkg_link
1501 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1505 sub svc_part_pkg_link {
1506 shift->_part_pkg_link('svc', @_);
1509 =item supp_part_pkg_link
1511 Returns the associated part_pkg_link records of type 'supp' (supplemental
1516 sub supp_part_pkg_link {
1517 shift->_part_pkg_link('supp', @_);
1520 sub _part_pkg_link {
1521 my( $self, $type ) = @_;
1522 qsearch({ table => 'part_pkg_link',
1523 hashref => { 'src_pkgpart' => $self->pkgpart,
1524 'link_type' => $type,
1525 #protection against infinite recursive links
1526 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1528 order_by => "ORDER BY hidden",
1532 sub self_and_bill_linked {
1533 shift->_self_and_linked('bill', @_);
1536 sub self_and_svc_linked {
1537 shift->_self_and_linked('svc', @_);
1540 sub _self_and_linked {
1541 my( $self, $type, $hidden ) = @_;
1545 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1546 $self->_part_pkg_link($type) ) )
1548 $_->hidden($hidden) if $hidden;
1555 =item part_pkg_taxoverride [ CLASS ]
1557 Returns all associated FS::part_pkg_taxoverride objects (see
1558 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1559 of class CLASS if defined. Class may be one of 'setup', 'recur',
1560 the empty string (default), or a usage class number (see L<FS::usage_class>).
1561 When a class is specified, the empty string class (default) is returned
1562 if no more specific values exist.
1566 sub part_pkg_taxoverride {
1570 my $hashref = { 'pkgpart' => $self->pkgpart };
1571 $hashref->{'usage_class'} = $class if defined($class);
1572 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1574 unless ( scalar(@overrides) || !defined($class) || !$class ){
1575 $hashref->{'usage_class'} = '';
1576 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1582 =item has_taxproduct
1584 Returns true if this package has any taxproduct associated with it.
1588 sub has_taxproduct {
1591 $self->taxproductnum ||
1592 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1593 keys %{ {$self->options} }
1599 =item taxproduct [ CLASS ]
1601 Returns the associated tax product for this package definition (see
1602 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1603 the usage classnum (see L<FS::usage_class>). Returns the default
1604 tax product for this record if the more specific CLASS value does
1613 my $part_pkg_taxproduct;
1615 my $taxproductnum = $self->taxproductnum;
1617 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1618 $taxproductnum = $class_taxproductnum
1619 if $class_taxproductnum
1622 $part_pkg_taxproduct =
1623 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1625 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1626 $taxproductnum = $self->taxproductnum;
1627 $part_pkg_taxproduct =
1628 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1631 $part_pkg_taxproduct;
1634 =item taxproduct_description [ CLASS ]
1636 Returns the description of the associated tax product for this package
1637 definition (see L<FS::part_pkg_taxproduct>).
1641 sub taxproduct_description {
1643 my $part_pkg_taxproduct = $self->taxproduct(@_);
1644 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1648 =item tax_rates DATA_PROVIDER, GEOCODE, [ CLASS ]
1650 Returns the tax table entries (L<FS::tax_rate> objects) that apply to this
1651 package in the location specified by GEOCODE, for usage class CLASS (one of
1652 'setup', 'recur', null, or a C<usage_class> number).
1658 my ($vendor, $geocode, $class) = @_;
1659 # if this part_pkg is overridden into a specific taxclass, get that class
1660 my @taxclassnums = map { $_->taxclassnum }
1661 $self->part_pkg_taxoverride($class);
1662 # otherwise, get its tax product category
1663 if (!@taxclassnums) {
1664 my $part_pkg_taxproduct = $self->taxproduct($class);
1665 # If this isn't defined, then the class has no taxproduct designation,
1666 # so return no tax rates.
1667 return () if !$part_pkg_taxproduct;
1669 # convert the taxproduct to the tax classes that might apply to it in
1671 @taxclassnums = map { $_->taxclassnum }
1672 grep { $_->taxable eq 'Y' } # why do we need this?
1673 $part_pkg_taxproduct->part_pkg_taxrate($geocode);
1675 return unless @taxclassnums;
1677 # then look up the actual tax_rate entries
1678 warn "Found taxclassnum values of ". join(',', @taxclassnums) ."\n"
1680 my $extra_sql = "AND taxclassnum IN (". join(',', @taxclassnums) . ")";
1681 my @taxes = qsearch({ 'table' => 'tax_rate',
1682 'hashref' => { 'geocode' => $geocode,
1683 'data_vendor' => $vendor,
1685 'extra_sql' => $extra_sql,
1687 warn "Found taxes ". join(',', map {$_->taxnum} @taxes) ."\n"
1693 =item part_pkg_discount
1695 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1698 =item part_pkg_usage
1700 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1705 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1706 PLAN is the object's I<plan> field. There should be better docs
1707 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1713 my $plan = $self->plan;
1715 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1719 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1720 my $class = ref($self). "::$plan";
1721 warn "reblessing $self into $class" if $DEBUG > 1;
1724 bless($self, $class) unless $@;
1728 =item calc_setup CUST_PKG START_DATE DETAILS_ARRAYREF OPTIONS_HASHREF
1730 =item calc_recur CUST_PKG START_DATE DETAILS_ARRAYREF OPTIONS_HASHREF
1732 Calculates and returns the setup or recurring fees, respectively, for this
1733 package. Implementation is in the FS::part_pkg:* module specific to this price
1736 Adds invoicing details to the passed-in DETAILS_ARRAYREF
1738 Options are passed as a hashref. Available options:
1744 Frequency override (for calc_recur)
1748 This option is filled in by the method rather than controlling its operation.
1749 It is an arrayref. Applicable discounts will be added to the arrayref, as
1750 L<FS::cust_bill_pkg_discount|FS::cust_bill_pkg_discount records>.
1754 For package add-ons, is the base L<FS::part_pkg|package definition>, otherwise
1755 no different than pkgpart.
1757 =item precommit_hooks
1759 This option is filled in by the method rather than controlling its operation.
1760 It is an arrayref. Anonymous coderefs will be added to the arrayref. They
1761 need to be called before completing the billing operation. For calc_recur
1764 =item increment_next_bill
1766 Increment the next bill date (boolean, for calc_recur). Typically true except
1767 for particular situations.
1771 This option is filled in by the method rather than controlling its operation.
1772 It indicates a deferred setup fee that is billed at calc_recur time (see price
1773 plan option prorate_defer_bill).
1777 Note: Don't calculate prices when not actually billing the package. For that,
1778 see the L</base_setup|base_setup> and L</base_recur|base_recur> methods.
1783 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1784 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1786 =item calc_remain CUST_PKG [ OPTION => VALUE ... ]
1788 Calculates and returns the remaining value to be credited upon package
1789 suspension, change, or cancellation, if enabled.
1791 Options are passed as a list of keys and values. Available options:
1797 Override for the current time
1799 =item cust_credit_source_bill_pkg
1801 This option is filled in by the method rather than controlling its operation.
1803 L<FS::cust_credit_source_bill_pkg|FS::cust_credit_source_bill_pkg> records will
1804 be added to the arrayref indicating the specific line items and amounts which
1805 are the source of this remaining credit.
1809 Note: Don't calculate prices when not actually suspending or cancelling the
1814 #fallback that returns 0 for old legacy packages with no plan
1815 sub calc_remain { 0; }
1817 =item calc_units CUST_PKG
1819 This returns the number of provisioned svc_phone records, or, of the package
1820 count_available_phones option is set, the number available to be provisoined
1825 #fallback that returns 0 for old legacy packages with no plan
1826 sub calc_units { 0; }
1828 #fallback for everything not based on flat.pm
1829 sub recur_temporality { 'upcoming'; }
1831 =item calc_cancel START_DATE DETAILS_ARRAYREF OPTIONS_HASHREF
1833 Runs any necessary billing on cancellation: another recurring cycle for
1834 recur_temporailty 'preceding' pacakges with the bill_recur_on_cancel option
1835 set (calc_recur), or, any outstanding usage for pacakges with the
1836 bill_usage_on_cancel option set (calc_usage).
1840 #fallback for everything not based on flat.pm, doesn't do this yet (which is
1841 #okay, nothing of ours not based on flat.pm does usage-on-cancel billing
1842 sub calc_cancel { 0; }
1844 #fallback for everything except bulk.pm
1845 sub hide_svc_detail { 0; }
1847 #fallback for packages that can't/won't summarize usage
1848 sub sum_usage { 0; }
1850 =item recur_cost_permonth CUST_PKG
1852 recur_cost divided by freq (only supported for monthly and longer frequencies)
1856 sub recur_cost_permonth {
1857 my($self, $cust_pkg) = @_;
1858 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1859 sprintf('%.2f', ($self->recur_cost || 0) / $self->freq );
1862 =item cust_bill_pkg_recur CUST_PKG
1864 Actual recurring charge for the specified customer package from customer's most
1869 sub cust_bill_pkg_recur {
1870 my($self, $cust_pkg) = @_;
1871 my $cust_bill_pkg = qsearchs({
1872 'table' => 'cust_bill_pkg',
1873 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1874 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1875 'recur' => { op=>'>', value=>'0' },
1877 'order_by' => 'ORDER BY cust_bill._date DESC,
1878 cust_bill_pkg.sdate DESC
1881 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1882 $cust_bill_pkg->recur;
1885 =item unit_setup CUST_PKG
1887 Returns the setup fee for one unit of the package.
1892 my ($self, $cust_pkg) = @_;
1893 $self->option('setup_fee') || 0;
1898 unit_setup minus setup_cost
1904 $self->unit_setup(@_) - ($self->setup_cost || 0);
1907 =item recur_margin_permonth
1909 base_recur_permonth minus recur_cost_permonth
1913 sub recur_margin_permonth {
1915 $self->base_recur_permonth(@_) - $self->recur_cost_permonth(@_);
1918 =item format OPTION DATA
1920 Returns data formatted according to the function 'format' described
1921 in the plan info. Returns DATA if no such function exists.
1926 my ($self, $option, $data) = (shift, shift, shift);
1927 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1928 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1934 =item parse OPTION DATA
1936 Returns data parsed according to the function 'parse' described
1937 in the plan info. Returns DATA if no such function exists.
1942 my ($self, $option, $data) = (shift, shift, shift);
1943 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1944 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1954 =head1 CLASS METHODS
1962 # Used by FS::Upgrade to migrate to a new database.
1964 sub _upgrade_data { # class method
1965 my($class, %opts) = @_;
1967 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1969 my @part_pkg = qsearch({
1970 'table' => 'part_pkg',
1971 'extra_sql' => "WHERE ". join(' OR ',
1972 'plan IS NULL', "plan = '' ",
1976 foreach my $part_pkg (@part_pkg) {
1978 unless ( $part_pkg->plan ) {
1979 $part_pkg->plan('flat');
1986 # Convert RADIUS accounting usage metrics from megabytes to gigabytes
1988 my $upgrade = 'part_pkg_gigabyte_usage';
1989 if (!FS::upgrade_journal->is_done($upgrade)) {
1990 foreach my $part_pkg (qsearch('part_pkg',
1991 { plan => 'sqlradacct_hour' })
1994 my $pkgpart = $part_pkg->pkgpart;
1996 foreach my $opt (qsearch('part_pkg_option',
1997 { 'optionname' => { op => 'LIKE',
1998 value => 'recur_included_%',
2000 pkgpart => $pkgpart,
2003 next if $opt->optionname eq 'recur_included_hours'; # unfortunately named field
2004 next if $opt->optionvalue == 0;
2006 $opt->optionvalue($opt->optionvalue / 1024);
2008 my $error = $opt->replace;
2009 die $error if $error;
2012 foreach my $opt (qsearch('part_pkg_option',
2013 { 'optionname' => { op => 'LIKE',
2014 value => 'recur_%_charge',
2016 pkgpart => $pkgpart,
2018 $opt->optionvalue($opt->optionvalue * 1024);
2020 my $error = $opt->replace;
2021 die $error if $error;
2025 FS::upgrade_journal->set_done($upgrade);
2028 # the rest can be done asynchronously
2031 sub queueable_upgrade {
2032 # now upgrade to the explicit custom flag
2034 my $search = FS::Cursor->new({
2035 'table' => 'part_pkg',
2036 'hashref' => { disabled => 'Y', custom => '' },
2037 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
2041 while (my $part_pkg = $search->fetch) {
2042 my $new = new FS::part_pkg { $part_pkg->hash };
2044 my $comment = $part_pkg->comment;
2045 $comment =~ s/^\(CUSTOM\) //;
2046 $comment = '(none)' unless $comment =~ /\S/;
2047 $new->comment($comment);
2049 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
2050 my $primary = $part_pkg->svcpart;
2051 my $options = { $part_pkg->options };
2053 my $error = $new->replace( $part_pkg,
2054 'pkg_svc' => $pkg_svc,
2055 'primary_svc' => $primary,
2056 'options' => $options,
2059 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
2066 # set family_pkgpart on any packages that don't have it
2067 $search = FS::Cursor->new('part_pkg', { 'family_pkgpart' => '' });
2068 while (my $part_pkg = $search->fetch) {
2069 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
2070 my $error = $part_pkg->SUPER::replace;
2072 warn "pkgpart#".$part_pkg->pkgpart.": $error\n";
2079 my @part_pkg_option = qsearch('part_pkg_option',
2080 { 'optionname' => 'unused_credit',
2083 foreach my $old_opt (@part_pkg_option) {
2084 my $pkgpart = $old_opt->pkgpart;
2085 my $error = $old_opt->delete;
2086 die $error if $error;
2088 foreach (qw(unused_credit_cancel unused_credit_change)) {
2089 my $new_opt = new FS::part_pkg_option {
2090 'pkgpart' => $pkgpart,
2094 $error = $new_opt->insert;
2095 die $error if $error;
2099 # migrate use_disposition_taqua and use_disposition to disposition_in
2100 @part_pkg_option = qsearch('part_pkg_option',
2101 { 'optionname' => { op => 'LIKE',
2102 value => 'use_disposition%',
2106 my %newopts = map { $_->pkgpart => $_ }
2107 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
2108 foreach my $old_opt (@part_pkg_option) {
2109 my $pkgpart = $old_opt->pkgpart;
2110 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
2112 my $error = $old_opt->delete;
2113 die $error if $error;
2115 if ( exists($newopts{$pkgpart}) ) {
2116 my $opt = $newopts{$pkgpart};
2117 $opt->optionvalue($opt->optionvalue.",$newval");
2118 $error = $opt->replace;
2119 die $error if $error;
2121 my $new_opt = new FS::part_pkg_option {
2122 'pkgpart' => $pkgpart,
2123 'optionname' => 'disposition_in',
2124 'optionvalue' => $newval,
2126 $error = $new_opt->insert;
2127 die $error if $error;
2128 $newopts{$pkgpart} = $new_opt;
2132 # set any package with FCC voice lines to the "VoIP with broadband" category
2133 # for backward compatibility
2135 # recover from a bad upgrade bug
2136 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
2137 if (!FS::upgrade_journal->is_done($upgrade)) {
2138 my $bad_upgrade = qsearchs('upgrade_journal',
2139 { upgrade => 'part_pkg_fcc_voip_class' }
2141 if ( $bad_upgrade ) {
2142 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
2143 ' AND history_date > '.($bad_upgrade->_date - 3600);
2144 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
2147 'table' => 'h_part_pkg_option',
2149 'extra_sql' => "$where AND history_action = 'delete'",
2150 'order_by' => 'ORDER BY history_date ASC',
2152 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
2155 'table' => 'h_pkg_svc',
2157 'extra_sql' => "$where AND history_action = 'replace_old'",
2158 'order_by' => 'ORDER BY history_date ASC',
2161 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
2162 my $pkgpart ||= $deleted->pkgpart;
2163 $opt{$pkgpart} ||= {
2169 if ( $deleted->isa('FS::part_pkg_option') ) {
2170 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
2172 my $svcpart = $deleted->svcpart;
2173 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
2174 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
2175 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
2178 foreach my $pkgpart (keys %opt) {
2179 my $part_pkg = FS::part_pkg->by_key($pkgpart);
2180 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
2182 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
2185 } # $bad_upgrade exists
2186 else { # do the original upgrade, but correctly this time
2187 my @part_pkg = qsearch('part_pkg', {
2188 fcc_ds0s => { op => '>', value => 0 },
2189 fcc_voip_class => ''
2191 foreach my $part_pkg (@part_pkg) {
2192 $part_pkg->set(fcc_voip_class => 2);
2193 my @pkg_svc = $part_pkg->pkg_svc;
2194 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
2195 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
2196 my $error = $part_pkg->replace(
2197 $part_pkg->replace_old,
2198 options => { $part_pkg->options },
2199 pkg_svc => \%quantity,
2200 hidden_svc => \%hidden,
2201 primary_svc => ($part_pkg->svcpart || ''),
2203 die $error if $error;
2206 FS::upgrade_journal->set_done($upgrade);
2211 =item curuser_pkgs_sql
2213 Returns an SQL fragment for searching for packages the current user can
2214 use, either via part_pkg.agentnum directly, or via agent type (see
2219 sub curuser_pkgs_sql {
2222 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
2226 =item agent_pkgs_sql AGENT | AGENTNUM, ...
2228 Returns an SQL fragment for searching for packages the provided agent or agents
2229 can use, either via part_pkg.agentnum directly, or via agent type (see
2234 sub agent_pkgs_sql {
2235 my $class = shift; #i'm a class method, not a sub (the question is... why??)
2236 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
2238 $class->_pkgs_sql(@agentnums); #is this why
2243 my( $class, @agentnums ) = @_;
2244 my $agentnums = join(',', @agentnums);
2248 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
2249 OR ( agentnum IS NULL
2250 AND EXISTS ( SELECT 1
2252 LEFT JOIN agent_type USING ( typenum )
2253 LEFT JOIN agent AS typeagent USING ( typenum )
2254 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
2255 AND typeagent.agentnum IN ($agentnums)
2273 #false laziness w/part_export & cdr
2275 foreach my $INC ( @INC ) {
2276 warn "globbing $INC/FS/part_pkg/[a-z]*.pm\n" if $DEBUG;
2277 foreach my $file ( glob("$INC/FS/part_pkg/[a-z]*.pm") ) {
2278 warn "attempting to load plan info from $file\n" if $DEBUG;
2279 $file =~ /\/(\w+)\.pm$/ or do {
2280 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
2284 my $info = eval "use FS::part_pkg::$mod; ".
2285 "\\%FS::part_pkg::$mod\::info;";
2287 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
2290 unless ( keys %$info ) {
2291 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
2294 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
2295 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
2296 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
2299 $info{$mod} = $info;
2300 $info->{'weight'} ||= 0; # quiet warnings
2304 # copy one level deep to allow replacement of fields and fieldorder
2305 tie %plans, 'Tie::IxHash',
2306 map { my %infohash = %{ $info{$_} };
2308 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
2311 # inheritance of plan options
2312 foreach my $name (keys(%info)) {
2313 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
2314 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
2315 delete $plans{$name};
2318 my $parents = $info{$name}->{'inherit_fields'} || [];
2319 my (%fields, %field_exists, @fieldorder);
2320 foreach my $parent ($name, @$parents) {
2321 if ( !exists($info{$parent}) ) {
2322 warn "$name tried to inherit from nonexistent '$parent'\n";
2325 %fields = ( # avoid replacing existing fields
2326 %{ $info{$parent}->{'fields'} || {} },
2329 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
2331 next if $field_exists{$_};
2332 $field_exists{$_} = 1;
2333 # allow inheritors to remove inherited fields from the fieldorder
2334 push @fieldorder, $_ if !exists($fields{$_}) or
2335 !exists($fields{$_}->{'disabled'});
2338 $plans{$name}->{'fields'} = \%fields;
2339 $plans{$name}->{'fieldorder'} = \@fieldorder;
2349 =head1 NEW PLAN CLASSES
2351 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
2352 found in eg/plan_template.pm. Until then, it is suggested that you use the
2353 other modules in FS/FS/part_pkg/ as a guide.
2357 The delete method is unimplemented.
2359 setup and recur semantics are not yet defined (and are implemented in
2360 FS::cust_bill. hmm.). now they're deprecated and need to go.
2364 part_pkg_taxrate is Pg specific
2366 replace should be smarter about managing the related tables (options, pkg_svc)
2370 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2371 schema.html from the base documentation.