2 use base qw( FS::m2m_Common FS::o2m_Common FS::option_Common );
5 use vars qw( %plans $DEBUG $setup_hack $skip_pkg_svc_hack );
6 use Carp qw(carp cluck confess);
7 use Scalar::Util qw( blessed );
9 use Time::Local qw( timelocal timelocal_nocheck ); # eventually replace with DateTime
12 use FS::Record qw( qsearch qsearchs dbh dbdef );
18 use FS::part_pkg_option;
19 use FS::part_pkg_msgcat;
20 use FS::part_pkg_taxrate;
21 use FS::part_pkg_taxoverride;
22 use FS::part_pkg_taxproduct;
23 use FS::part_pkg_link;
24 use FS::part_pkg_discount;
25 use FS::part_pkg_vendor;
26 use FS::part_pkg_currency;
30 $skip_pkg_svc_hack = 0;
34 FS::part_pkg - Object methods for part_pkg objects
40 $record = new FS::part_pkg \%hash
41 $record = new FS::part_pkg { 'column' => 'value' };
43 $custom_record = $template_record->clone;
45 $error = $record->insert;
47 $error = $new_record->replace($old_record);
49 $error = $record->delete;
51 $error = $record->check;
53 @pkg_svc = $record->pkg_svc;
55 $svcnum = $record->svcpart;
56 $svcnum = $record->svcpart( 'svc_acct' );
60 An FS::part_pkg object represents a package definition. FS::part_pkg
61 inherits from FS::Record. The following fields are currently supported:
65 =item pkgpart - primary key (assigned automatically for new package definitions)
67 =item pkg - Text name of this package definition (customer-viewable)
69 =item comment - Text name of this package definition (non-customer-viewable)
71 =item classnum - Optional package class (see L<FS::pkg_class>)
73 =item promo_code - Promotional code
75 =item setup - Setup fee expression (deprecated)
77 =item freq - Frequency of recurring fee
79 =item recur - Recurring fee expression (deprecated)
81 =item setuptax - Setup fee tax exempt flag, empty or `Y'
83 =item recurtax - Recurring fee tax exempt flag, empty or `Y'
85 =item taxclass - Tax class
87 =item plan - Price plan
89 =item plandata - Price plan data (deprecated - see L<FS::part_pkg_option> instead)
91 =item disabled - Disabled flag, empty or `Y'
93 =item custom - Custom flag, empty or `Y'
95 =item setup_cost - for cost tracking
97 =item recur_cost - for cost tracking
99 =item pay_weight - Weight (relative to credit_weight and other package definitions) that controls payment application to specific line items.
101 =item credit_weight - Weight (relative to other package definitions) that controls credit application to specific line items.
103 =item agentnum - Optional agentnum (see L<FS::agent>)
105 =item fcc_ds0s - Optional DS0 equivalency number for FCC form 477
107 =item fcc_voip_class - Which column of FCC form 477 part II.B this package
110 =item successor - Foreign key for the part_pkg that replaced this record.
111 If this record is not obsolete, will be null.
113 =item family_pkgpart - Foreign key for the part_pkg that was the earliest
114 ancestor of this record. If this record is not a successor to another
115 part_pkg, will be equal to pkgpart.
117 =item delay_start - Number of days to delay package start, by default
127 Creates a new package definition. To add the package definition to
128 the database, see L<"insert">.
132 sub table { 'part_pkg'; }
136 An alternate constructor. Creates a new package definition by duplicating
137 an existing definition. A new pkgpart is assigned and the custom flag is
138 set to Y. To add the package definition to the database, see L<"insert">.
144 my $class = ref($self);
145 my %hash = $self->hash;
146 $hash{'pkgpart'} = '';
147 $hash{'custom'} = 'Y';
148 #new FS::part_pkg ( \%hash ); # ?
149 new $class ( \%hash ); # ?
152 =item insert [ , OPTION => VALUE ... ]
154 Adds this package definition to the database. If there is an error,
155 returns the error, otherwise returns false.
157 Currently available options are: I<pkg_svc>, I<primary_svc>, I<cust_pkg>,
158 I<custnum_ref> and I<options>.
160 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
161 values, appropriate FS::pkg_svc records will be inserted. I<hidden_svc> can
162 be set to a hashref of svcparts and flag values ('Y' or '') to set the
163 'hidden' field in these records.
165 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
166 FS::pkg_svc record will be updated.
168 If I<cust_pkg> is set to a pkgnum of a FS::cust_pkg record (or the FS::cust_pkg
169 record itself), the object will be updated to point to this package definition.
171 In conjunction with I<cust_pkg>, if I<custnum_ref> is set to a scalar reference,
172 the scalar will be updated with the custnum value from the cust_pkg record.
174 If I<tax_overrides> is set to a hashref with usage classes as keys and comma
175 separated tax class numbers as values, appropriate FS::part_pkg_taxoverride
176 records will be inserted.
178 If I<options> is set to a hashref of options, appropriate FS::part_pkg_option
179 records will be inserted.
181 If I<part_pkg_currency> is set to a hashref of options (with the keys as
182 option_CURRENCY), appropriate FS::part_pkg::currency records will be inserted.
189 warn "FS::part_pkg::insert called on $self with options ".
190 join(', ', map "$_=>$options{$_}", keys %options)
193 local $SIG{HUP} = 'IGNORE';
194 local $SIG{INT} = 'IGNORE';
195 local $SIG{QUIT} = 'IGNORE';
196 local $SIG{TERM} = 'IGNORE';
197 local $SIG{TSTP} = 'IGNORE';
198 local $SIG{PIPE} = 'IGNORE';
200 my $oldAutoCommit = $FS::UID::AutoCommit;
201 local $FS::UID::AutoCommit = 0;
204 warn " inserting part_pkg record" if $DEBUG;
205 my $error = $self->SUPER::insert( $options{options} );
207 $dbh->rollback if $oldAutoCommit;
212 if ( $self->get('family_pkgpart') eq '' ) {
213 $self->set('family_pkgpart' => $self->pkgpart);
214 $error = $self->SUPER::replace;
216 $dbh->rollback if $oldAutoCommit;
221 my $conf = new FS::Conf;
222 if ( $conf->exists('agent_defaultpkg') ) {
223 warn " agent_defaultpkg set; allowing all agents to purchase package"
225 foreach my $agent_type ( qsearch('agent_type', {} ) ) {
226 my $type_pkgs = new FS::type_pkgs({
227 'typenum' => $agent_type->typenum,
228 'pkgpart' => $self->pkgpart,
230 my $error = $type_pkgs->insert;
232 $dbh->rollback if $oldAutoCommit;
238 warn " inserting part_pkg_taxoverride records" if $DEBUG;
239 my %overrides = %{ $options{'tax_overrides'} || {} };
240 foreach my $usage_class ( keys %overrides ) {
242 ( exists($overrides{$usage_class}) && defined($overrides{$usage_class}) )
243 ? $overrides{$usage_class}
245 my @overrides = (grep "$_", split(',', $override) );
246 my $error = $self->process_m2m (
247 'link_table' => 'part_pkg_taxoverride',
248 'target_table' => 'tax_class',
249 'hashref' => { 'usage_class' => $usage_class },
250 'params' => \@overrides,
253 $dbh->rollback if $oldAutoCommit;
258 warn " inserting part_pkg_currency records" if $DEBUG;
259 my %part_pkg_currency = %{ $options{'part_pkg_currency'} || {} };
260 foreach my $key ( keys %part_pkg_currency ) {
261 $key =~ /^(.+)_([A-Z]{3})$/ or next;
262 my $part_pkg_currency = new FS::part_pkg_currency {
263 'pkgpart' => $self->pkgpart,
266 'optionvalue' => $part_pkg_currency{$key},
268 my $error = $part_pkg_currency->insert;
270 $dbh->rollback if $oldAutoCommit;
275 unless ( $skip_pkg_svc_hack ) {
277 warn " inserting pkg_svc records" if $DEBUG;
278 my $pkg_svc = $options{'pkg_svc'} || {};
279 my $hidden_svc = $options{'hidden_svc'} || {};
280 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
281 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
283 ( $options{'primary_svc'} && $options{'primary_svc'}==$part_svc->svcpart )
287 my $pkg_svc = new FS::pkg_svc( {
288 'pkgpart' => $self->pkgpart,
289 'svcpart' => $part_svc->svcpart,
290 'quantity' => $quantity,
291 'primary_svc' => $primary_svc,
292 'hidden' => $hidden_svc->{$part_svc->svcpart},
294 my $error = $pkg_svc->insert;
296 $dbh->rollback if $oldAutoCommit;
303 if ( $options{'cust_pkg'} ) {
304 warn " updating cust_pkg record " if $DEBUG;
306 ref($options{'cust_pkg'})
307 ? $options{'cust_pkg'}
308 : qsearchs('cust_pkg', { pkgnum => $options{'cust_pkg'} } );
309 ${ $options{'custnum_ref'} } = $old_cust_pkg->custnum
310 if $options{'custnum_ref'};
311 my %hash = $old_cust_pkg->hash;
312 $hash{'pkgpart'} = $self->pkgpart,
313 my $new_cust_pkg = new FS::cust_pkg \%hash;
314 local($FS::cust_pkg::disable_agentcheck) = 1;
315 my $error = $new_cust_pkg->replace($old_cust_pkg);
317 $dbh->rollback if $oldAutoCommit;
318 return "Error modifying cust_pkg record: $error";
322 if ( $options{'part_pkg_vendor'} ) {
323 while ( my ($exportnum, $vendor_pkg_id) =
324 each %{ $options{part_pkg_vendor} }
327 my $ppv = new FS::part_pkg_vendor( {
328 'pkgpart' => $self->pkgpart,
329 'exportnum' => $exportnum,
330 'vendor_pkg_id' => $vendor_pkg_id,
332 my $error = $ppv->insert;
334 $dbh->rollback if $oldAutoCommit;
335 return "Error inserting part_pkg_vendor record: $error";
340 warn " committing transaction" if $DEBUG and $oldAutoCommit;
341 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
348 Currently unimplemented.
353 return "Can't (yet?) delete package definitions.";
354 # check & make sure the pkgpart isn't in cust_pkg or type_pkgs?
357 =item replace OLD_RECORD [ , OPTION => VALUE ... ]
359 Replaces OLD_RECORD with this one in the database. If there is an error,
360 returns the error, otherwise returns false.
362 Currently available options are: I<pkg_svc>, I<hidden_svc>, I<primary_svc>
365 If I<pkg_svc> is set to a hashref with svcparts as keys and quantities as
366 values, the appropriate FS::pkg_svc records will be replaced. I<hidden_svc>
367 can be set to a hashref of svcparts and flag values ('Y' or '') to set the
368 'hidden' field in these records. I<bulk_skip> can be set to a hashref of
369 svcparts and flag values ('Y' or '') to set the 'bulk_skip' field in those
372 If I<primary_svc> is set to the svcpart of the primary service, the appropriate
373 FS::pkg_svc record will be updated.
375 If I<options> is set to a hashref, the appropriate FS::part_pkg_option records
378 If I<part_pkg_currency> is set to a hashref of options (with the keys as
379 option_CURRENCY), appropriate FS::part_pkg::currency records will be replaced.
386 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
391 ( ref($_[0]) eq 'HASH' )
395 $options->{options} = { $old->options } unless defined($options->{options});
397 warn "FS::part_pkg::replace called on $new to replace $old with options".
398 join(', ', map "$_ => ". $options->{$_}, keys %$options)
401 local $SIG{HUP} = 'IGNORE';
402 local $SIG{INT} = 'IGNORE';
403 local $SIG{QUIT} = 'IGNORE';
404 local $SIG{TERM} = 'IGNORE';
405 local $SIG{TSTP} = 'IGNORE';
406 local $SIG{PIPE} = 'IGNORE';
408 my $oldAutoCommit = $FS::UID::AutoCommit;
409 local $FS::UID::AutoCommit = 0;
412 my $conf = new FS::Conf;
413 if ( $conf->exists('part_pkg-lineage') ) {
414 if ( grep { $options->{options}->{$_} ne $old->option($_, 1) }
415 qw(setup_fee recur_fee) #others? config?
418 warn " superseding package" if $DEBUG;
420 my $error = $new->supersede($old, %$options);
422 $dbh->rollback if $oldAutoCommit;
426 warn " committing transaction" if $DEBUG and $oldAutoCommit;
427 $dbh->commit if $oldAutoCommit;
434 #plandata shit stays in replace for upgrades until after 2.0 (or edit
436 warn " saving legacy plandata" if $DEBUG;
437 my $plandata = $new->get('plandata');
438 $new->set('plandata', '');
440 warn " deleting old part_pkg_option records" if $DEBUG;
441 foreach my $part_pkg_option ( $old->part_pkg_option ) {
442 my $error = $part_pkg_option->delete;
444 $dbh->rollback if $oldAutoCommit;
449 warn " replacing part_pkg record" if $DEBUG;
450 my $error = $new->SUPER::replace($old, $options->{options} );
452 $dbh->rollback if $oldAutoCommit;
456 warn " inserting part_pkg_option records for plandata: $plandata|" if $DEBUG;
457 foreach my $part_pkg_option (
458 map { /^(\w+)=(.*)$/ or do { $dbh->rollback if $oldAutoCommit;
459 return "illegal plandata: $plandata";
461 new FS::part_pkg_option {
462 'pkgpart' => $new->pkgpart,
467 split("\n", $plandata)
469 my $error = $part_pkg_option->insert;
471 $dbh->rollback if $oldAutoCommit;
476 #trivial nit: not the most efficient to delete and reinsert
477 warn " deleting old part_pkg_currency records" if $DEBUG;
478 foreach my $part_pkg_currency ( $old->part_pkg_currency ) {
479 my $error = $part_pkg_currency->delete;
481 $dbh->rollback if $oldAutoCommit;
482 return "error deleting part_pkg_currency record: $error";
486 warn " inserting new part_pkg_currency records" if $DEBUG;
487 my %part_pkg_currency = %{ $options->{'part_pkg_currency'} || {} };
488 foreach my $key ( keys %part_pkg_currency ) {
489 $key =~ /^(.+)_([A-Z]{3})$/ or next;
490 my $part_pkg_currency = new FS::part_pkg_currency {
491 'pkgpart' => $new->pkgpart,
494 'optionvalue' => $part_pkg_currency{$key},
496 my $error = $part_pkg_currency->insert;
498 $dbh->rollback if $oldAutoCommit;
499 return "error inserting part_pkg_currency record: $error";
504 warn " replacing pkg_svc records" if $DEBUG;
505 my $pkg_svc = $options->{'pkg_svc'};
506 my $hidden_svc = $options->{'hidden_svc'} || {};
507 my $bulk_skip = $options->{'bulk_skip'} || {};
508 if ( $pkg_svc ) { # if it wasn't passed, don't change existing pkg_svcs
509 foreach my $part_svc ( qsearch('part_svc', {} ) ) {
510 my $quantity = $pkg_svc->{$part_svc->svcpart} || 0;
511 my $hidden = $hidden_svc->{$part_svc->svcpart} || '';
512 my $bulk_skip = $bulk_skip->{$part_svc->svcpart} || '';
514 ( defined($options->{'primary_svc'}) && $options->{'primary_svc'}
515 && $options->{'primary_svc'} == $part_svc->svcpart
520 my $old_pkg_svc = qsearchs('pkg_svc', {
521 'pkgpart' => $old->pkgpart,
522 'svcpart' => $part_svc->svcpart,
525 my $old_quantity = 0;
526 my $old_primary_svc = '';
528 my $old_bulk_skip = '';
529 if ( $old_pkg_svc ) {
530 $old_quantity = $old_pkg_svc->quantity;
531 $old_primary_svc = $old_pkg_svc->primary_svc
532 if $old_pkg_svc->dbdef_table->column('primary_svc'); # is this needed?
533 $old_hidden = $old_pkg_svc->hidden;
534 $old_bulk_skip = $old_pkg_svc->old_bulk_skip;
537 next unless $old_quantity != $quantity
538 || $old_primary_svc ne $primary_svc
539 || $old_hidden ne $hidden
540 || $old_bulk_skip ne $bulk_skip;
542 my $new_pkg_svc = new FS::pkg_svc( {
543 'pkgsvcnum' => ( $old_pkg_svc ? $old_pkg_svc->pkgsvcnum : '' ),
544 'pkgpart' => $new->pkgpart,
545 'svcpart' => $part_svc->svcpart,
546 'quantity' => $quantity,
547 'primary_svc' => $primary_svc,
549 'bulk_skip' => $bulk_skip,
551 my $error = $old_pkg_svc
552 ? $new_pkg_svc->replace($old_pkg_svc)
553 : $new_pkg_svc->insert;
555 $dbh->rollback if $oldAutoCommit;
559 } #if $options->{pkg_svc}
561 my @part_pkg_vendor = $old->part_pkg_vendor;
562 my @current_exportnum = ();
563 if ( $options->{'part_pkg_vendor'} ) {
564 my($exportnum,$vendor_pkg_id);
565 while ( ($exportnum,$vendor_pkg_id)
566 = each %{$options->{'part_pkg_vendor'}} ) {
568 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
569 if($exportnum == $part_pkg_vendor->exportnum
570 && $vendor_pkg_id ne $part_pkg_vendor->vendor_pkg_id) {
571 $part_pkg_vendor->vendor_pkg_id($vendor_pkg_id);
572 my $error = $part_pkg_vendor->replace;
574 $dbh->rollback if $oldAutoCommit;
575 return "Error replacing part_pkg_vendor record: $error";
580 elsif($exportnum == $part_pkg_vendor->exportnum
581 && $vendor_pkg_id eq $part_pkg_vendor->vendor_pkg_id) {
586 unless ( $noinsert ) {
587 my $ppv = new FS::part_pkg_vendor( {
588 'pkgpart' => $new->pkgpart,
589 'exportnum' => $exportnum,
590 'vendor_pkg_id' => $vendor_pkg_id,
592 my $error = $ppv->insert;
594 $dbh->rollback if $oldAutoCommit;
595 return "Error inserting part_pkg_vendor record: $error";
598 push @current_exportnum, $exportnum;
601 foreach my $part_pkg_vendor ( @part_pkg_vendor ) {
602 unless ( grep($_ eq $part_pkg_vendor->exportnum, @current_exportnum) ) {
603 my $error = $part_pkg_vendor->delete;
605 $dbh->rollback if $oldAutoCommit;
606 return "Error deleting part_pkg_vendor record: $error";
611 # propagate changes to certain core fields
612 if ( $conf->exists('part_pkg-lineage') ) {
613 warn " propagating changes to family" if $DEBUG;
614 my $error = $new->propagate($old);
616 $dbh->rollback if $oldAutoCommit;
621 warn " committing transaction" if $DEBUG and $oldAutoCommit;
622 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
628 Checks all fields to make sure this is a valid package definition. If
629 there is an error, returns the error, otherwise returns false. Called by the
630 insert and replace methods.
636 warn "FS::part_pkg::check called on $self" if $DEBUG;
638 for (qw(setup recur plandata)) {
639 #$self->set($_=>0) if $self->get($_) =~ /^\s*$/; }
640 return "Use of $_ field is deprecated; set a plan and options: ".
642 if length($self->get($_));
646 if ( $self->dbdef_table->column('freq')->type =~ /(int)/i ) {
647 my $error = $self->ut_number('freq');
648 return $error if $error;
650 $self->freq =~ /^(\d+[hdw]?)$/
651 or return "Illegal or empty freq: ". $self->freq;
655 my @null_agentnum_right = ( 'Edit global package definitions' );
656 push @null_agentnum_right, 'One-time charge'
657 if $self->freq =~ /^0/;
658 push @null_agentnum_right, 'Customize customer package'
659 if $self->disabled eq 'Y'; #good enough
661 my $error = $self->ut_numbern('pkgpart')
662 || $self->ut_text('pkg')
663 || $self->ut_textn('comment')
664 || $self->ut_textn('promo_code')
665 || $self->ut_alphan('plan')
666 || $self->ut_enum('setuptax', [ '', 'Y' ] )
667 || $self->ut_enum('recurtax', [ '', 'Y' ] )
668 || $self->ut_textn('taxclass')
669 || $self->ut_enum('disabled', [ '', 'Y' ] )
670 || $self->ut_enum('custom', [ '', 'Y' ] )
671 || $self->ut_enum('no_auto', [ '', 'Y' ])
672 || $self->ut_enum('recur_show_zero', [ '', 'Y' ])
673 || $self->ut_enum('setup_show_zero', [ '', 'Y' ])
674 #|| $self->ut_moneyn('setup_cost')
675 #|| $self->ut_moneyn('recur_cost')
676 || $self->ut_floatn('setup_cost')
677 || $self->ut_floatn('recur_cost')
678 || $self->ut_floatn('pay_weight')
679 || $self->ut_floatn('credit_weight')
680 || $self->ut_numbern('taxproductnum')
681 || $self->ut_foreign_keyn('classnum', 'pkg_class', 'classnum')
682 || $self->ut_foreign_keyn('addon_classnum', 'pkg_class', 'classnum')
683 || $self->ut_foreign_keyn('taxproductnum',
684 'part_pkg_taxproduct',
688 ? $self->ut_foreign_keyn('agentnum', 'agent', 'agentnum' )
689 : $self->ut_agentnum_acl('agentnum', \@null_agentnum_right)
691 || $self->ut_numbern('fcc_ds0s')
692 || $self->ut_numbern('fcc_voip_class')
693 || $self->ut_numbern('delay_start')
694 || $self->ut_foreign_keyn('successor', 'part_pkg', 'pkgpart')
695 || $self->ut_foreign_keyn('family_pkgpart', 'part_pkg', 'pkgpart')
696 || $self->SUPER::check
698 return $error if $error;
700 return 'Unknown plan '. $self->plan
701 unless exists($plans{$self->plan});
703 my $conf = new FS::Conf;
704 return 'Taxclass is required'
705 if ! $self->taxclass && $conf->exists('require_taxclasses');
710 =item supersede OLD [, OPTION => VALUE ... ]
712 Inserts this package as a successor to the package OLD. All options are as
713 for C<insert>. After inserting, disables OLD and sets the new package as its
719 my ($new, $old, %options) = @_;
722 $new->set('pkgpart' => '');
723 $new->set('family_pkgpart' => $old->family_pkgpart);
724 warn " inserting successor package\n" if $DEBUG;
725 $error = $new->insert(%options);
726 return $error if $error;
728 warn " disabling superseded package\n" if $DEBUG;
729 $old->set('successor' => $new->pkgpart);
730 $old->set('disabled' => 'Y');
731 $error = $old->SUPER::replace; # don't change its options/pkg_svc records
732 return $error if $error;
734 warn " propagating changes to family" if $DEBUG;
735 $new->propagate($old);
740 If any of certain fields have changed from OLD to this package, then,
741 for all packages in the same lineage as this one, sets those fields
742 to their values in this package.
746 my @propagate_fields = (
747 qw( pkg classnum setup_cost recur_cost taxclass
748 setuptax recurtax pay_weight credit_weight
756 map { $_ => $new->get($_) }
757 grep { $new->get($_) ne $old->get($_) }
761 my @part_pkg = qsearch('part_pkg', {
762 'family_pkgpart' => $new->family_pkgpart
765 foreach my $part_pkg ( @part_pkg ) {
766 my $pkgpart = $part_pkg->pkgpart;
767 next if $pkgpart == $new->pkgpart; # don't modify $new
768 warn " propagating to pkgpart $pkgpart\n" if $DEBUG;
769 foreach ( keys %fields ) {
770 $part_pkg->set($_, $fields{$_});
772 # SUPER::replace to avoid changing non-core fields
773 my $error = $part_pkg->SUPER::replace;
774 push @error, "pkgpart $pkgpart: $error"
780 =item pkg_locale LOCALE
782 Returns a customer-viewable string representing this package for the given
783 locale, from the part_pkg_msgcat table. If the given locale is empty or no
784 localized string is found, returns the base pkg field.
789 my( $self, $locale ) = @_;
790 return $self->pkg unless $locale;
791 my $part_pkg_msgcat = $self->part_pkg_msgcat($locale) or return $self->pkg;
792 $part_pkg_msgcat->pkg;
795 =item part_pkg_msgcat LOCALE
797 Like pkg_locale, but returns the FS::part_pkg_msgcat object itself.
801 sub part_pkg_msgcat {
802 my( $self, $locale ) = @_;
803 qsearchs( 'part_pkg_msgcat', {
804 pkgpart => $self->pkgpart,
809 =item pkg_comment [ OPTION => VALUE... ]
811 Returns an (internal) string representing this package. Currently,
812 "pkgpart: pkg - comment", is returned. "pkg - comment" may be returned in the
813 future, omitting pkgpart. The comment will have '(CUSTOM) ' prepended if
816 If the option nopkgpart is true then the "pkgpart: ' is omitted.
824 #$self->pkg. ' - '. $self->comment;
825 #$self->pkg. ' ('. $self->comment. ')';
826 my $pre = $opt{nopkgpart} ? '' : $self->pkgpart. ': ';
827 my $custom_comment = $self->custom_comment(%opt);
828 $pre. $self->pkg. ( $custom_comment ? " - $custom_comment" : '' );
831 sub price_info { # safety, in case a part_pkg hasn't defined price_info
837 my $price_info = $self->price_info(@_);
838 ( $self->custom ? '(CUSTOM) ' : '' ).
840 ( ( ($self->custom || $self->comment) && $price_info ) ? ' - ' : '' ).
846 Returns the package class, as an FS::pkg_class object, or the empty string
847 if there is no package class.
849 =item addon_pkg_class
851 Returns the add-on package class, as an FS::pkg_class object, or the empty
852 string if there is no add-on package class.
856 sub addon_pkg_class {
858 if ( $self->addon_classnum ) {
859 qsearchs('pkg_class', { 'classnum' => $self->addon_classnum } );
867 Returns the package category name, or the empty string if there is no package
874 my $pkg_class = $self->pkg_class;
876 ? $pkg_class->categoryname
882 Returns the package class name, or the empty string if there is no package
889 my $pkg_class = $self->pkg_class;
891 ? $pkg_class->classname
895 =item addon_classname
897 Returns the add-on package class name, or the empty string if there is no
898 add-on package class.
902 sub addon_classname {
904 my $pkg_class = $self->addon_pkg_class;
906 ? $pkg_class->classname
912 Returns the associated agent for this event, if any, as an FS::agent object.
914 =item pkg_svc [ HASHREF | OPTION => VALUE ]
916 Returns all FS::pkg_svc objects (see L<FS::pkg_svc>) for this package
917 definition (with non-zero quantity).
919 One option is available, I<disable_linked>. If set true it will return the
920 services for this package definition alone, omitting services from any add-on
927 Returns all FS::type_pkgs objects (see L<FS::type_pkgs>) for this package
935 # #sort { $b->primary cmp $a->primary }
936 # grep { $_->quantity }
937 # qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
939 my $opt = ref($_[0]) ? $_[0] : { @_ };
940 my %pkg_svc = map { $_->svcpart => $_ }
941 grep { $_->quantity }
942 qsearch( 'pkg_svc', { 'pkgpart' => $self->pkgpart } );
944 unless ( $opt->{disable_linked} ) {
945 foreach my $dst_pkg ( map $_->dst_pkg, $self->svc_part_pkg_link ) {
946 my @pkg_svc = grep { $_->quantity }
947 qsearch( 'pkg_svc', { pkgpart=>$dst_pkg->pkgpart } );
948 foreach my $pkg_svc ( @pkg_svc ) {
949 if ( $pkg_svc{$pkg_svc->svcpart} ) {
950 my $quantity = $pkg_svc{$pkg_svc->svcpart}->quantity;
951 $pkg_svc{$pkg_svc->svcpart}->quantity($quantity + $pkg_svc->quantity);
953 $pkg_svc{$pkg_svc->svcpart} = $pkg_svc;
963 =item svcpart [ SVCDB ]
965 Returns the svcpart of the primary service definition (see L<FS::part_svc>)
966 associated with this package definition (see L<FS::pkg_svc>). Returns
967 false if there not a primary service definition or exactly one service
968 definition with quantity 1, or if SVCDB is specified and does not match the
969 svcdb of the service definition. SVCDB can be specified as a scalar table
970 name, such as 'svc_acct', or as an arrayref of possible table names.
975 my $pkg_svc = shift->_primary_pkg_svc(@_);
976 $pkg_svc ? $pkg_svc->svcpart : '';
979 =item part_svc [ SVCDB ]
981 Like the B<svcpart> method, but returns the FS::part_svc object (see
987 my $pkg_svc = shift->_primary_pkg_svc(@_);
988 $pkg_svc ? $pkg_svc->part_svc : '';
991 sub _primary_pkg_svc {
994 my $svcdb = scalar(@_) ? shift : [];
995 $svcdb = ref($svcdb) ? $svcdb : [ $svcdb ];
996 my %svcdb = map { $_=>1 } @$svcdb;
999 grep { !scalar(@$svcdb) || $svcdb{ $_->part_svc->svcdb } }
1002 my @pkg_svc = grep { $_->primary_svc =~ /^Y/i } @svcdb_pkg_svc;
1003 @pkg_svc = grep {$_->quantity == 1 } @svcdb_pkg_svc
1005 return '' if scalar(@pkg_svc) != 1;
1009 =item svcpart_unique_svcdb SVCDB
1011 Returns the svcpart of a service definition (see L<FS::part_svc>) matching
1012 SVCDB associated with this package definition (see L<FS::pkg_svc>). Returns
1013 false if there not a primary service definition for SVCDB or there are multiple
1014 service definitions for SVCDB.
1018 sub svcpart_unique_svcdb {
1019 my( $self, $svcdb ) = @_;
1020 my @svcdb_pkg_svc = grep { ( $svcdb eq $_->part_svc->svcdb ) } $self->pkg_svc;
1021 return '' if scalar(@svcdb_pkg_svc) != 1;
1022 $svcdb_pkg_svc[0]->svcpart;
1027 Returns a list of the acceptable payment types for this package. Eventually
1028 this should come out of a database table and be editable, but currently has the
1029 following logic instead:
1031 If the package is free, the single item B<BILL> is
1032 returned, otherwise, the single item B<CARD> is returned.
1034 (CHEK? LEC? Probably shouldn't accept those by default, prone to abuse)
1040 if ( $self->is_free ) {
1049 Returns true if this package is free.
1055 if ( $self->can('is_free_options') ) {
1056 not grep { $_ !~ /^\s*0*(\.0*)?\s*$/ }
1057 map { $self->option($_) }
1058 $self->is_free_options;
1060 warn "FS::part_pkg::is_free: FS::part_pkg::". $self->plan. " subclass ".
1061 "provides neither is_free_options nor is_free method; returning false";
1066 # whether the plan allows discounts to be applied to this package
1067 sub can_discount { 0; }
1069 # whether the plan allows changing the start date
1070 sub can_start_date { 1; }
1072 # the delay start date if present
1073 sub delay_start_date {
1076 my $delay = $self->delay_start or return '';
1078 # avoid timelocal silliness
1079 my $dt = DateTime->today(time_zone => 'local');
1080 $dt->add(days => $delay);
1084 sub can_currency_exchange { 0; }
1087 # moved to FS::Misc to make this accessible to other packages
1089 FS::Misc::pkg_freqs();
1094 Returns an english representation of the I<freq> field, such as "monthly",
1095 "weekly", "semi-annually", etc.
1101 my $freq = $self->freq;
1103 #my $freqs_href = $self->freqs_href;
1104 my $freqs_href = freqs_href();
1106 if ( exists($freqs_href->{$freq}) ) {
1107 $freqs_href->{$freq};
1109 my $interval = 'month';
1110 if ( $freq =~ /^(\d+)([hdw])$/ ) {
1111 my %interval = ( 'h' => 'hour', 'd'=>'day', 'w'=>'week' );
1112 $interval = $interval{$2};
1117 "every $freq ${interval}s";
1122 =item add_freq TIMESTAMP [ FREQ ]
1124 Adds a billing period of some frequency to the provided timestamp and
1125 returns the resulting timestamp, or -1 if the frequency could not be
1126 parsed (shouldn't happen). By default, the frequency of this package
1127 will be used; to override this, pass a different frequency as a second
1133 my( $self, $date, $freq ) = @_;
1134 $freq = $self->freq unless $freq;
1136 #change this bit to use Date::Manip? CAREFUL with timezones (see
1137 # mailing list archive)
1138 my ($sec,$min,$hour,$mday,$mon,$year) = (localtime($date) )[0,1,2,3,4,5];
1140 if ( $freq =~ /^\d+$/ ) {
1142 until ( $mon < 12 ) { $mon -= 12; $year++; }
1144 $mday = 28 if $mday > 28 && FS::Conf->new->exists('anniversary-rollback');
1146 } elsif ( $freq =~ /^(\d+)w$/ ) {
1148 $mday += $weeks * 7;
1149 } elsif ( $freq =~ /^(\d+)d$/ ) {
1152 } elsif ( $freq =~ /^(\d+)h$/ ) {
1159 timelocal_nocheck($sec,$min,$hour,$mday,$mon,$year);
1164 For backwards compatibility, returns the plandata field as well as all options
1165 from FS::part_pkg_option.
1171 carp "plandata is deprecated";
1173 $self->SUPER::plandata(@_);
1175 my $plandata = $self->get('plandata');
1176 my %options = $self->options;
1177 $plandata .= join('', map { "$_=$options{$_}\n" } keys %options );
1182 =item part_pkg_vendor
1184 Returns all vendor/external package ids as FS::part_pkg_vendor objects (see
1185 L<FS::part_pkg_vendor>).
1187 =item vendor_pkg_ids
1189 Returns a list of vendor/external package ids by exportnum
1193 sub vendor_pkg_ids {
1195 map { $_->exportnum => $_->vendor_pkg_id } $self->part_pkg_vendor;
1198 =item part_pkg_option
1200 Returns all options as FS::part_pkg_option objects (see
1201 L<FS::part_pkg_option>).
1205 Returns a list of option names and values suitable for assigning to a hash.
1211 map { $_->optionname => $_->optionvalue } $self->part_pkg_option;
1214 =item option OPTIONNAME [ QUIET ]
1216 Returns the option value for the given name, or the empty string. If a true
1217 value is passed as the second argument, warnings about missing the option
1223 my( $self, $opt, $ornull ) = @_;
1224 my $part_pkg_option =
1225 qsearchs('part_pkg_option', {
1226 pkgpart => $self->pkgpart,
1229 return $part_pkg_option->optionvalue if $part_pkg_option;
1230 my %plandata = map { /^(\w+)=(.*)$/; ( $1 => $2 ); }
1231 split("\n", $self->get('plandata') );
1232 return $plandata{$opt} if exists $plandata{$opt};
1233 cluck "WARNING: (pkgpart ". $self->pkgpart. ") Package def option $opt ".
1234 "not found in options or plandata!\n"
1239 =item part_pkg_currency [ CURRENCY ]
1241 Returns all currency options as FS::part_pkg_currency objects (see
1242 L<FS::part_pkg_currency>), or, if a currency is specified, only return the
1243 objects for that currency.
1247 sub part_pkg_currency {
1249 my %hash = ( 'pkgpart' => $self->pkgpart );
1250 $hash{'currency'} = shift if @_;
1251 qsearch('part_pkg_currency', \%hash );
1254 =item part_pkg_currency_options CURRENCY
1256 Returns a list of option names and values from FS::part_pkg_currency for the
1261 sub part_pkg_currency_options {
1263 map { $_->optionname => $_->optionvalue } $self->part_pkg_currency(shift);
1266 =item part_pkg_currency_option CURRENCY OPTIONNAME
1268 Returns the option value for the given name and currency.
1272 sub part_pkg_currency_option {
1273 my( $self, $currency, $optionname ) = @_;
1274 my $part_pkg_currency =
1275 qsearchs('part_pkg_currency', { 'pkgpart' => $self->pkgpart,
1276 'currency' => $currency,
1277 'optionname' => $optionname,
1280 #fatal if not found? that works for our use cases from
1281 #part_pkg/currency_fixed, but isn't how we would typically/expect the method
1282 #to behave. have to catch it there if we change it here...
1283 or die "Unknown price for ". $self->pkg_comment. " in $currency\n";
1285 $part_pkg_currency->optionvalue;
1288 =item bill_part_pkg_link
1290 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1294 sub bill_part_pkg_link {
1295 shift->_part_pkg_link('bill', @_);
1298 =item svc_part_pkg_link
1300 Returns the associated part_pkg_link records (see L<FS::part_pkg_link>).
1304 sub svc_part_pkg_link {
1305 shift->_part_pkg_link('svc', @_);
1308 =item supp_part_pkg_link
1310 Returns the associated part_pkg_link records of type 'supp' (supplemental
1315 sub supp_part_pkg_link {
1316 shift->_part_pkg_link('supp', @_);
1319 sub _part_pkg_link {
1320 my( $self, $type ) = @_;
1321 qsearch({ table => 'part_pkg_link',
1322 hashref => { 'src_pkgpart' => $self->pkgpart,
1323 'link_type' => $type,
1324 #protection against infinite recursive links
1325 'dst_pkgpart' => { op=>'!=', value=> $self->pkgpart },
1327 order_by => "ORDER BY hidden",
1331 sub self_and_bill_linked {
1332 shift->_self_and_linked('bill', @_);
1335 sub self_and_svc_linked {
1336 shift->_self_and_linked('svc', @_);
1339 sub _self_and_linked {
1340 my( $self, $type, $hidden ) = @_;
1344 foreach ( ( $self, map { $_->dst_pkg->_self_and_linked($type, $_->hidden) }
1345 $self->_part_pkg_link($type) ) )
1347 $_->hidden($hidden) if $hidden;
1354 =item part_pkg_taxoverride [ CLASS ]
1356 Returns all associated FS::part_pkg_taxoverride objects (see
1357 L<FS::part_pkg_taxoverride>). Limits the returned set to those
1358 of class CLASS if defined. Class may be one of 'setup', 'recur',
1359 the empty string (default), or a usage class number (see L<FS::usage_class>).
1360 When a class is specified, the empty string class (default) is returned
1361 if no more specific values exist.
1365 sub part_pkg_taxoverride {
1369 my $hashref = { 'pkgpart' => $self->pkgpart };
1370 $hashref->{'usage_class'} = $class if defined($class);
1371 my @overrides = qsearch('part_pkg_taxoverride', $hashref );
1373 unless ( scalar(@overrides) || !defined($class) || !$class ){
1374 $hashref->{'usage_class'} = '';
1375 @overrides = qsearch('part_pkg_taxoverride', $hashref );
1381 =item has_taxproduct
1383 Returns true if this package has any taxproduct associated with it.
1387 sub has_taxproduct {
1390 $self->taxproductnum ||
1391 scalar( grep { $_ =~/^usage_taxproductnum_/ && $self->option($_) }
1392 keys %{ {$self->options} }
1398 =item taxproduct [ CLASS ]
1400 Returns the associated tax product for this package definition (see
1401 L<FS::part_pkg_taxproduct>). CLASS may be one of 'setup', 'recur' or
1402 the usage classnum (see L<FS::usage_class>). Returns the default
1403 tax product for this record if the more specific CLASS value does
1412 my $part_pkg_taxproduct;
1414 my $taxproductnum = $self->taxproductnum;
1416 my $class_taxproductnum = $self->option("usage_taxproductnum_$class", 1);
1417 $taxproductnum = $class_taxproductnum
1418 if $class_taxproductnum
1421 $part_pkg_taxproduct =
1422 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1424 unless ($part_pkg_taxproduct || $taxproductnum eq $self->taxproductnum ) {
1425 $taxproductnum = $self->taxproductnum;
1426 $part_pkg_taxproduct =
1427 qsearchs( 'part_pkg_taxproduct', { 'taxproductnum' => $taxproductnum } );
1430 $part_pkg_taxproduct;
1433 =item taxproduct_description [ CLASS ]
1435 Returns the description of the associated tax product for this package
1436 definition (see L<FS::part_pkg_taxproduct>).
1440 sub taxproduct_description {
1442 my $part_pkg_taxproduct = $self->taxproduct(@_);
1443 $part_pkg_taxproduct ? $part_pkg_taxproduct->description : '';
1446 =item part_pkg_taxrate DATA_PROVIDER, GEOCODE, [ CLASS ]
1448 Returns the package to taxrate m2m records for this package in the location
1449 specified by GEOCODE (see L<FS::part_pkg_taxrate>) and usage class CLASS.
1450 CLASS may be one of 'setup', 'recur', or one of the usage classes numbers
1451 (see L<FS::usage_class>).
1455 sub _expand_cch_taxproductnum {
1458 my $part_pkg_taxproduct = $self->taxproduct($class);
1460 my ($a,$b,$c,$d) = ( $part_pkg_taxproduct
1461 ? ( split ':', $part_pkg_taxproduct->taxproduct )
1464 $a = '' unless $a; $b = '' unless $b; $c = '' unless $c; $d = '' unless $d;
1465 my $extra_sql = "AND ( taxproduct = '$a:$b:$c:$d'
1466 OR taxproduct = '$a:$b:$c:'
1467 OR taxproduct = '$a:$b:".":$d'
1468 OR taxproduct = '$a:$b:".":' )";
1469 map { $_->taxproductnum } qsearch( { 'table' => 'part_pkg_taxproduct',
1470 'hashref' => { 'data_vendor'=>'cch' },
1471 'extra_sql' => $extra_sql,
1476 sub part_pkg_taxrate {
1478 my ($data_vendor, $geocode, $class) = @_;
1481 my $extra_sql = 'WHERE part_pkg_taxproduct.data_vendor = '.
1482 dbh->quote($data_vendor);
1484 # CCH oddness in m2m
1485 $extra_sql .= ' AND ('.
1486 join(' OR ', map{ 'geocode = '. $dbh->quote(substr($geocode, 0, $_)) }
1490 # much more CCH oddness in m2m -- this is kludgy
1491 my @tpnums = $self->_expand_cch_taxproductnum($class);
1492 if (scalar(@tpnums)) {
1493 $extra_sql .= ' AND ('.
1494 join(' OR ', map{ "taxproductnum = $_" } @tpnums ).
1497 $extra_sql .= ' AND ( 0 = 1 )';
1500 my $addl_from = 'LEFT JOIN part_pkg_taxproduct USING ( taxproductnum )';
1501 my $order_by = 'ORDER BY taxclassnum, length(geocode) desc, length(taxproduct) desc';
1502 my $select = 'DISTINCT ON(taxclassnum) *, taxproduct';
1504 # should qsearch preface columns with the table to facilitate joins?
1505 qsearch( { 'table' => 'part_pkg_taxrate',
1506 'select' => $select,
1507 'hashref' => { # 'data_vendor' => $data_vendor,
1508 # 'taxproductnum' => $self->taxproductnum,
1510 'addl_from' => $addl_from,
1511 'extra_sql' => $extra_sql,
1512 'order_by' => $order_by,
1516 =item part_pkg_discount
1518 Returns the package to discount m2m records (see L<FS::part_pkg_discount>)
1521 =item part_pkg_usage
1523 Returns the voice usage pools (see L<FS::part_pkg_usage>) defined for
1528 Reblesses the object into the FS::part_pkg::PLAN class (if available), where
1529 PLAN is the object's I<plan> field. There should be better docs
1530 on how to create new price plans, but until then, see L</NEW PLAN CLASSES>.
1536 my $plan = $self->plan;
1538 cluck "no price plan found for pkgpart ". $self->pkgpart. "\n"
1542 return $self if ref($self) =~ /::$plan$/; #already blessed into plan subclass
1543 my $class = ref($self). "::$plan";
1544 warn "reblessing $self into $class" if $DEBUG > 1;
1547 bless($self, $class) unless $@;
1552 sub calc_setup { die 'no calc_setup for '. shift->plan. "\n"; }
1553 sub calc_recur { die 'no calc_recur for '. shift->plan. "\n"; }
1555 #fallback that return 0 for old legacy packages with no plan
1556 sub calc_remain { 0; }
1557 sub calc_units { 0; }
1559 #fallback for everything not based on flat.pm
1560 sub recur_temporality { 'upcoming'; }
1561 sub calc_cancel { 0; }
1563 #fallback for everything except bulk.pm
1564 sub hide_svc_detail { 0; }
1566 #fallback for packages that can't/won't summarize usage
1567 sub sum_usage { 0; }
1569 =item recur_cost_permonth CUST_PKG
1571 recur_cost divided by freq (only supported for monthly and longer frequencies)
1575 sub recur_cost_permonth {
1576 my($self, $cust_pkg) = @_;
1577 return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
1578 sprintf('%.2f', $self->recur_cost / $self->freq );
1581 =item cust_bill_pkg_recur CUST_PKG
1583 Actual recurring charge for the specified customer package from customer's most
1588 sub cust_bill_pkg_recur {
1589 my($self, $cust_pkg) = @_;
1590 my $cust_bill_pkg = qsearchs({
1591 'table' => 'cust_bill_pkg',
1592 'addl_from' => 'LEFT JOIN cust_bill USING ( invnum )',
1593 'hashref' => { 'pkgnum' => $cust_pkg->pkgnum,
1594 'recur' => { op=>'>', value=>'0' },
1596 'order_by' => 'ORDER BY cust_bill._date DESC,
1597 cust_bill_pkg.sdate DESC
1600 }) or return 0; #die "use cust_bill_pkg_recur credits with once_perinv condition";
1601 $cust_bill_pkg->recur;
1604 =item unit_setup CUST_PKG
1606 Returns the setup fee for one unit of the package.
1611 my ($self, $cust_pkg) = @_;
1612 $self->option('setup_fee') || 0;
1615 =item format OPTION DATA
1617 Returns data formatted according to the function 'format' described
1618 in the plan info. Returns DATA if no such function exists.
1623 my ($self, $option, $data) = (shift, shift, shift);
1624 if (exists($plans{$self->plan}->{fields}->{$option}{format})) {
1625 &{$plans{$self->plan}->{fields}->{$option}{format}}($data);
1631 =item parse OPTION DATA
1633 Returns data parsed according to the function 'parse' described
1634 in the plan info. Returns DATA if no such function exists.
1639 my ($self, $option, $data) = (shift, shift, shift);
1640 if (exists($plans{$self->plan}->{fields}->{$option}{parse})) {
1641 &{$plans{$self->plan}->{fields}->{$option}{parse}}($data);
1651 =head1 CLASS METHODS
1659 # Used by FS::Upgrade to migrate to a new database.
1661 sub _upgrade_data { # class method
1662 my($class, %opts) = @_;
1664 warn "[FS::part_pkg] upgrading $class\n" if $DEBUG;
1666 my @part_pkg = qsearch({
1667 'table' => 'part_pkg',
1668 'extra_sql' => "WHERE ". join(' OR ',
1669 'plan IS NULL', "plan = '' ",
1673 foreach my $part_pkg (@part_pkg) {
1675 unless ( $part_pkg->plan ) {
1676 $part_pkg->plan('flat');
1683 # now upgrade to the explicit custom flag
1685 @part_pkg = qsearch({
1686 'table' => 'part_pkg',
1687 'hashref' => { disabled => 'Y', custom => '' },
1688 'extra_sql' => "AND comment LIKE '(CUSTOM) %'",
1691 foreach my $part_pkg (@part_pkg) {
1692 my $new = new FS::part_pkg { $part_pkg->hash };
1694 my $comment = $part_pkg->comment;
1695 $comment =~ s/^\(CUSTOM\) //;
1696 $comment = '(none)' unless $comment =~ /\S/;
1697 $new->comment($comment);
1699 my $pkg_svc = { map { $_->svcpart => $_->quantity } $part_pkg->pkg_svc };
1700 my $primary = $part_pkg->svcpart;
1701 my $options = { $part_pkg->options };
1703 my $error = $new->replace( $part_pkg,
1704 'pkg_svc' => $pkg_svc,
1705 'primary_svc' => $primary,
1706 'options' => $options,
1708 die $error if $error;
1711 # set family_pkgpart on any packages that don't have it
1712 @part_pkg = qsearch('part_pkg', { 'family_pkgpart' => '' });
1713 foreach my $part_pkg (@part_pkg) {
1714 $part_pkg->set('family_pkgpart' => $part_pkg->pkgpart);
1715 my $error = $part_pkg->SUPER::replace;
1716 die $error if $error;
1719 my @part_pkg_option = qsearch('part_pkg_option',
1720 { 'optionname' => 'unused_credit',
1723 foreach my $old_opt (@part_pkg_option) {
1724 my $pkgpart = $old_opt->pkgpart;
1725 my $error = $old_opt->delete;
1726 die $error if $error;
1728 foreach (qw(unused_credit_cancel unused_credit_change)) {
1729 my $new_opt = new FS::part_pkg_option {
1730 'pkgpart' => $pkgpart,
1734 $error = $new_opt->insert;
1735 die $error if $error;
1739 # migrate use_disposition_taqua and use_disposition to disposition_in
1740 @part_pkg_option = qsearch('part_pkg_option',
1741 { 'optionname' => { op => 'LIKE',
1742 value => 'use_disposition%',
1746 my %newopts = map { $_->pkgpart => $_ }
1747 qsearch('part_pkg_option', { 'optionname' => 'disposition_in', } );
1748 foreach my $old_opt (@part_pkg_option) {
1749 my $pkgpart = $old_opt->pkgpart;
1750 my $newval = $old_opt->optionname eq 'use_disposition_taqua' ? '100'
1752 my $error = $old_opt->delete;
1753 die $error if $error;
1755 if ( exists($newopts{$pkgpart}) ) {
1756 my $opt = $newopts{$pkgpart};
1757 $opt->optionvalue($opt->optionvalue.",$newval");
1758 $error = $opt->replace;
1759 die $error if $error;
1761 my $new_opt = new FS::part_pkg_option {
1762 'pkgpart' => $pkgpart,
1763 'optionname' => 'disposition_in',
1764 'optionvalue' => $newval,
1766 $error = $new_opt->insert;
1767 die $error if $error;
1768 $newopts{$pkgpart} = $new_opt;
1772 # set any package with FCC voice lines to the "VoIP with broadband" category
1773 # for backward compatibility
1775 # recover from a bad upgrade bug
1776 my $upgrade = 'part_pkg_fcc_voip_class_FIX';
1777 if (!FS::upgrade_journal->is_done($upgrade)) {
1778 my $bad_upgrade = qsearchs('upgrade_journal',
1779 { upgrade => 'part_pkg_fcc_voip_class' }
1781 if ( $bad_upgrade ) {
1782 my $where = 'WHERE history_date <= '.$bad_upgrade->_date.
1783 ' AND history_date > '.($bad_upgrade->_date - 3600);
1784 my @h_part_pkg_option = map { FS::part_pkg_option->new($_->hashref) }
1787 'table' => 'h_part_pkg_option',
1789 'extra_sql' => "$where AND history_action = 'delete'",
1790 'order_by' => 'ORDER BY history_date ASC',
1792 my @h_pkg_svc = map { FS::pkg_svc->new($_->hashref) }
1795 'table' => 'h_pkg_svc',
1797 'extra_sql' => "$where AND history_action = 'replace_old'",
1798 'order_by' => 'ORDER BY history_date ASC',
1801 foreach my $deleted (@h_part_pkg_option, @h_pkg_svc) {
1802 my $pkgpart ||= $deleted->pkgpart;
1803 $opt{$pkgpart} ||= {
1809 if ( $deleted->isa('FS::part_pkg_option') ) {
1810 $opt{$pkgpart}{options}{ $deleted->optionname } = $deleted->optionvalue;
1812 my $svcpart = $deleted->svcpart;
1813 $opt{$pkgpart}{pkg_svc}{$svcpart} = $deleted->quantity;
1814 $opt{$pkgpart}{hidden_svc}{$svcpart} ||= $deleted->hidden;
1815 $opt{$pkgpart}{primary_svc} = $svcpart if $deleted->primary_svc;
1818 foreach my $pkgpart (keys %opt) {
1819 my $part_pkg = FS::part_pkg->by_key($pkgpart);
1820 my $error = $part_pkg->replace( $part_pkg->replace_old, $opt{$pkgpart} );
1822 die "error recovering damaged pkgpart $pkgpart:\n$error\n";
1825 } # $bad_upgrade exists
1826 else { # do the original upgrade, but correctly this time
1827 @part_pkg = qsearch('part_pkg', {
1828 fcc_ds0s => { op => '>', value => 0 },
1829 fcc_voip_class => ''
1831 foreach my $part_pkg (@part_pkg) {
1832 $part_pkg->set(fcc_voip_class => 2);
1833 my @pkg_svc = $part_pkg->pkg_svc;
1834 my %quantity = map {$_->svcpart, $_->quantity} @pkg_svc;
1835 my %hidden = map {$_->svcpart, $_->hidden } @pkg_svc;
1836 my $error = $part_pkg->replace(
1837 $part_pkg->replace_old,
1838 options => { $part_pkg->options },
1839 pkg_svc => \%quantity,
1840 hidden_svc => \%hidden,
1841 primary_svc => ($part_pkg->svcpart || ''),
1843 die $error if $error;
1846 FS::upgrade_journal->set_done($upgrade);
1851 =item curuser_pkgs_sql
1853 Returns an SQL fragment for searching for packages the current user can
1854 use, either via part_pkg.agentnum directly, or via agent type (see
1859 sub curuser_pkgs_sql {
1862 $class->_pkgs_sql( $FS::CurrentUser::CurrentUser->agentnums );
1866 =item agent_pkgs_sql AGENT | AGENTNUM, ...
1868 Returns an SQL fragment for searching for packages the provided agent or agents
1869 can use, either via part_pkg.agentnum directly, or via agent type (see
1874 sub agent_pkgs_sql {
1875 my $class = shift; #i'm a class method, not a sub (the question is... why??)
1876 my @agentnums = map { ref($_) ? $_->agentnum : $_ } @_;
1878 $class->_pkgs_sql(@agentnums); #is this why
1883 my( $class, @agentnums ) = @_;
1884 my $agentnums = join(',', @agentnums);
1888 ( agentnum IS NOT NULL AND agentnum IN ($agentnums) )
1889 OR ( agentnum IS NULL
1890 AND EXISTS ( SELECT 1
1892 LEFT JOIN agent_type USING ( typenum )
1893 LEFT JOIN agent AS typeagent USING ( typenum )
1894 WHERE type_pkgs.pkgpart = part_pkg.pkgpart
1895 AND typeagent.agentnum IN ($agentnums)
1913 #false laziness w/part_export & cdr
1915 foreach my $INC ( @INC ) {
1916 warn "globbing $INC/FS/part_pkg/*.pm\n" if $DEBUG;
1917 foreach my $file ( glob("$INC/FS/part_pkg/*.pm") ) {
1918 warn "attempting to load plan info from $file\n" if $DEBUG;
1919 $file =~ /\/(\w+)\.pm$/ or do {
1920 warn "unrecognized file in $INC/FS/part_pkg/: $file\n";
1924 my $info = eval "use FS::part_pkg::$mod; ".
1925 "\\%FS::part_pkg::$mod\::info;";
1927 die "error using FS::part_pkg::$mod (skipping): $@\n" if $@;
1930 unless ( keys %$info ) {
1931 warn "no %info hash found in FS::part_pkg::$mod, skipping\n";
1934 warn "got plan info from FS::part_pkg::$mod: $info\n" if $DEBUG;
1935 #if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1936 # warn "skipping disabled plan FS::part_pkg::$mod" if $DEBUG;
1939 $info{$mod} = $info;
1940 $info->{'weight'} ||= 0; # quiet warnings
1944 # copy one level deep to allow replacement of fields and fieldorder
1945 tie %plans, 'Tie::IxHash',
1946 map { my %infohash = %{ $info{$_} };
1948 sort { $info{$a}->{'weight'} <=> $info{$b}->{'weight'} }
1951 # inheritance of plan options
1952 foreach my $name (keys(%info)) {
1953 if (exists($info{$name}->{'disabled'}) and $info{$name}->{'disabled'}) {
1954 warn "skipping disabled plan FS::part_pkg::$name" if $DEBUG;
1955 delete $plans{$name};
1958 my $parents = $info{$name}->{'inherit_fields'} || [];
1959 my (%fields, %field_exists, @fieldorder);
1960 foreach my $parent ($name, @$parents) {
1961 if ( !exists($info{$parent}) ) {
1962 warn "$name tried to inherit from nonexistent '$parent'\n";
1965 %fields = ( # avoid replacing existing fields
1966 %{ $info{$parent}->{'fields'} || {} },
1969 foreach (@{ $info{$parent}->{'fieldorder'} || [] }) {
1971 next if $field_exists{$_};
1972 $field_exists{$_} = 1;
1973 # allow inheritors to remove inherited fields from the fieldorder
1974 push @fieldorder, $_ if !exists($fields{$_}) or
1975 !exists($fields{$_}->{'disabled'});
1978 $plans{$name}->{'fields'} = \%fields;
1979 $plans{$name}->{'fieldorder'} = \@fieldorder;
1989 =head1 NEW PLAN CLASSES
1991 A module should be added in FS/FS/part_pkg/ Eventually, an example may be
1992 found in eg/plan_template.pm. Until then, it is suggested that you use the
1993 other modules in FS/FS/part_pkg/ as a guide.
1997 The delete method is unimplemented.
1999 setup and recur semantics are not yet defined (and are implemented in
2000 FS::cust_bill. hmm.). now they're deprecated and need to go.
2004 part_pkg_taxrate is Pg specific
2006 replace should be smarter about managing the related tables (options, pkg_svc)
2010 L<FS::Record>, L<FS::cust_pkg>, L<FS::type_pkgs>, L<FS::pkg_svc>, L<Safe>.
2011 schema.html from the base documentation.