-my $countrydefault = scalar($conf->config('countrydefault')) || 'US';
-my %conf_opt = (
- #for services.html and status.html
- 'cust_pkg-display_times' => $conf->exists('cust_pkg-display_times'),
-
- #for status.html
- 'cust_pkg-show_autosuspend' => $conf->exists('cust_pkg-show_autosuspend'),
-
- #for location.html
- 'countrydefault' => $countrydefault,
- 'statedefault' => ( scalar($conf->config('statedefault'))
- || ($countrydefault eq 'US' ? 'CA' : '') ),
- #for services.html
- 'svc_external-skip_manual' => $conf->exists('svc_external-skip_manual'),
- 'legacy_link' => $conf->exists('legacy_link'),
-);
-
-#subroutines
-
-sub get_packages {
- my $cust_main = shift or return undef;
- my $conf = shift;
-
- my $method;
- if ( $cgi->param('showcancelledpackages') eq '0' #see if it was set by me
- || ( $conf->exists('hidecancelledpackages')
- && ! $cgi->param('showcancelledpackages') )
- )
- {
- $method = 'ncancelled_pkgs';
- } else {
- $method = 'all_pkgs';
+my $cust_pkg_fields =
+ join(', ', map { "cust_pkg.$_ AS $_" } fields('cust_pkg') );
+
+my $part_pkg_fields =
+ join(', ', ( map { "part_pkg.$_ AS part_pkg_$_" } fields('part_pkg') ),
+ 'setup_option.optionvalue AS part_pkg__setup_fee',
+ 'recur_option.optionvalue AS part_pkg__recur_fee',
+ );
+
+my $group_by =
+ join(', ', map "cust_pkg.$_", fields('cust_pkg') ). ', '.
+ join(', ', map "part_pkg.$_", fields('part_pkg') );
+
+my $num_svcs = '( SELECT COUNT(*) FROM cust_svc '.
+ ' WHERE cust_svc.pkgnum = cust_pkg.pkgnum ) AS num_svcs';
+
+# don't exclude cancelled packages at this stage
+my @packages = $cust_main->all_pkgs( {
+ 'select' => "$cust_pkg_fields, $part_pkg_fields, $num_svcs",
+ 'addl_from' => qq{
+ LEFT JOIN part_pkg USING ( pkgpart )
+ LEFT JOIN part_pkg_option AS setup_option
+ ON ( cust_pkg.pkgpart = setup_option.pkgpart
+ AND setup_option.optionname = 'setup_fee' )
+ LEFT JOIN part_pkg_option AS recur_option
+ ON ( cust_pkg.pkgpart = recur_option.pkgpart
+ AND recur_option.optionname = 'recur_fee' )
+ },
+} );
+
+my $is_anything_hidden = 0; # optimization
+
+my %change_to_from; # target pkgnum => current cust_pkg, for future changes
+my %changed_from; # old pkgnum => new cust_pkg, for past changes
+my %supplementals_of; # main pkgnum => arrayref of supplementals
+
+foreach my $cust_pkg ( @packages ) {
+ my %hash = $cust_pkg->hash;
+ my %part_pkg = map { /^part_pkg_(.+)$/ or die; ( $1 => $hash{$_} ); }
+ grep { /^part_pkg_/ } keys %hash;
+ $cust_pkg->{'_pkgpart'} = new FS::part_pkg \%part_pkg;
+ if ( $cust_pkg->change_to_pkgnum ) {
+ $change_to_from{$cust_pkg->change_to_pkgnum} = $cust_pkg;
+ $is_anything_hidden = 1;
+ }
+ if ( $cust_pkg->change_pkgnum ) {
+ $changed_from{$cust_pkg->change_pkgnum} = $cust_pkg;
+ $is_anything_hidden = 1;
+ }
+ if ( $cust_pkg->main_pkgnum ) {
+ $supplementals_of{$cust_pkg->main_pkgnum} ||= [];
+ push @{ $supplementals_of{$cust_pkg->main_pkgnum} }, $cust_pkg;
+ $is_anything_hidden = 1;