+my $addl_from = '
+ LEFT JOIN part_pkg USING ( pkgpart )
+ LEFT JOIN cust_pkg AS chgto ON ( chgto.change_to_pkgnum = cust_pkg.pkgnum )
+ LEFT JOIN cust_pkg AS chgfrom ON ( chgfrom.change_pkgnum = cust_pkg.pkgnum )
+';
+
+my $extra_sql =
+ ' AND cust_pkg.main_pkgnum IS NULL '. # supplemental package of something else
+ ' AND chgto.pkgnum IS NULL '. # ordered, not-yet-active change target
+ ' AND chgfrom.pkgnum IS NULL '; # canceled package changed into another
+
+unless ( $cgi->param('showoldpackages') ) {
+ my $years = $conf->config('cust_main-packages-years') || 2;
+ my $then = time - $years * 31556926; #60*60*24*365.2422 is close enough
+
+ $extra_sql .= " AND (
+ ( part_pkg.freq = '0'
+ AND ( cust_pkg.setup IS NULL OR cust_pkg.setup > $then )
+ )
+ OR ( part_pkg.freq != '0'
+ AND ( cust_pkg.cancel IS NULL OR cust_pkg.cancel > $then )
+ )
+ OR EXISTS ( SELECT 1 FROM cust_svc WHERE cust_svc.pkgnum = cust_pkg.pkgnum )
+ )";
+}
+
+if ( $cgi->param('classnum') =~ /^(\d+)$/ ) {
+ my $classnum = $1;
+ if ( $classnum == 0 ) {
+ $extra_sql .= " AND part_pkg.classnum IS NULL ";
+ } else {
+ $extra_sql .= " AND part_pkg.classnum = $classnum ";
+ }
+}
+
+if ( $cgi->param('status') =~ /^([\w ]+)$/ ) {
+ my $status = $1;
+ $extra_sql .= ' AND '. FS::cust_pkg->status_sql. " = '$status' ";
+}
+
+if ( $cgi->param('locationnum') =~ /^(\d+)$/ ) {
+ my $locationnum = $1;
+ $extra_sql .= " AND cust_pkg.locationnum = $locationnum ";
+}
+
+my $total_pkgs = $cust_main->all_pkgs;
+
+my $method = $hide_cancelled ? 'ncancelled_pkgs' : 'all_pkgs';
+my $num_pkgs = $cust_main->$method({
+ 'addl_from' => $addl_from,
+ 'extra_sql' => $extra_sql,
+});
+
+my $maxrecords = 10;
+my $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
+$cgi->delete('offset');
+
+my @packages = $cust_main->$method( {